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
letshadowing creates a fresh ordinal at the same block depth. - Go: Short variable declarations (
:=) follow Go’s block-level redeclaration vs. shadowing rules. - JavaScript / TypeScript:
vardeclarations hoist to the enclosing function scope whileletandconststay 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
F2andF3stay 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 totalNormalized 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.0Pillar 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:
- 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. - Floating-Point Guard (
containsFloatOperand): IEEE-754 floating-point math is not strictly associative ((a + b) + ccan round differently froma + (b + c)). WhencontainsFloatOperandsees floats, Canontra skips associative re-grouping. - Commutative and Associative Sorting: Pure non-trapping integer and bitwise operands of
+,*,&,|,^,==, and!=are flattened and sorted canonically by operand hash (hashExprB). - Comparison Flipping and Double Negation:
b > anormalizes toa < b,b >= anormalizes toa <= b, andnot (not x)simplifies tox. - Unordered Sets and Dicts: Pure
ExprSetitems and pureExprDictkeys 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:
- Dominator Trees and Frontiers:
computeDominators(Lengauer-Tarjan) andcomputeDominanceFrontiersbuild exact dominator relationships for basic blocks and SSA def-use analysis. - Branch Condition Normalization:
if (!cond) { B } else { A }normalizes toif (cond) { A } else { B };if (a != b) { B } else { A }normalizes toif (a == b) { A } else { B }. - Early-Exit Guard Lifting and Dead Code Pruning: Early-return guard clauses align with equivalent nested
if/elseblocks, and unreachable statements immediately afterreturn,raise,break, orcontinueare removed. - Reverse Post-Order (RPO) Numbering (
canonicalizeCFGRPO): Basic blocks are numbered0throughk-1in RPO order from entry, withCondTrueedges ordered beforeCondFalse.
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 (i32vsu64,f32vsf64) and tracks mutability (&Tvs&mut T). - Ordered Tuples (
TypeTuple): Preserves tuple element order ((A, B)(B, A)). - Flattened Unions and Intersections: Nested unions and intersections flatten, deduplicate, and sort via
makeUnionandmakeIntersection:(A | B) | (C | A)becomesA | B | C. - Positional Generic Names and Sorted Records: Generic type parameters map to positional names (
α0,α1) while keeping bounds and Go~Tconstraints; 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\x07stores a compact per-file summary sobuildWholeRepoCallGraphFromSummaries(112.9 uson 10 modules) andbuildWholeRepoDataFlowFromSummaries(65.6 uson 10 modules) rebuild repository graphs without re-parsing unchanged files. - Fast Impact Slicing:
backwardReachabilityConeandcomputeBatchImpactSliceCSRtrace multi-file PR blast radii in microseconds.