ml_switcheroo.testing.linter

Structural Validation Linter (The Anti-Pollution Check).

This module provides the StructuralLinter, a static analysis tool designed to verify that the output of a transpilation contains no artifacts from the source framework.

Detection Scope: 1. Direct Imports: Flags import torch or from flax import …. 2. Aliased Usage: Tracks import torch as t and flags subsequent calls like t.abs(). 3. Attribute Access: Flags torch.nn.Linear if torch is a forbidden root.

Classes

StructuralLinter

Scans CST for forbidden framework usage.

Functions

validate_transpilation(→ Tuple[bool, List[str]])

Facade to lint generated code against a specific source framework.

Module Contents

class ml_switcheroo.testing.linter.StructuralLinter(forbidden_roots: Set[str])[source]

Bases: libcst.CSTVisitor

Scans CST for forbidden framework usage.

forbidden_roots
violations: List[str] = []
check(code: str) List[str][source]

Runs the linter on a source string.

Parameters:

code – The Python source code to validate.

Returns:

A list of error messages. Empty if valid.

Return type:

List[str]

visit_Import(node: libcst.Import) None[source]

Checks import x, import x as y.

Logs violations if the root package is forbidden. Tracks aliases to detect usage later in the file.

Parameters:

node – The Import node.

leave_Import(node: libcst.Import) None[source]

Exits the import scope context.

Parameters:

node – The Import node being exited.

visit_ImportFrom(node: libcst.ImportFrom) None[source]

Checks from x import y.

Logs violations if the module root matches forbidden set.

Parameters:

node – The ImportFrom node.

leave_ImportFrom(node: libcst.ImportFrom) None[source]

Exits the import-from scope context.

Parameters:

node – The ImportFrom node being exited.

visit_Name(node: libcst.Name) None[source]

Checks usage of aliased forbidden variables (e.g. t.abs() where t is torch).

Ignores names inside import definition statements.

Parameters:

node – The Name node.

visit_Attribute(node: libcst.Attribute) None[source]

Checks attributes to provide more specific error messages (e.g. torch.abs).

If the left side of the attribute matches a forbidden alias, logs an error.

Parameters:

node – The Attribute node.

ml_switcheroo.testing.linter.validate_transpilation(code: str, source_fw: str) Tuple[bool, List[str]][source]

Facade to lint generated code against a specific source framework.

It automatically expands the source_fw into a set of forbidden roots including: 1. The framework itself (e.g. ‘torch’). 2. Known aliases (from adapter). 3. Inherited parents (e.g. ‘flax_nnx’ bans ‘jax’ too).

Parameters:
  • code – The generated python code.

  • source_fw – The framework that SHOULD have been removed (e.g., “torch”).

Returns:

(is_valid, list_of_errors)