"""Six-step AST canonicalization and the canonical program hash (``docs/02`` §7.2). Two programs are *semantically equivalent* iff their canonical ASTs hash equal. ``canonical_program_sha256`` is the integrity anchor reused by the C2 dual-compile exact-match (``canonical_program_exact_match``) and the executor (P3): 1. resolve entity names → stable IDs (via the world's label→id map); 2. numeric literal normalize (exact rational; expression → SymPy canonical); 3. commutative operand sort (per-DSL commutative ops, sorted by canonical JSON); 4. alias operator expand (per-DSL alias → canonical op name); 5. redundant cast/remove (per-DSL no-op identity casts collapse to their arg); 6. topological node ordering (children canonicalized before parents, so a parent's commutative sort is over already-canonical operands). Step 6 is structural in the recursion: each child is canonicalized before its parent, and the parent's commutative sort keys on the canonical (post-alias) op. The numbered order is the spec's conceptual order; alias-expansion is applied before the commutative sort so sort keys on the *canonical* operator, which is the operator commutativity is defined on. """ from __future__ import annotations from collections.abc import Mapping from dataclasses import dataclass from fractions import Fraction from typing import Any from ..hashing import canonical_json, canonical_json_hash from ..sources.base import World from .ast import LITERAL, REF, AstNode, Dsl, Program, canonical_number_str, parse_number # Per-DSL canonicalization profile (loaded lazily to avoid a circular import: # the dsl modules import this module to compute the canonical hash). @dataclass(frozen=True) class DslProfile: """Per-DSL canonicalization knobs.""" commutative_ops: frozenset[str] aliases: Mapping[str, str] identity_casts: frozenset[str] def profile(dsl: Dsl) -> DslProfile: """Load the canonicalization profile for one DSL (lazy import).""" if dsl == "plotqa_dsl_v1": from . import plotdsl return DslProfile(plotdsl.COMMUTATIVE_OPS, plotdsl.ALIASES, plotdsl.IDENTITY_CASTS) if dsl == "geometry_dsl_v1": from . import geometrydsl return DslProfile( geometrydsl.COMMUTATIVE_OPS, geometrydsl.ALIASES, geometrydsl.IDENTITY_CASTS ) if dsl == "table_dsl_v1": from . import tabledsl return DslProfile(tabledsl.COMMUTATIVE_OPS, tabledsl.ALIASES, tabledsl.IDENTITY_CASTS) if dsl == "clevr_dsl_v1": from . import clevrdsl return DslProfile(clevrdsl.COMMUTATIVE_OPS, clevrdsl.ALIASES, clevrdsl.IDENTITY_CASTS) raise ValueError(f"unknown DSL {dsl!r}") # --- world resolution (step 1) --------------------------------------------- def entity_ids(world: World | None) -> set[str]: """All stable entity ids declared by a world (``plot_world_v1`` / ``geometry_world_v1``).""" if not world: return set() ids: set[str] = set() for series in world.get("series", []) or []: if isinstance(series, Mapping) and series.get("id"): ids.add(str(series["id"])) for point in series.get("points", []) or [] if isinstance(series, Mapping) else []: if isinstance(point, Mapping) and point.get("id"): ids.add(str(point["id"])) for entity in world.get("entities", []) or []: if isinstance(entity, Mapping) and entity.get("id"): ids.add(str(entity["id"])) for obj in world.get("objects", []) or []: if isinstance(obj, Mapping) and obj.get("id"): ids.add(str(obj["id"])) return ids def entity_aliases(world: World | None) -> dict[str, str]: """Label → stable-id map for entity-name resolution (``docs/02`` §7.2 step 1). A plot series label resolves to its ``series:`` id; a geometry entity has no human label separate from its id, so it maps to itself. A referent that is already a stable id passes through unchanged. """ if not world: return {} aliases: dict[str, str] = {} for series in world.get("series", []) or []: if isinstance(series, Mapping) and series.get("id"): sid = str(series["id"]) aliases[sid] = sid label = series.get("label") if isinstance(label, str) and label: aliases[label] = sid for entity in world.get("entities", []) or []: if isinstance(entity, Mapping) and entity.get("id"): eid = str(entity["id"]) aliases[eid] = eid for obj in world.get("objects", []) or []: if isinstance(obj, Mapping) and obj.get("id"): oid = str(obj["id"]) aliases[oid] = oid return aliases def resolve_ref_id(node: AstNode, aliases: Mapping[str, str]) -> AstNode: """Step 1: replace a REF label with its stable id when a mapping exists.""" if not node.is_ref(): return node raw = node.ref_id() resolved = aliases.get(raw, raw) if resolved == raw: return node return AstNode(op=REF, args=(resolved,), return_type=node.return_type) # --- literal normalization (step 2) ---------------------------------------- def canonical_expression(expr: str) -> str: """Canonical SymPy form of an expression literal (``docs/02`` §3.3). ``sympy.expand`` + the default printer yields a term-ordered canonical string so ``"1 + x"`` and ``"x + 1"`` collapse. SymPy is imported lazily; if it is unavailable the literal is left untouched (P2 plot programs never need it). """ try: import sympy except ImportError: # pragma: no cover - sympy is pinned in requirements return expr try: expanded = sympy.expand(sympy.sympify(expr)) except Exception: # noqa: BLE001 - sympify raises varied types on bad input return expr return str(sympy.sstr(expanded)) def normalize_literal(node: AstNode) -> AstNode: """Step 2: re-canonicalize a LITERAL's value (numeric exact / expression SymPy).""" if not node.is_literal() or not node.args: return node value = node.args[0] if node.return_type in ("number", "integer") and isinstance(value, str): return AstNode( op=LITERAL, args=(canonical_number_str(parse_number(value)),), return_type=node.return_type, ) if node.return_type == "expression" and isinstance(value, str): return AstNode( op=LITERAL, args=(canonical_expression(value),), return_type=node.return_type ) return node # --- canonicalize ---------------------------------------------------------- def canonicalize(node: AstNode, *, dsl: Dsl, world: World | None = None) -> AstNode: """Apply the §7.2 six steps to ``node`` and return a new canonical :class:`AstNode`.""" prof = profile(dsl) aliases = entity_aliases(world) def canon(n: AstNode) -> AstNode: # Step 1: resolve entity references. n = resolve_ref_id(n, aliases) # Leaves: step 2 only. if n.is_ref(): return n if n.is_literal(): return normalize_literal(n) # Compound: canonicalize children first (step 6 — topological ordering). canon_args = tuple(_canonicalize_arg(a, canon) for a in n.args) # Step 4: alias operator expand (before sort so sort keys on the canonical op). op = prof.aliases.get(n.op, n.op) # Step 5: redundant cast/remove — a single-arg identity cast collapses. if ( op in prof.identity_casts and len(canon_args) == 1 and isinstance(canon_args[0], AstNode) ): return canon_args[0] # Step 3: commutative operand sort over canonical child JSON. if op in prof.commutative_ops: canon_args = _sort_commutative(canon_args) return AstNode(op=op, args=canon_args, return_type=n.return_type) return canon(node) def _canonicalize_arg(arg: Any, canon: Any) -> Any: """Canonicalize a sub-node; pass bare atomic field keys through untouched.""" if isinstance(arg, AstNode): return canon(arg) return arg def _sort_commutative(args: tuple[Any, ...]) -> tuple[Any, ...]: """Sort commutative operands by their canonical-JSON serialization (stable).""" return tuple(sorted(args, key=_arg_sort_key)) def _arg_sort_key(arg: Any) -> str: if isinstance(arg, AstNode): return canonical_json(arg.to_ast_node_dict()) if isinstance(arg, bool): return canonical_json(arg) if isinstance(arg, int): return canonical_json(arg) if isinstance(arg, Fraction): return canonical_number_str(arg) if isinstance(arg, str): return canonical_json(arg) return canonical_json(str(arg)) # --- canonical program hash ------------------------------------------------ def canonical_program_sha256(program: Program, *, world: World | None = None) -> str: """SHA-256 of the canonical program AST (+ referent selector). The hash input is the canonical-JSON of:: {"program": , "referent_selector": } This is the exact-match key for ``canonical_program_exact_match`` (P4) and the program fingerprint reused by the executor (P3). Equivalent programs hash equal; non-equivalent programs hash differently. """ canon_program = canonicalize(program.program, dsl=program.dsl, world=world) referent: dict[str, Any] | None = None if program.referent_selector is not None: canon_ref = canonicalize(program.referent_selector, dsl=program.dsl, world=world) referent = canon_ref.to_ast_node_dict() return canonical_json_hash( {"program": canon_program.to_ast_node_dict(), "referent_selector": referent} ) def programs_equivalent(a: Program, b: Program, *, world: World | None = None) -> bool: """True iff two programs share a canonical program hash (§7.2 canonical match).""" return canonical_program_sha256(a, world=world) == canonical_program_sha256(b, world=world) __all__ = [ "DslProfile", "canonical_expression", "canonical_program_sha256", "canonicalize", "entity_aliases", "entity_ids", "profile", "programs_equivalent", "resolve_ref_id", ]