cs-object 1.0.0__tar.gz → 1.1.0__tar.gz

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.
Files changed (52) hide show
  1. {cs_object-1.0.0/src/cs_object.egg-info → cs_object-1.1.0}/PKG-INFO +1 -1
  2. {cs_object-1.0.0 → cs_object-1.1.0}/pyproject.toml +1 -1
  3. {cs_object-1.0.0 → cs_object-1.1.0/src/cs_object.egg-info}/PKG-INFO +1 -1
  4. {cs_object-1.0.0 → cs_object-1.1.0}/src/cs_object.egg-info/SOURCES.txt +2 -0
  5. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/__main__.py +5 -0
  6. cs_object-1.1.0/src/cso_python/artifact_plan.py +289 -0
  7. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/authoring.md +16 -0
  8. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/describe.py +2 -2
  9. cs_object-1.1.0/tests/test_artifact_plan.py +204 -0
  10. {cs_object-1.0.0 → cs_object-1.1.0}/LICENSE +0 -0
  11. {cs_object-1.0.0 → cs_object-1.1.0}/NOTICE +0 -0
  12. {cs_object-1.0.0 → cs_object-1.1.0}/README.md +0 -0
  13. {cs_object-1.0.0 → cs_object-1.1.0}/setup.cfg +0 -0
  14. {cs_object-1.0.0 → cs_object-1.1.0}/src/cs_object.egg-info/dependency_links.txt +0 -0
  15. {cs_object-1.0.0 → cs_object-1.1.0}/src/cs_object.egg-info/top_level.txt +0 -0
  16. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/__init__.py +0 -0
  17. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/annotations.py +0 -0
  18. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/authoring.py +0 -0
  19. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/bindings.py +0 -0
  20. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/comparison.py +0 -0
  21. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/definitions.py +0 -0
  22. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/execution.py +0 -0
  23. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/exporter.py +0 -0
  24. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/external.py +0 -0
  25. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/function_calls.py +0 -0
  26. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/glyphs.py +0 -0
  27. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/guidance.py +0 -0
  28. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/handles.py +0 -0
  29. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/notation.py +0 -0
  30. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/planner.py +0 -0
  31. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/py.typed +0 -0
  32. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/source.py +0 -0
  33. {cs_object-1.0.0 → cs_object-1.1.0}/src/cso_python/source_plan.py +0 -0
  34. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_authoring_v2.py +0 -0
  35. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_binding_types.py +0 -0
  36. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_bindings.py +0 -0
  37. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_boolean_call_outputs.py +0 -0
  38. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_boolean_tables.py +0 -0
  39. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_cli.py +0 -0
  40. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_definitions.py +0 -0
  41. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_describe.py +0 -0
  42. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_execution.py +0 -0
  43. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_exporter.py +0 -0
  44. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_external_functions.py +0 -0
  45. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_function_calls.py +0 -0
  46. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_guidance.py +0 -0
  47. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_handle_reuse.py +0 -0
  48. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_method_table.py +0 -0
  49. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_notation.py +0 -0
  50. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_notation_preflight.py +0 -0
  51. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_numeric_declarations.py +0 -0
  52. {cs_object-1.0.0 → cs_object-1.1.0}/tests/test_source_plan.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cs-object
3
- Version: 1.0.0
3
+ Version: 1.1.0
4
4
  Summary: Constrained Python authoring and CalculationSourceObject JSON export
5
5
  Author: Viktar B
6
6
  License: Apache-2.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "cs-object"
7
- version = "1.0.0"
7
+ version = "1.1.0"
8
8
  description = "Constrained Python authoring and CalculationSourceObject JSON export"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cs-object
3
- Version: 1.0.0
3
+ Version: 1.1.0
4
4
  Summary: Constrained Python authoring and CalculationSourceObject JSON export
5
5
  Author: Viktar B
6
6
  License: Apache-2.0
@@ -9,6 +9,7 @@ src/cs_object.egg-info/top_level.txt
9
9
  src/cso_python/__init__.py
10
10
  src/cso_python/__main__.py
