File size: 5,179 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
"""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:  # noqa: BLE001 - any JSON failure is a parse failure
        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"]