Datasets:
File size: 12,096 Bytes
e1ced61 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 | """Immutable typed AST for the canonical question programs (``docs/02`` §7).
A question *program* is a tree of :class:`AstNode` values. The serialized form
conforms to ``schemas/compiled_program.schema.json`` ``$defs/astNode``::
{"op": <str>, "args": [<astNode | str | number | bool>, ...], "return_type": <str>?}
Design choices pinned by the spec:
* **Exact numerics.** Numeric literals are ``fractions.Fraction`` internally and
serialize to a *canonical rational string* (``5`` → ``"5"``, ``3/2`` →
``"3/2"``, ``"1.50"`` → ``"3/2"``), never a JSON float — so ``1.5`` and
``3/2`` collapse to one canonical form (``docs/02`` §3.2/§3.3 "exact rational
우선", "decimal string canonicalizer trailing-zero 제거"). A literal that would
lose precision as a float is therefore exact.
* **Uniform nodes.** Every meaningful operand is an :class:`AstNode`: compound
ops (``LOOKUP``, ``MEASURE``, …) and two leaf kinds — ``REF`` (an entity
reference with a stable id) and ``LITERAL`` (an atomic value). Bare atomic
``args`` are reserved for *field/key* strings (e.g. ``"value"``) that are not
themselves typed operands. This keeps the type checker uniform: it dispatches
on ``op`` and reads ``return_type``.
* **Immutability.`` :class:`AstNode` and :class:`Program` are frozen; ``args`` is
a tuple. Canonicalization returns new nodes rather than mutating.
The :class:`Program` envelope is the P2 structural record — it carries the AST,
the referent selector, the *declared* referent cardinality, the resolved
referenced node ids, and the canonical program hash. The full
``compiled_program`` record (``compile_id`` / ``compiler_role`` / ``model`` /
``request_sha256``) is the **P4 C2 model-compiler** record and is not produced
here.
"""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from fractions import Fraction
from functools import lru_cache
from typing import Any, Literal, Union
from ..ingest.base import IngestError
from ..paths import repo_root
from ..schema_io import load_schema, validate
Dsl = Literal["plotqa_dsl_v1", "geometry_dsl_v1", "table_dsl_v1", "clevr_dsl_v1"]
CompileStatus = Literal["compiled", "unsupported"]
# Leaf op markers. A leaf node carries exactly one atomic arg.
REF = "REF" # entity reference: args=(id_str,), return_type = entity kind
LITERAL = "LITERAL" # atomic value: args=(serialized_value,), return_type = value kind
# One positional operand of a node: a sub-node, or a bare atomic field/key.
Arg = Union["AstNode", str, int, Fraction, bool]
class ProgramError(IngestError):
"""Raised when an AST node or :class:`Program` is malformed or schema-invalid."""
# --- numeric canonicalization (§3.2/§3.3) ----------------------------------
def parse_number(value: str | int | Fraction) -> Fraction:
"""Parse a decimal/rational/integer into an exact reduced :class:`Fraction`.
Accepts ``"1.5"``, ``"3/2"``, ``"5"``, ``"5.0"`` and integers. ``Fraction``
reduces and exact-represents each so numerically-equal inputs compare equal.
"""
if isinstance(value, Fraction):
return value
if isinstance(value, int) and not isinstance(value, bool):
return Fraction(value)
return Fraction(str(value))
def canonical_number_str(value: str | int | Fraction) -> str:
"""Canonical exact-rational string of a numeric value (``docs/02`` §3.2).
Integers render as their decimal string (``5`` → ``"5"``); non-integer
rationals as ``"num/den"`` in lowest terms (``3/2`` → ``"3/2"``). Trailing
zeros are gone because the form is exact, not decimal. Two numerically-equal
inputs always produce the same string.
"""
frac = parse_number(value)
if frac.denominator == 1:
return str(frac.numerator)
return f"{frac.numerator}/{frac.denominator}"
# --- AST node ---------------------------------------------------------------
@dataclass(frozen=True)
class AstNode:
"""One immutable node of a question program (``compiled_program.schema.json`` astNode).
``op`` is the operator/predicate name (``LOOKUP``, ``MeasureOf``, ``REF``,
``LITERAL``, …). ``args`` is an order-significant tuple of sub-nodes and bare
atomic field keys. ``return_type`` is the typed result kind
(``value``/``series``/``point``/``angle``/``number``/…); it is the type the
checker and canonicalizer propagate.
"""
op: str
args: tuple[Arg, ...] = ()
return_type: str = ""
def to_ast_node_dict(self) -> dict[str, Any]:
"""Serialize to a dict conforming to ``$defs/astNode``."""
out: dict[str, Any] = {"op": self.op, "args": [_arg_to_dict(a) for a in self.args]}
if self.return_type:
out["return_type"] = self.return_type
return out
def is_ref(self) -> bool:
return self.op == REF
def is_literal(self) -> bool:
return self.op == LITERAL
def ref_id(self) -> str:
"""The stable entity id of a ``REF`` leaf (raises otherwise)."""
if not self.is_ref():
raise ProgramError(f"{self.op!r} node is not an entity reference")
if len(self.args) != 1 or not isinstance(self.args[0], str):
raise ProgramError(f"REF node must carry one string id, got {self.args!r}")
return self.args[0]
def _arg_to_dict(arg: Arg) -> Any:
if isinstance(arg, AstNode):
return arg.to_ast_node_dict()
if isinstance(arg, bool): # before int: bool is an int subclass
return arg
if isinstance(arg, int):
return arg
if isinstance(arg, Fraction):
# A bare numeric arg is serialized as its canonical exact string so it
# never degrades to a lossy float; builders normally wrap numerics in a
# LITERAL node, but this keeps a bare Fraction exact if it appears.
return canonical_number_str(arg)
if isinstance(arg, str):
return arg
raise ProgramError(f"unsupported AST arg type {type(arg)!r}")
def _arg_from_dict(arg: Any) -> Arg:
"""Inverse of :func:`_arg_to_dict`: rebuild one AST arg from model JSON."""
if isinstance(arg, Mapping): # nested astNode
return ast_node_from_dict(arg)
if isinstance(arg, bool): # before int: bool is an int subclass
return arg
if isinstance(arg, int):
return arg
if isinstance(arg, float):
return parse_number(str(arg)) # exact rational, never a lossy float
if isinstance(arg, str):
return arg
raise ProgramError(f"unsupported astNode arg {arg!r}")
def ast_node_from_dict(data: Mapping[str, Any]) -> AstNode:
"""Rebuild an :class:`AstNode` from a ``$defs/astNode``-shaped dict.
The inverse of :meth:`AstNode.to_ast_node_dict`, used by the C2 compiler
(P4) to parse a model's JSON program response into the typed AST. Numeric
args are kept exact (a JSON float becomes a :class:`~fractions.Fraction`).
Raises :class:`ProgramError` on a malformed node; call
:func:`validate_ast_node` first for schema-level errors.
"""
if not isinstance(data, Mapping):
raise ProgramError(f"astNode must be an object, got {type(data).__name__}")
op = data.get("op")
if not isinstance(op, str) or not op:
raise ProgramError("astNode requires a non-empty string 'op'")
raw_args = data.get("args", [])
if not isinstance(raw_args, list):
raise ProgramError("astNode 'args' must be an array")
args = tuple(_arg_from_dict(a) for a in raw_args)
return_type = str(data.get("return_type", "") or "")
return AstNode(op=op, args=args, return_type=return_type)
# --- leaf constructors ------------------------------------------------------
def ref(entity_id: str, *, return_type: str = "entity") -> AstNode:
"""Build an entity-reference leaf (``op=REF``, one string id arg)."""
if not entity_id:
raise ProgramError("entity reference id must be non-empty")
return AstNode(op=REF, args=(entity_id,), return_type=return_type)
def lit(value: str | int | Fraction | bool, *, return_type: str) -> AstNode:
"""Build an atomic-literal leaf.
Numerics (``return_type`` ``number``/``integer``) serialize via
:func:`canonical_number_str`; booleans as JSON booleans; expressions/strings
as their (pre-canonicalization) string form.
"""
if return_type in ("number", "integer"):
return AstNode(op=LITERAL, args=(canonical_number_str(value),), return_type=return_type)
if return_type == "boolean":
return AstNode(op=LITERAL, args=(bool(value),), return_type=return_type)
if return_type in ("expression", "string", "field"):
return AstNode(op=LITERAL, args=(str(value),), return_type=return_type)
raise ProgramError(f"unsupported literal return_type {return_type!r}")
# --- program envelope -------------------------------------------------------
@dataclass(frozen=True)
class Program:
"""The P2 structural program record for one normalized item.
``canonical_program_sha256`` is filled by
:func:`~explicit_learning.dsl.canonicalize.canonical_program_sha256`.
``constraint_channels`` carries geometry channel provenance (constraint
node key → ``text``/``visual``/``redundant``) for the P3 intervention layer;
it is **not** part of the schema-conforming envelope.
"""
dsl: Dsl
program: AstNode
base_id: str
question_sha256: str
choices_sha256: str
compile_status: CompileStatus
referent_selector: AstNode | None = None
required_referent_cardinality: int | None = None
referenced_node_ids: tuple[str, ...] = ()
canonical_program_sha256: str = ""
reason_code: str | None = None
constraint_channels: tuple[tuple[str, str], ...] = ()
def to_dict(self) -> dict[str, Any]:
"""The P2 program envelope (a subset of ``compiled_program``).
The ``program`` sub-dict conforms to ``$defs/astNode``; the envelope is
not itself a full ``compiled_program`` record (that needs P4's
``compile_id``/``compiler_role``/``model``).
"""
envelope: dict[str, Any] = {
"dsl": self.dsl,
"program": self.program.to_ast_node_dict(),
"base_id": self.base_id,
"question_sha256": self.question_sha256,
"choices_sha256": self.choices_sha256,
"compile_status": self.compile_status,
"referent_selector": (
self.referent_selector.to_ast_node_dict() if self.referent_selector else None
),
"required_referent_cardinality": self.required_referent_cardinality,
"referenced_node_ids": list(self.referenced_node_ids),
"canonical_program_sha256": self.canonical_program_sha256 or None,
}
if self.reason_code is not None:
envelope["reason_code"] = self.reason_code
return envelope
# --- schema validation ------------------------------------------------------
@lru_cache(maxsize=1)
def _compiled_program_schema() -> dict[str, Any]:
return load_schema(repo_root() / "schemas" / "compiled_program.schema.json")
@lru_cache(maxsize=1)
def _ast_node_schema() -> dict[str, Any]:
"""A standalone schema validating one ``astNode`` (with ``$defs`` in scope)."""
full = _compiled_program_schema()
return {"$schema": full.get("$schema", ""), "$defs": full["$defs"], "$ref": "#/$defs/astNode"}
def validate_ast_node(node: Mapping[str, Any] | AstNode) -> None:
"""Raise :class:`ProgramError` if ``node`` violates ``$defs/astNode``."""
instance = node.to_ast_node_dict() if isinstance(node, AstNode) else dict(node)
errors = validate(instance, _ast_node_schema())
if errors:
raise ProgramError("astNode failed schema validation: " + "; ".join(errors))
__all__ = [
"Arg",
"AstNode",
"CompileStatus",
"Dsl",
"LITERAL",
"Program",
"ProgramError",
"REF",
"ast_node_from_dict",
"canonical_number_str",
"lit",
"parse_number",
"ref",
"validate_ast_node",
]
|