varar-core 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
varar_core/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Pure functional core engine for var (parse → plan → execute, matcher, diffs, conformance)."""
2
+
3
+ __version__ = "0.0.0"
varar_core/ast.py ADDED
@@ -0,0 +1,141 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Union
5
+
6
+ from varar_core.span import Span
7
+
8
+
9
+ # Maps a block-text offset to its source offset. Block text is the raw
10
+ # source minus BLOCK markers only (list bullets, blockquote `>` prefixes),
11
+ # so a paragraph or list item has a single entry and a blockquote one entry
12
+ # per quoted line. Inline markup is never stripped — see
13
+ # doc/superpowers/specs/2026-07-06-explicit-inline-format-plugins-design.md.
14
+ @dataclass(frozen=True, slots=True)
15
+ class SegmentOffset:
16
+ text_offset: int
17
+ source_offset: int
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class Heading:
22
+ kind: str = "heading"
23
+ level: int = 0
24
+ text: str = ""
25
+ span: Span | None = None
26
+
27
+ def __post_init__(self) -> None:
28
+ if self.span is None:
29
+ raise TypeError("span is required")
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class Paragraph:
34
+ kind: str = "paragraph"
35
+ text: str = ""
36
+ span: Span | None = None
37
+ segment_map: tuple[SegmentOffset, ...] = ()
38
+
39
+ def __post_init__(self) -> None:
40
+ if self.span is None:
41
+ raise TypeError("span is required")
42
+
43
+
44
+ @dataclass(frozen=True, slots=True)
45
+ class ListItem:
46
+ kind: str = "list_item"
47
+ text: str = ""
48
+ span: Span | None = None
49
+ segment_map: tuple[SegmentOffset, ...] = ()
50
+ ordered: bool = False
51
+ marker_span: Span | None = None
52
+
53
+ def __post_init__(self) -> None:
54
+ if self.span is None:
55
+ raise TypeError("span is required")
56
+ if self.marker_span is None:
57
+ raise TypeError("marker_span is required")
58
+
59
+
60
+ @dataclass(frozen=True, slots=True)
61
+ class Blockquote:
62
+ kind: str = "blockquote"
63
+ text: str = ""
64
+ span: Span | None = None
65
+ segment_map: tuple[SegmentOffset, ...] = ()
66
+
67
+ def __post_init__(self) -> None:
68
+ if self.span is None:
69
+ raise TypeError("span is required")
70
+
71
+
72
+ @dataclass(frozen=True, slots=True)
73
+ class Row:
74
+ cells: tuple[str, ...] = ()
75
+ cell_spans: tuple[Span, ...] = ()
76
+ span: Span | None = None
77
+
78
+ def __post_init__(self) -> None:
79
+ if self.span is None:
80
+ raise TypeError("span is required")
81
+
82
+
83
+ @dataclass(frozen=True, slots=True)
84
+ class Table:
85
+ kind: str = "table"
86
+ span: Span | None = None
87
+ header: Row | None = None
88
+ rows: tuple[Row, ...] = ()
89
+
90
+ def __post_init__(self) -> None:
91
+ if self.span is None:
92
+ raise TypeError("span is required")
93
+ if self.header is None:
94
+ raise TypeError("header is required")
95
+
96
+
97
+ @dataclass(frozen=True, slots=True)
98
+ class Fence:
99
+ kind: str = "fence"
100
+ span: Span | None = None
101
+ info: str = ""
102
+ body: str = ""
103
+ body_span: Span | None = None
104
+
105
+ def __post_init__(self) -> None:
106
+ if self.span is None:
107
+ raise TypeError("span is required")
108
+ if self.body_span is None:
109
+ raise TypeError("body_span is required")
110
+
111
+
112
+ @dataclass(frozen=True, slots=True)
113
+ class ThematicBreak:
114
+ kind: str = "thematic_break"
115
+ span: Span | None = None
116
+
117
+ def __post_init__(self) -> None:
118
+ if self.span is None:
119
+ raise TypeError("span is required")
120
+
121
+
122
+ Block = Union[Heading, Paragraph, ListItem, Blockquote, Table, Fence, ThematicBreak]
123
+
124
+
125
+ @dataclass(frozen=True, slots=True)
126
+ class Example:
127
+ scope_stack: tuple[str, ...] = ()
128
+ span: Span | None = None
129
+ body: tuple[Block, ...] = ()
130
+
131
+ def __post_init__(self) -> None:
132
+ if self.span is None:
133
+ raise TypeError("span is required")
134
+
135
+
136
+ @dataclass(frozen=True, slots=True)
137
+ class VarDoc:
138
+ path: str = ""
139
+ source: str = ""
140
+ examples: tuple[Example, ...] = ()
141
+ orphan_attachments: tuple[Union[Table, Fence], ...] = ()
@@ -0,0 +1,23 @@
1
+ import json
2
+ from typing import Any
3
+
4
+
5
+ def canonical_stringify(value: Any) -> str:
6
+ """Serialize a value to canonical JSON format.
7
+
8
+ Produces output byte-for-byte compatible with JS:
9
+ JSON.stringify(sortKeys(value), null, 2) + "\\n"
10
+
11
+ - sort_keys=True: recursively sorts all object keys
12
+ - indent=2: 2-space indentation
13
+ - ensure_ascii=False: keeps non-ASCII characters raw (emojis, accents)
14
+ - separators=(",", ": "): compact separators matching JSON.stringify
15
+ - trailing newline appended
16
+ """
17
+ return json.dumps(
18
+ value,
19
+ sort_keys=True,
20
+ indent=2,
21
+ ensure_ascii=False,
22
+ separators=(",", ": ")
23
+ ) + "\n"
@@ -0,0 +1,183 @@
1
+ """cell_diff.py — port of typescript/packages/core/src/cell-diff.ts.
2
+
3
+ Pure functions and immutable types for comparing row/table step returns against
4
+ the authored Markdown cells.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+ from typing import Any, Sequence
10
+
11
+ from varar_core.ast import Table
12
+ from varar_core.span import Span
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class RowCheck:
17
+ """One checked column of one header-bound row: the input the comparison needs."""
18
+
19
+ column: str
20
+ value: str # the cell text, e.g. "9"
21
+ span: Span # the cell text's source range in the .md
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class CellDiff:
26
+ """The verdict for one checked column after comparing against the table."""
27
+
28
+ column: str
29
+ span: Span
30
+ expected: str
31
+ actual: str
32
+ ok: bool
33
+ # The raw pre-display values, present on the inline-parameter path (where
34
+ # comparison is deep equality over transformed values). Adapter-facing;
35
+ # never serialized into run results or conformance artifacts.
36
+ expected_value: Any = None
37
+ actual_value: Any = None
38
+ # True when the parameter type's ``format`` rendered ``actual`` — the
39
+ # display pair is document notation, and adapters should prefer it over
40
+ # the raw values in their expected/actual projection.
41
+ formatted: bool = False
42
+
43
+
44
+ def render_cell_value(value: Any) -> str:
45
+ """Display rules 2-4 of the mismatch-rendering chain.
46
+
47
+ Rule 1, the parameter type's ``format``, applies only on the
48
+ inline-parameter path — see param_diff.py. A string renders as-is, any
49
+ other primitive via ``str``, anything else via ``repr``. The ``repr``
50
+ fallback is port-native and deliberately outside conformance — bundles
51
+ that pin an object actual must use ``format``.
52
+ """
53
+ if isinstance(value, str):
54
+ return value
55
+ if value is None or isinstance(value, (bool, int, float)):
56
+ return str(value)
57
+ return repr(value)
58
+
59
+
60
+ def compare_row(
61
+ returned: Any,
62
+ checks: Sequence[RowCheck],
63
+ ) -> tuple[CellDiff, ...]:
64
+ """Compare a row step's returned dict against the row's cells.
65
+
66
+ Only columns present on *returned* are checked; the rest are inputs.
67
+ A non-dict return (including None) checks nothing.
68
+ """
69
+ if returned is None or not isinstance(returned, dict):
70
+ return ()
71
+ diffs: list[CellDiff] = []
72
+ for check in checks:
73
+ if check.column not in returned:
74
+ continue
75
+ actual = render_cell_value(returned[check.column])
76
+ diffs.append(
77
+ CellDiff(
78
+ column=check.column,
79
+ span=check.span,
80
+ expected=check.value,
81
+ actual=actual,
82
+ ok=actual == check.value,
83
+ )
84
+ )
85
+ return tuple(diffs)
86
+
87
+
88
+ class CellMismatchError(Exception):
89
+ """Raised when a header-bound row's returned columns don't all match.
90
+
91
+ Carries the mismatched cells so adapters can render/record them.
92
+ """
93
+
94
+ cells: tuple[CellDiff, ...]
95
+
96
+ def __init__(self, cells: Sequence[CellDiff]) -> None:
97
+ self.cells = tuple(cells)
98
+ msg = "; ".join(
99
+ f"{c.column}: expected {c.expected} but was {c.actual}" for c in self.cells
100
+ )
101
+ super().__init__(msg)
102
+
103
+
104
+ def is_cell_mismatch_error(e: object) -> bool:
105
+ return isinstance(e, CellMismatchError)
106
+
107
+
108
+ class ReturnShapeError(Exception):
109
+ """The step returned the wrong type or shape — an author mistake, not a value diff."""
110
+
111
+ def __init__(self, message: str) -> None:
112
+ super().__init__(message)
113
+
114
+
115
+ def compare_table(
116
+ returned: Any,
117
+ input_table: Table,
118
+ ) -> tuple[CellDiff, ...]:
119
+ """Compare a whole-table step's returned table against the input table.
120
+
121
+ *returned* may be:
122
+ - None → no checks (returns empty tuple)
123
+ - list[list] → positional (array-of-arrays)
124
+ - list[dict] → keyed by header cell (array-of-records)
125
+
126
+ Cells compare as exact strings (``str(value) == cell_text``).
127
+ Type/shape problems raise ``ReturnShapeError``.
128
+ """
129
+ if returned is None:
130
+ return ()
131
+ if not isinstance(returned, list):
132
+ raise ReturnShapeError(
133
+ f"expected a table (array of rows), got {type(returned).__name__}"
134
+ )
135
+
136
+ columns = input_table.header.cells # type: ignore[union-attr]
137
+ data_rows = input_table.rows
138
+
139
+ if len(returned) != len(data_rows):
140
+ raise ReturnShapeError(
141
+ f"expected {len(data_rows)} row(s), got {len(returned)}"
142
+ )
143
+
144
+ def _is_record(r: Any) -> bool:
145
+ return isinstance(r, dict)
146
+
147
+ all_arrays = all(isinstance(r, list) for r in returned)
148
+ all_records = all(_is_record(r) for r in returned)
149
+
150
+ if not all_arrays and not all_records:
151
+ raise ReturnShapeError("table rows must be all arrays or all objects")
152
+
153
+ diffs: list[CellDiff] = []
154
+ for i, row in enumerate(data_rows):
155
+ ret = returned[i]
156
+ if all_arrays:
157
+ cells_ret: list[Any] = ret
158
+ if len(cells_ret) != len(columns):
159
+ raise ReturnShapeError(
160
+ f"row {i}: expected {len(columns)} column(s), got {len(cells_ret)}"
161
+ )
162
+ for j, column in enumerate(columns):
163
+ if all_arrays:
164
+ actual_value = ret[j]
165
+ else:
166
+ rec: dict[str, Any] = ret
167
+ if column not in rec:
168
+ raise ReturnShapeError(f'row {i}: missing column "{column}"')
169
+ actual_value = rec[column]
170
+
171
+ expected = row.cells[j] if j < len(row.cells) else ""
172
+ actual = render_cell_value(actual_value)
173
+ span: Span = row.cell_spans[j] if j < len(row.cell_spans) else row.span # type: ignore[assignment]
174
+ diffs.append(
175
+ CellDiff(
176
+ column=column,
177
+ span=span,
178
+ expected=expected,
179
+ actual=actual,
180
+ ok=actual == expected,
181
+ )
182
+ )
183
+ return tuple(diffs)