| """Parse a model's C2 compile response into a typed ``Program`` (``docs/02`` §7). |
| |
| The model emits a JSON object with the program-envelope subset |
| (``dsl`` / ``program`` / ``referent_selector`` / |
| ``required_referent_cardinality``). Parsing is strict and never guesses: |
| |
| 1. JSON-parse (tolerating a surrounding code fence). |
| 2. Validate ``program`` and ``referent_selector`` against ``$defs/astNode``. |
| 3. Rebuild typed :class:`AstNode`s (numerics kept exact). |
| 4. Construct a :class:`Program` and run the P2 :func:`typecheck` (dangling |
| selector / type mismatch / scalar-vs-set cardinality). A rejection here is a |
| parse failure, not a silent accept. |
| |
| The single allowed *repair* (§7) is driven by the compiler: it re-asks the model |
| with the first-response errors and parses the second response. This module is |
| pure — ``parse_program_response`` makes no model call; it reports ``ok``/invalid |
| and the compiler maps the attempt index to ``parse_status``. |
| """ |
|
|
| from __future__ import annotations |
|
|
| from dataclasses import dataclass |
| from typing import Any |
|
|
| from ..dsl.ast import ( |
| AstNode, |
| Dsl, |
| Program, |
| ProgramError, |
| ast_node_from_dict, |
| validate_ast_node, |
| ) |
| from ..dsl.canonicalize import canonical_program_sha256 |
| from ..dsl.typecheck import TypecheckError, typecheck |
| from ..schema_io import parse_json |
| from ..sources.base import World |
|
|
|
|
| @dataclass(frozen=True) |
| class ParsedProgram: |
| """The outcome of parsing one model response (one attempt). |
| |
| ``ok`` is ``True`` iff a typed, type-checked :class:`Program` was produced. |
| ``canonical_program_sha256`` is filled only when ``ok`` (the §7.2 hash key). |
| """ |
|
|
| program: Program | None |
| ok: bool |
| errors: tuple[str, ...] |
| canonical_program_sha256: str | None |
|
|
|
|
| def parse_program_response( |
| raw: str, |
| *, |
| dsl: Dsl, |
| world: World, |
| base_id: str, |
| question_sha256: str, |
| choices_sha256: str, |
| ) -> ParsedProgram: |
| """Parse one model response into a typed program or report errors. |
| |
| Never raises on a malformed response — every failure is captured in |
| ``errors`` with ``ok=False`` so the compiler can drive the one repair. |
| """ |
| errors: list[str] = [] |
| try: |
| doc = parse_json(raw) |
| except Exception as exc: |
| return ParsedProgram(None, False, (f"json: {exc!r}",), None) |
| if not isinstance(doc, dict): |
| return ParsedProgram(None, False, ("response is not a JSON object",), None) |
|
|
| resp_dsl = doc.get("dsl", dsl) |
| if resp_dsl != dsl: |
| errors.append(f"dsl mismatch: response {resp_dsl!r} != request {dsl!r}") |
|
|
| program_node = _build_ast(doc.get("program"), "program", errors) |
| referent_node = _build_ast( |
| doc.get("referent_selector"), "referent_selector", errors, nullable=True |
| ) |
| required = doc.get("required_referent_cardinality", None) |
|
|
| if errors or program_node is None: |
| return ParsedProgram(None, False, tuple(errors), None) |
|
|
| try: |
| program = Program( |
| dsl=dsl, |
| program=program_node, |
| base_id=base_id, |
| question_sha256=question_sha256, |
| choices_sha256=choices_sha256, |
| compile_status="compiled", |
| referent_selector=referent_node, |
| required_referent_cardinality=_coerce_cardinality(required, errors), |
| ) |
| except ProgramError as exc: |
| errors.append(f"program construct: {exc!r}") |
| return ParsedProgram(None, False, tuple(errors), None) |
|
|
| try: |
| program = typecheck(program, world=world) |
| except TypecheckError as exc: |
| return ParsedProgram(None, False, (f"typecheck: {exc!r}",), None) |
| except ProgramError as exc: |
| return ParsedProgram(None, False, (f"program: {exc!r}",), None) |
|
|
| canon = canonical_program_sha256(program, world=world) |
| program = _replace(program, canonical_program_sha256=canon) |
| return ParsedProgram(program, True, (), canon) |
|
|
|
|
| def _build_ast( |
| value: Any, label: str, errors: list[str], *, nullable: bool = False |
| ) -> AstNode | None: |
| if value is None: |
| if nullable: |
| return None |
| errors.append(f"{label}: missing") |
| return None |
| try: |
| validate_ast_node(value) |
| except ProgramError as exc: |
| errors.append(f"{label}: {exc!r}") |
| return None |
| try: |
| return ast_node_from_dict(value) |
| except ProgramError as exc: |
| errors.append(f"{label}: {exc!r}") |
| return None |
|
|
|
|
| def _coerce_cardinality(value: Any, errors: list[str]) -> int | None: |
| if value is None: |
| return None |
| if isinstance(value, bool) or not isinstance(value, int): |
| errors.append(f"required_referent_cardinality must be int|null, got {value!r}") |
| return None |
| if value < 0: |
| errors.append(f"required_referent_cardinality must be >= 0, got {value!r}") |
| return None |
| return int(value) |
|
|
|
|
| def _replace(program: Program, *, canonical_program_sha256: str) -> Program: |
| from dataclasses import replace |
|
|
| return replace(program, canonical_program_sha256=canonical_program_sha256) |
|
|
|
|
| __all__ = ["ParsedProgram", "parse_program_response"] |
|
|