11
11
  src/cso_python/annotations.py
12
+ src/cso_python/artifact_plan.py
12
13
  src/cso_python/authoring.md
13
14
  src/cso_python/authoring.py
14
15
  src/cso_python/bindings.py
@@ -27,6 +28,7 @@ src/cso_python/planner.py
27
28
  src/cso_python/py.typed
28
29
  src/cso_python/source.py
29
30
  src/cso_python/source_plan.py
31
+ tests/test_artifact_plan.py
30
32
  tests/test_authoring_v2.py
31
33
  tests/test_binding_types.py
32
34
  tests/test_bindings.py
@@ -23,6 +23,10 @@ def main(argv: list[str] | None = None) -> int:
23
23
  from .describe import describe_from_argv
24
24
 
25
25
  return describe_from_argv(arguments[1:])
26
+ if arguments and arguments[0] == "artifact-plan":
27
+ from .artifact_plan import artifact_plan_from_argv
28
+
29
+ return artifact_plan_from_argv(arguments[1:])
26
30
  parser = argparse.ArgumentParser(
27
31
  prog="python -m cso_python",
28
32
  description="Author and export constrained Python calculations. Export is not numerical verification.",
@@ -40,6 +44,7 @@ def main(argv: list[str] | None = None) -> int:
40
44
  commands.add_parser(
41
45
  "describe", help="Describe a calculation without executing authored code."
42
46
  )
47
+ commands.add_parser("artifact-plan", help="Compile a browser calculation plan.")
43
48
  commands.add_parser("authoring", help="Read version-matched calculation authoring guidance.")
44
49
  commands.add_parser("bindings", help="Generate typed calculation handles")
45
50
  add_export_arguments(export)
@@ -0,0 +1,289 @@
1
+ """Compile the browser arithmetic subset using the CSO source expression planner."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import ast
7
+ import json
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import NoReturn
11
+
12
+ from .annotations import Annotation, symbol_annotation
13
+ from .definitions import Definitions
14
+ from .describe import describe_input
15
+ from .notation import notation_identity, parse_notation
16
+ from .source import (
17
+ Capture,
18
+ CapturedModule,
19
+ Json,
20
+ SourceError,
21
+ authoring_name,
22
+ kwargs,
23
+ numeric_kind,
24
+ span,
25
+ )
26
+ from .source_plan import OPS, lower_expression
27
+
28
+ BROWSER_OPERATIONS = {*OPS.values(), "fg.uminus"}
29
+
30
+
31
+ def unsupported(module: CapturedModule, node: ast.AST, message: str) -> NoReturn:
32
+ raise SourceError(
33
+ "UNSUPPORTED_ARTIFACT_FEATURE", message, location=span(module.id, node)
34
+ )
35
+
36
+
37
+ def titles(module: CapturedModule, function: ast.FunctionDef) -> tuple[str, str]:
38
+ decorators = {authoring_name(call.func): call for call in function.decorator_list}
39
+ if len(function.decorator_list) != 2 or decorators.keys() != {
40
+ "calculation",
41
+ "section",
42
+ }:
43
+ unsupported(
44
+ module,
45
+ function,
46
+ "A browser calculation requires one @calculation and one @section.",
47
+ )
48
+ calculation = kwargs(
49
+ decorators["calculation"], module.id, {"id", "title"}, {"id", "title"}
50
+ )
51
+ section = kwargs(
52
+ decorators["section"], module.id, {"id", "title", "root"}, {"title"}
53
+ )
54
+ if not section.get("root", True):
55
+ unsupported(
56
+ module,
57
+ decorators["section"],
58
+ "The browser calculation section must be a root section.",
59
+ )
60
+ return calculation["title"], section["title"]
61
+
62
+
63
+ def display_metadata(
64
+ module: CapturedModule, node: ast.AST, declared: Annotation, glyphs: set[str]
65
+ ) -> Json:
66
+ spec = declared.metadata
67
+ if spec is None:
68
+ unsupported(
69
+ module,
70
+ node,
71
+ "Declare the input's glyph, description and unit in its signature.",
72
+ )
73
+ extra = spec.keys() - {"glyph", "description", "unit", "comment"}
74
+ if extra:
75
+ unsupported(
76
+ module,
77
+ node,
78
+ f"Unsupported browser symbol metadata: {', '.join(sorted(extra))}.",
79
+ )
80
+ for field in ("unit", "glyph"):
81
+ if field == "unit" and not spec[field]:
82
+ continue
83
+ parsed = parse_notation(spec[field])
84
+ if not parsed.ok:
85
+ raise SourceError(
86
+ "INVALID_NOTATION",
87
+ f"Invalid {field}: {parsed.diagnostic.message}",
88
+ location=span(module.id, node),
89
+ )
90
+ if field == "glyph":
91
+ identity = notation_identity(parsed.value)
92
+ if identity in glyphs:
93
+ raise SourceError(
94
+ "DUPLICATE_GLYPH",
95
+ f"Duplicate glyph {spec[field]!r}.",
96
+ location=span(module.id, node),
97
+ )
98
+ glyphs.add(identity)
99
+ return spec
100
+
101
+
102
+ def formula_nodes(
103
+ module: CapturedModule,
104
+ function: ast.FunctionDef,
105
+ parameters: set[str],
106
+ expr: ast.expr,
107
+ available: set[str],
108
+ ) -> list[Json]:
109
+ # A call like documented_result(2) lowers to a literal. Reject it before that
110
+ # projection, which would lose the distinction between opaque results and constants.
111
+ for operand in ast.walk(expr):
112
+ if isinstance(operand, (ast.Call, ast.Subscript)):
113
+ unsupported(
114
+ module,
115
+ operand,
116
+ "Browser formulas support arithmetic on quantities and numeric literals.",
117
+ )
118
+ projected = []
119
+ for node in lower_expression(module, function, parameters, expr, given=False):
120
+ key, mode = node["key"], node["mode"]
121
+ if mode == "LITERAL":
122
+ literal = node["literal"]
123
+ projected.append(
124
+ {
125
+ "key": key,
126
+ "mode": mode,
127
+ "value": literal["value"],
128
+ "numericKind": literal["numericKind"],
129
+ **({"draft": node["draft"]} if "draft" in node else {}),
130
+ }
131
+ )
132
+ elif mode == "SYMBOL":
133
+ name = node["ref"]["name"]
134
+ if name not in available:
135
+ raise SourceError(
136
+ "MISSING_REFERENCE",
137
+ f"Unknown or forward quantity reference {name!r}.",
138
+ location=node["location"],
139
+ )
140
+ projected.append({"key": key, "mode": mode, "name": name})
141
+ elif mode == "FUNCTION" and node["funcSpec"]["id"] in BROWSER_OPERATIONS:
142
+ projected.append(
143
+ {
144
+ "key": key,
145
+ "mode": mode,
146
+ "functionId": node["funcSpec"]["id"],
147
+ "args": [arg["key"] for arg in node["funcArgs"]],
148
+ }
149
+ )
150
+ else:
151
+ unsupported(
152
+ module, expr, "Browser formulas support +, -, *, /, ** and unary minus."
153
+ )
154
+ return projected
155
+
156
+
157
+ def build_artifact_plan(source: Path, function: str) -> Json:
158
+ if not function.isidentifier():
159
+ raise SourceError(
160
+ "INVALID_USAGE", "Function must be an identifier.", stage="usage"
161
+ )
162
+ capture = Capture(source)
163
+ module = capture.load(capture.entry)
164
+ definition = Definitions(capture).get(module.path, function)
165
+ fn = definition.function
166
+ title, section_title = titles(module, fn)
167
+ glyphs: set[str] = set()
168
+ parameters = set(definition.parameters)
169
+ available = parameters.copy()
170
+ inputs = []
171
+ for name, parameter in definition.parameters.items():
172
+ metadata = display_metadata(module, parameter.node, parameter.declared, glyphs)
173
+ item = describe_input(name, parameter, module.id)
174
+ if "comment" in metadata:
175
+ item["comment"] = metadata["comment"]
176
+ if "default" in item:
177
+ item["defaultNumericKind"] = numeric_kind(item["default"])
178
+ inputs.append(item)
179
+
180
+ items: list[Json] = []
181
+ text_ids: set[str] = set()
182
+ for node in fn.body:
183
+ if isinstance(node, ast.Return):
184
+ continue # Definitions has checked this is the final output dictionary.
185
+ if (
186
+ isinstance(node, ast.Expr)
187
+ and isinstance(node.value, ast.Call)
188
+ and authoring_name(node.value.func) == "text"
189
+ ):
190
+ if "text" not in module.imported:
191
+ unsupported(module, node, "Import text from cso_python.")
192
+ data = kwargs(node.value, module.id, {"id", "content"}, {"id", "content"})
193
+ if data["id"] in text_ids:
194
+ raise SourceError(
195
+ "DUPLICATE_IDENTITY",
196
+ f"Duplicate text ID {data['id']!r}.",
197
+ location=span(module.id, node),
198
+ )
199
+ text_ids.add(data["id"])
200
+ items.append({"kind": "text", "content": data["content"]})
201
+ continue
202
+ if not (
203
+ isinstance(node, ast.AnnAssign)
204
+ and isinstance(node.target, ast.Name)
205
+ and node.value is not None
206
+ ):
207
+ unsupported(
208
+ module,
209
+ node,
210
+ f"Browser calculations do not support {type(node).__name__} here. Use text or a named arithmetic step.",
211
+ )
212
+ name = node.target.id
213
+ if name in available or name in module.imported or name.startswith("__cso_"):
214
+ raise SourceError(
215
+ "DUPLICATE_IDENTITY",
216
+ f"Quantity name {name!r} is already used or reserved.",
217
+ location=span(module.id, node),
218
+ )
219
+ declared = symbol_annotation(node, module.id, module.aliases)
220
+ spec = display_metadata(module, node, declared, glyphs)
221
+ nodes = formula_nodes(module, fn, parameters, node.value, available)
222
+ items.append(
223
+ {
224
+ "kind": "formula",
225
+ "name": name,
226
+ **spec,
227
+ "numericType": declared.numeric_type,
228
+ "rootKey": nodes[0]["key"],
229
+ "nodes": nodes,
230
+ }
231
+ )
232
+ available.add(name)
233
+
234
+ outputs = []
235
+ for name, output in definition.outputs.items():
236
+ selection = output.selection
237
+ if not isinstance(selection, ast.Name) or selection.id not in available:
238
+ unsupported(
239
+ module, selection, "Each public output must select a named quantity."
240
+ )
241
+ if definition.legacy_return and selection.id != name:
242
+ unsupported(
243
+ module,
244
+ selection,
245
+ "Legacy output maps must return each quantity under its own name.",
246
+ )
247
+ outputs.append({"name": name, "symbol": selection.id})
248
+ if not outputs:
249
+ unsupported(module, fn, "Return at least one named calculation output.")
250
+ return {
251
+ "version": 1,
252
+ "title": title,
253
+ "sectionTitle": section_title,
254
+ "inputs": inputs,
255
+ "items": items,
256
+ "outputs": outputs,
257
+ }
258
+
259
+
260
+ class ArtifactPlanParser(argparse.ArgumentParser):
261
+ def error(self, message: str) -> NoReturn:
262
+ raise SourceError("INVALID_USAGE", message, stage="usage")
263
+
264
+
265
+ def artifact_plan_from_argv(argv: list[str]) -> int:
266
+ parser = ArtifactPlanParser(prog="python -m cso_python artifact-plan")
267
+ parser.add_argument("source", type=Path)
268
+ parser.add_argument("--function", action="append", required=True)
269
+ try:
270
+ args = parser.parse_args(argv)
271
+ if len(args.function) != 1:
272
+ raise SourceError("DUPLICATE_OPTION", "Duplicate --function", stage="usage")
273
+ plan = build_artifact_plan(args.source, args.function[0])
274
+ except SourceError as error:
275
+ diagnostics = [error.diagnostic, *error.additional_diagnostics]
276
+ except (OSError, UnicodeError, ValueError, RuntimeError) as error:
277
+ diagnostics = [
278
+ {"code": "SOURCE_READ_FAILED", "message": str(error), "stage": "source"}
279
+ ]
280
+ else:
281
+ print(
282
+ json.dumps({"ok": True, "plan": plan}, ensure_ascii=False, allow_nan=False)
283
+ )
284
+ return 0
285
+ print(
286
+ json.dumps({"ok": False, "diagnostics": diagnostics}, ensure_ascii=False),
287
+ file=sys.stderr,
288
+ )
289
+ return 2 if diagnostics[0]["stage"] == "usage" else 1
@@ -279,6 +279,22 @@ intermediates remain documented, observed and verified.
279
279
 
280
280
  ## Supported source and document content
281
281
 
282
+ ### Browser artifacts
283
+
284
+ For an interactive browser calculation, use one `@calculation(id=..., title=...)`
285
+ with one root `@section(title=..., root=True)`. Declare each parameter and
286
+ assignment with `Annotated[float, symbol(glyph=..., description=..., unit=...)]`
287
+ or its `int` equivalent. Keep assumptions in
288
+ `text(id=..., content=...)` statements. Write arithmetic using `+`, `-`, `*`,
289
+ `/`, `**`, unary minus, numeric literals and previously declared quantities.
290
+ Return a dictionary that maps public output names to those quantities.
291
+ The artifact exporter reports a source error for features outside this subset.
292
+
293
+ `python -m cso_python artifact-plan SOURCE --function NAME` compiles the
294
+ formulas, presentation order and input defaults without running the calculation.
295
+ Browser edits evaluate this plan. The Python execution and verification commands
296
+ remain available for checking specific inputs against the source.
297
+
282
298
  ### External functions
283
299
 
284
300
  Declare an ordinary single-file Python adapter in a local metadata module with
@@ -30,7 +30,7 @@ def _quantity(
30
30
  }
31
31
 
32
32
 
33
- def _input(name: str, parameter: ParameterDefinition, module_id: str) -> Json:
33
+ def describe_input(name: str, parameter: ParameterDefinition, module_id: str) -> Json:
34
34
  item = _quantity(
35
35
  name,
36
36
  parameter.documented,
@@ -75,7 +75,7 @@ def describe(source: Path, function: str) -> Json:
75
75
  "sourceManifest": manifest,
76
76
  "sourceClosureHash": capture.closure_hash(),
77
77
  "inputs": [
78
- _input(name, parameter, definition.module.id)
78
+ describe_input(name, parameter, definition.module.id)
79
79
  for name, parameter in definition.parameters.items()
80
80
  ],
81
81
  "outputs": [
@@ -0,0 +1,204 @@
1
+ import contextlib
2
+ import io
3
+ import json
4
+ import tempfile
5
+ import unittest
6
+ from pathlib import Path
7
+
8
+ from cso_python.__main__ import main
9
+ from cso_python.artifact_plan import build_artifact_plan
10
+ from cso_python.execution import execute
11
+ from cso_python.source import SourceError
12
+
13
+ SOURCE = """from typing import Annotated, TypeAlias
14
+ from cso_python import calculation, section, symbol, text, documented_result
15
+ Ratio: TypeAlias = Annotated[float, symbol(glyph="r", description="Ratio", unit="")]
16
+ Count: TypeAlias = Annotated[int, symbol(glyph="n", description="Count", unit="")]
17
+ Scaled: TypeAlias = Annotated[float, symbol(glyph="s", description="Scaled count", unit="")]
18
+ Adjusted: TypeAlias = Annotated[float, symbol(glyph="a", description="Adjusted count", unit="")]
19
+
20
+ @calculation(id="example", title="Scaling")
21
+ @section(title="Inputs and scale", root=True)
22
+ def calculate(count: Count, ratio: Ratio = 2):
23
+ text(id="assume", content="Assume a fixed ratio.")
24
+ scaled: Scaled = count * ratio
25
+ adjusted: Adjusted = -scaled / 2.0
26
+ return {"total": adjusted, "factor": ratio}
27
+ """
28
+
29
+
30
+ class ArtifactPlanTest(unittest.TestCase):
31
+ def setUp(self):
32
+ temporary = tempfile.TemporaryDirectory()
33
+ self.addCleanup(temporary.cleanup)
34
+ self.source = Path(temporary.name) / "example.cso.py"
35
+ self.source.write_text(SOURCE)
36
+
37
+ def test_plan_keeps_source_order_input_kinds_and_output_selections(self):
38
+ plan = build_artifact_plan(self.source, "calculate")
39
+ self.assertEqual(
40
+ (plan["version"], plan["title"], plan["sectionTitle"]),
41
+ (1, "Scaling", "Inputs and scale"),
42
+ )
43
+ self.assertNotIn("default", plan["inputs"][0])
44
+ self.assertEqual(
45
+ plan["inputs"][1],
46
+ {
47
+ "name": "ratio",
48
+ "description": "Ratio",
49
+ "glyph": "r",
50
+ "unit": "",
51
+ "numericType": "float",
52
+ "default": 2,
53
+ "defaultNumericKind": "int",
54
+ },
55
+ )
56
+ prose, first, second = plan["items"]
57
+ self.assertEqual(prose, {"kind": "text", "content": "Assume a fixed ratio."})
58
+ self.assertEqual(
59
+ (first["name"], first["description"], first["numericType"]),
60
+ ("scaled", "Scaled count", "float"),
61
+ )
62
+ self.assertEqual(first["nodes"][0]["functionId"], "fg.multiply")
63
+ self.assertEqual(
64
+ second["nodes"],
65
+ [
66
+ {
67
+ "key": "n1",
68
+ "mode": "FUNCTION",
69
+ "functionId": "fg.divide",
70
+ "args": ["n2", "n4"],
71
+ },
72
+ {
73
+ "key": "n2",
74
+ "mode": "FUNCTION",
75
+ "functionId": "fg.uminus",
76
+ "args": ["n3"],
77
+ },
78
+ {"key": "n3", "mode": "SYMBOL", "name": "scaled"},
79
+ {
80
+ "key": "n4",
81
+ "mode": "LITERAL",
82
+ "value": 2.0,
83
+ "numericKind": "float",
84
+ "draft": "2.0",
85
+ },
86
+ ],
87
+ )
88
+ self.assertEqual(second["rootKey"], second["nodes"][0]["key"])
89
+ self.assertEqual(
90
+ plan["outputs"],
91
+ [
92
+ {"name": "total", "symbol": "adjusted"},
93
+ {"name": "factor", "symbol": "ratio"},
94
+ ],
95
+ )
96
+
97
+ def test_comments_and_literal_display_text_match_the_captured_source(self):
98
+ self.source.write_text(
99
+ SOURCE.replace(
100
+ 'description="Ratio"', 'description="Ratio", comment="Measured ratio"'
101
+ )
102
+ .replace(
103
+ 'description="Adjusted count"',
104
+ 'description="Adjusted count", comment="Rounded at display only"',
105
+ )
106
+ .replace("-scaled / 2.0", "-scaled / 2.000e0")
107
+ )
108
+ plan = build_artifact_plan(self.source, "calculate")
109
+ response = execute(self.source, "calculate", {"count": 4})
110
+ self.assertTrue(response["ok"], response["diagnostics"])
111
+ normal_symbols = {
112
+ item["symbol"]["description"]: item["symbol"]
113
+ for item in response["execution"]["cso"]["sections"][0]["items"]
114
+ if item["kind"] == "symbol"
115
+ }
116
+ for quantity in [
117
+ *plan["inputs"],
118
+ *[i for i in plan["items"] if i["kind"] == "formula"],
119
+ ]:
120
+ normal = normal_symbols[quantity["description"]]
121
+ self.assertEqual(quantity.get("comment", ""), normal.get("comment", ""))
122
+ if "nodes" in quantity:
123
+ self.assertEqual(
124
+ [(n["key"], n.get("draft")) for n in quantity["nodes"]],
125
+ [(n["key"], n.get("draft")) for n in normal["valueTree"]["nodes"]],
126
+ )
127
+
128
+ def test_rejects_unsupported_source_without_silently_losing_its_meaning(self):
129
+ for before, after, code in [
130
+ (
131
+ "count * ratio",
132
+ "documented_result(count * ratio)",
133
+ "UNSUPPORTED_ARTIFACT_FEATURE",
134
+ ),
135
+ (
136
+ "count * ratio",
137
+ "count if ratio > 2 else ratio",
138
+ "UNSUPPORTED_ARTIFACT_FEATURE",
139
+ ),
140
+ ("count * ratio", "count + adjusted", "MISSING_REFERENCE"),
141
+ (
142
+ " scaled:",
143
+ " assert count > 0, 'Positive count only'\n scaled:",
144
+ "UNSUPPORTED_ARTIFACT_FEATURE",
145
+ ),
146
+ (
147
+ 'description="Scaled count"',
148
+ 'notation_scope="unused", description="Scaled count"',
149
+ "UNSUPPORTED_ARTIFACT_FEATURE",
150
+ ),
151
+ (
152
+ 'title="Scaling"',
153
+ 'title="Scaling", metadata={"scope": "test only"}',
154
+ "INVALID_METADATA",
155
+ ),
156
+ ("root=True", "root=False", "UNSUPPORTED_ARTIFACT_FEATURE"),
157
+ ('glyph="s"', 'glyph="r"', "DUPLICATE_GLYPH"),
158
+ ("text(id=", "figure(id=", "UNSUPPORTED_ARTIFACT_FEATURE"),
159
+ ("count: Count,", "count: Count = 2.0,", "DEFAULT_TYPE_MISMATCH"),
160
+ ]:
161
+ with self.subTest(source=after):
162
+ self.source.write_text(SOURCE.replace(before, after))
163
+ with self.assertRaises(SourceError) as caught:
164
+ build_artifact_plan(self.source, "calculate")
165
+ self.assertEqual(caught.exception.diagnostic["code"], code)
166
+ self.assertIn("location", caught.exception.diagnostic)
167
+
168
+ def test_planning_does_not_execute_arithmetic(self):
169
+ self.source.write_text(SOURCE.replace("count * ratio", "1 / 0"))
170
+ plan = build_artifact_plan(self.source, "calculate")
171
+ self.assertEqual(plan["items"][1]["nodes"][0]["functionId"], "fg.divide")
172
+
173
+ def test_rejects_legacy_return_with_conflicting_symbol_binding(self):
174
+ self.source.write_text(
175
+ SOURCE.replace("count: Count, ratio: Ratio = 2", "")
176
+ .replace("count * ratio", "3.0")
177
+ .replace(
178
+ '{"total": adjusted, "factor": ratio}',
179
+ '{"scaled": adjusted, "adjusted": scaled}',
180
+ )
181
+ )
182
+ with self.assertRaisesRegex(SourceError, "Legacy output maps"):
183
+ build_artifact_plan(self.source, "calculate")
184
+
185
+ def test_cli_emits_machine_readable_diagnostics_on_stderr(self):
186
+ for args, expected_code, status in [
187
+ ([], "INVALID_USAGE", 2),
188
+ (["--function", "absent"], "MISSING_FUNCTION", 1),
189
+ (
190
+ ["--function", "calculate", "--function", "calculate"],
191
+ "DUPLICATE_OPTION",
192
+ 2,
193
+ ),
194
+ ]:
195
+ with self.subTest(args=args):
196
+ out, err = io.StringIO(), io.StringIO()
197
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
198
+ self.assertEqual(
199
+ main(["artifact-plan", str(self.source), *args]), status
200
+ )
201
+ self.assertEqual(out.getvalue(), "")
202
+ self.assertEqual(
203
+ json.loads(err.getvalue())["diagnostics"][0]["code"], expected_code
204
+ )
File without changes
File without changes
File without changes
File without changes
File without changes