"""Typed compiler for CLEVR's source-native functional programs. Official CLEVR questions contain a dependency-indexed program whose nodes have ``inputs``, ``function`` and ``value_inputs`` fields. The compiler below translates that DAG into the project's immutable :class:`AstNode` tree without guessing or calling a model. Only the released CLEVR function vocabulary is accepted; malformed arity, forward references, and unknown functions produce an ``unsupported`` program with a deterministic reason code. """ from __future__ import annotations from collections.abc import Mapping, Sequence from dataclasses import dataclass, replace from typing import Any from ..ingest.base import NormalizedItem from ..sources.base import World from .ast import AstNode, Dsl, Program, ProgramError, lit from .canonicalize import canonical_program_sha256 from .typecheck import OpSignature, typecheck DSL: Dsl = "clevr_dsl_v1" @dataclass(frozen=True) class _NativeSignature: inputs: tuple[str, ...] return_type: str value_input: str | None = None _NATIVE_SIGNATURES: dict[str, _NativeSignature] = { "scene": _NativeSignature((), "object_set"), "filter_color": _NativeSignature(("object_set",), "object_set", "string"), "filter_material": _NativeSignature(("object_set",), "object_set", "string"), "filter_shape": _NativeSignature(("object_set",), "object_set", "string"), "filter_size": _NativeSignature(("object_set",), "object_set", "string"), "unique": _NativeSignature(("object_set",), "object"), "relate": _NativeSignature(("object",), "object_set", "string"), "same_color": _NativeSignature(("object",), "object_set"), "same_material": _NativeSignature(("object",), "object_set"), "same_shape": _NativeSignature(("object",), "object_set"), "same_size": _NativeSignature(("object",), "object_set"), "union": _NativeSignature(("object_set", "object_set"), "object_set"), "intersect": _NativeSignature(("object_set", "object_set"), "object_set"), "count": _NativeSignature(("object_set",), "integer"), "exist": _NativeSignature(("object_set",), "boolean"), "query_color": _NativeSignature(("object",), "string"), "query_material": _NativeSignature(("object",), "string"), "query_shape": _NativeSignature(("object",), "string"), "query_size": _NativeSignature(("object",), "string"), "equal_color": _NativeSignature(("string", "string"), "boolean"), "equal_material": _NativeSignature(("string", "string"), "boolean"), "equal_shape": _NativeSignature(("string", "string"), "boolean"), "equal_size": _NativeSignature(("string", "string"), "boolean"), "equal_integer": _NativeSignature(("integer", "integer"), "boolean"), "equal_object": _NativeSignature(("object", "object"), "boolean"), "less_than": _NativeSignature(("integer", "integer"), "boolean"), "greater_than": _NativeSignature(("integer", "integer"), "boolean"), } SIGNATURES: dict[str, OpSignature] = { name.upper(): OpSignature( arg_types=signature.inputs + ((signature.value_input,) if signature.value_input is not None else ()), return_type=signature.return_type, commutative=name in { "union", "intersect", "equal_color", "equal_material", "equal_shape", "equal_size", "equal_integer", "equal_object", }, selector_kind=( "scalar" if name == "unique" else "set" if signature.return_type == "object_set" else "none" ), ) for name, signature in _NATIVE_SIGNATURES.items() } COMMUTATIVE_OPS = frozenset( name.upper() for name, signature in SIGNATURES.items() if signature.commutative ) ALIASES: dict[str, str] = {} IDENTITY_CASTS: frozenset[str] = frozenset() _UNSUPPORTED_NODE = AstNode(op="UNSUPPORTED", args=(), return_type="") def compile_clevr(item: NormalizedItem, world: World) -> Program: """Compile the native program stored on a normalized CLEVR item.""" raw_steps = item.provenance.get("program") if not isinstance(raw_steps, list): return _unsupported(item, "native_program_missing") return compile_clevr_steps( raw_steps, world=world, base_id=item.base_id, question_sha256=item.question_sha256, choices_sha256=item.choices_sha256, ) def compile_clevr_steps( raw_steps: Sequence[Mapping[str, Any]], *, world: World, base_id: str, question_sha256: str, choices_sha256: str, ) -> Program: """Compile one official ``program`` array into a typed tree. Every dependency must point backward to an already compiled node. This preserves the official DAG evaluation order and makes forward references or cycles a typed reject instead of relying on Python recursion behavior. """ nodes: list[AstNode] = [] unique_nodes: list[AstNode] = [] try: if not raw_steps: raise ProgramError("native_program_empty") for index, raw in enumerate(raw_steps): if not isinstance(raw, Mapping): raise ProgramError(f"node_{index}_not_object") function = raw.get("function") if not isinstance(function, str) or function not in _NATIVE_SIGNATURES: raise ProgramError(f"node_{index}_unsupported_function_{function}") signature = _NATIVE_SIGNATURES[function] raw_inputs = raw.get("inputs") raw_values = raw.get("value_inputs") if not isinstance(raw_inputs, list) or any( isinstance(value, bool) or not isinstance(value, int) for value in raw_inputs ): raise ProgramError(f"node_{index}_inputs_not_integer_array") if len(raw_inputs) != len(signature.inputs): raise ProgramError(f"node_{index}_{function}_input_arity_{len(raw_inputs)}") if any(value < 0 or value >= index for value in raw_inputs): raise ProgramError(f"node_{index}_has_forward_or_invalid_input") if not isinstance(raw_values, list): raise ProgramError(f"node_{index}_value_inputs_not_array") expected_values = 1 if signature.value_input is not None else 0 if len(raw_values) != expected_values: raise ProgramError(f"node_{index}_{function}_value_arity_{len(raw_values)}") args: list[AstNode] = [nodes[value] for value in raw_inputs] if signature.value_input is not None: value = raw_values[0] if not isinstance(value, str) or not value: raise ProgramError(f"node_{index}_{function}_value_not_string") args.append(lit(value, return_type=signature.value_input)) node = AstNode( op=function.upper(), args=tuple(args), return_type=signature.return_type, ) nodes.append(node) if function == "unique": unique_nodes.append(node) referent = unique_nodes[-1] if unique_nodes else None candidate = Program( dsl=DSL, program=nodes[-1], base_id=base_id, question_sha256=question_sha256, choices_sha256=choices_sha256, compile_status="compiled", referent_selector=referent, required_referent_cardinality=1 if referent is not None else None, ) checked = typecheck(candidate, world=world) return replace( checked, canonical_program_sha256=canonical_program_sha256(checked, world=world), ) except (ProgramError, ValueError) as exc: return Program( dsl=DSL, program=_UNSUPPORTED_NODE, base_id=base_id, question_sha256=question_sha256, choices_sha256=choices_sha256, compile_status="unsupported", reason_code=_reason(str(exc)), ) def _unsupported(item: NormalizedItem, reason: str) -> Program: return Program( dsl=DSL, program=_UNSUPPORTED_NODE, base_id=item.base_id, question_sha256=item.question_sha256, choices_sha256=item.choices_sha256, compile_status="unsupported", reason_code=reason, ) def _reason(message: str) -> str: return ( message.strip() .lower() .replace(" ", "_") .replace(":", "_") .replace("'", "") .replace('"', "") ) __all__ = [ "ALIASES", "COMMUTATIVE_OPS", "DSL", "IDENTITY_CASTS", "SIGNATURES", "compile_clevr", "compile_clevr_steps", ]