Skip to content

Canonicalization Pillars

Before hashing, Canontra converts each parsed file into one unified canonical form called CanonicalProgram (toCanonicalProgram in Canontra.Normalize.Normalize). Doing this once in a single pass avoids repeated AST walks and double parsing in computeManifest.

Pillar 1: Language-Specific Local Variable Normalization (Canontra.Normalize.Alpha)

Section titled “Pillar 1: Language-Specific Local Variable Normalization (Canontra.Normalize.Alpha)”

Renaming a local variable inside a private function body does not change how a program behaves or break any caller. canonicalizeAlphaModuleForLang replaces bound local names with deterministic scope coordinates (@v<depth>.<ordinal>) while following each language’s real scoping rules:

  • Rust: Sequential let shadowing creates a fresh ordinal at the same block depth.
  • Go: Short variable declarations (:=) follow Go’s block-level redeclaration vs. shadowing rules.
  • JavaScript / TypeScript: var declarations hoist to the enclosing function scope while let and const stay block-scoped.
  • Python: Follows Python LEGB lookup plus PEP 572 walrus (:=) hoisting out of comprehensions into the enclosing function scope.
  • Public Contracts Untouched: Exported function names, class/interface/trait names, public parameter names, and imports are never renamed, so F2 and F3 stay strictly sensitive to API changes.
# Before normalization (two versions differing in local names)
def sum_positive(items: list[int]) -> int:
total = 0 # vs: accumulator = 0
for item in items: # vs: for value in items:
if item > 0:
total = total + item
return total

Normalized internal form (F1 and F_DF match bit-for-bit):

fn sum_positive(items: list[int]) -> int:
let @v0.0 = 0
for @v1.0 in items:
if (0 < @v1.0):
@v0.0 = (@v0.0 + @v1.0)
return @v0.0

Pillar 2: Purity and IEEE-754 Guarded Expression Sorting (Canontra.Normalize.Algebraic)

Section titled “Pillar 2: Purity and IEEE-754 Guarded Expression Sorting (Canontra.Normalize.Algebraic)”

Equivalent expressions written in different order (such as a + b vs b + a, or b > a vs a < b) should match only when reordering is mathematically safe. Canontra guards every rewrite with isNonTrappingPureExpr and containsFloatOperand:

  1. Safety Guard (isNonTrappingPureExpr): Expressions containing function calls (ExprCall), await, yield, walrus assignments (:=), potentially trapping division/indexing, short-circuiting boolean operators, or string + concatenation are never reordered.
  2. Floating-Point Guard (containsFloatOperand): IEEE-754 floating-point math is not strictly associative ((a + b) + c can round differently from a + (b + c)). When containsFloatOperand sees floats, Canontra skips associative re-grouping.
  3. Commutative and Associative Sorting: Pure non-trapping integer and bitwise operands of +, *, &, |, ^, ==, and != are flattened and sorted canonically by operand hash (hashExprB).
  4. Comparison Flipping and Double Negation: b > a normalizes to a < b, b >= a normalizes to a <= b, and not (not x) simplifies to x.
  5. Unordered Sets and Dicts: Pure ExprSet items and pure ExprDict keys are sorted into ascending canonical order.
b > a and not (not flag) ==> a < b and flag
(y + x) * factor ==> factor * (x + y) [pure, non-float]
{3, 1, 2} ==> {1, 2, 3}

Pillar 3: Control-Flow Graph Canonicalization (Canontra.Analysis.CFGCanonical)

Section titled “Pillar 3: Control-Flow Graph Canonicalization (Canontra.Analysis.CFGCanonical)”

Flipping an if/else condition or using an early return guard changes the surface syntax without changing execution paths. CFGCanonical puts control flow into a uniform graph shape before hashing F_CF and F_DF:

  1. Dominator Trees and Frontiers: computeDominators (Lengauer-Tarjan) and computeDominanceFrontiers build exact dominator relationships for basic blocks and SSA def-use analysis.
  2. Branch Condition Normalization: if (!cond) { B } else { A } normalizes to if (cond) { A } else { B }; if (a != b) { B } else { A } normalizes to if (a == b) { A } else { B }.
  3. Early-Exit Guard Lifting and Dead Code Pruning: Early-return guard clauses align with equivalent nested if/else blocks, and unreachable statements immediately after return, raise, break, or continue are removed.
  4. Reverse Post-Order (RPO) Numbering (canonicalizeCFGRPO): Basic blocks are numbered 0 through k-1 in RPO order from entry, with CondTrue edges ordered before CondFalse.

Pillar 4: ABI-Precise Structural Type Contracts (Canontra.Analysis.TypeContract)

Section titled “Pillar 4: ABI-Precise Structural Type Contracts (Canontra.Analysis.TypeContract)”

F_T captures public type shapes across Python, TypeScript, Go, and Rust while ignoring cosmetic type-syntax differences:

  • Exact Scalar Widths and Mutability (Mutability): Keeps fixed-width scalar types distinct (i32 vs u64, f32 vs f64) and tracks mutability (&T vs &mut T).
  • Ordered Tuples (TypeTuple): Preserves tuple element order ((A, B) ≠\neq (B, A)).
  • Flattened Unions and Intersections: Nested unions and intersections flatten, deduplicate, and sort via makeUnion and makeIntersection: (A | B) | (C | A) becomes A | B | C.
  • Positional Generic Names and Sorted Records: Generic type parameters map to positional names (α0, α1) while keeping bounds and Go ~T constraints; record literal fields sort by field name.

Pillar 5: Package Resolution, Summary Cache, and Compact CSR Graphs (WholeRepoGraph, CSRGraph)

Section titled “Pillar 5: Package Resolution, Summary Cache, and Compact CSR Graphs (WholeRepoGraph, CSRGraph)”

Whole-repository call graphs (F_WCG) and data-flow graphs (F_WDF) are stored as flat unboxed Compressed Sparse Row (CSR) arrays (csrRowOffsets :: Vector Word32, csrColIndices :: Vector Word32, csrEdgeFlags :: Vector Word16) with Set/IntMap deduplication instead of pointer-heavy maps:

  • Go Package Merging and JS/TS Barrel Exports: Combines Go files in the same package directory and resolves TypeScript/JavaScript re-export barrels to prevent false name-only matches.
  • Summary-Backed Warm Synthesis (FileGraphSummary): CNTR\x07 stores a compact per-file summary so buildWholeRepoCallGraphFromSummaries (112.9 us on 10 modules) and buildWholeRepoDataFlowFromSummaries (65.6 us on 10 modules) rebuild repository graphs without re-parsing unchanged files.
  • Fast Impact Slicing: backwardReachabilityCone and computeBatchImpactSliceCSR trace multi-file PR blast radii in microseconds.