cs-object 0.1.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.
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.4
2
+ Name: cs-object
3
+ Version: 0.1.0
4
+ Summary: Constrained Python authoring and CalculationSourceObject JSON export
5
+ Author: Viktar B
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/viktar-b/CalculationSourceObject
8
+ Project-URL: Repository, https://github.com/viktar-b/CalculationSourceObject
9
+ Project-URL: Issues, https://github.com/viktar-b/CalculationSourceObject/issues
10
+ Requires-Python: >=3.11
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ License-File: NOTICE
14
+ Dynamic: license-file
15
+
16
+ # cs-object
17
+
18
+ Author constrained `.cso.py` calculations with Python 3.11+. Runtime dependencies
19
+ are the standard library only. Read [authoring](../../docs/authoring.md) before
20
+ writing calculations and use [two-panel](../../examples/two-panel/README.md) for
21
+ shared metadata and composed calls.
22
+
23
+ ## Install and run
24
+
25
+ Install from PyPI with `python -m pip install cs-object`. The import package and
26
+ module command remain `cso_python`.
27
+
28
+ Follow [workspace setup](../../docs/development.md#setup) to build and install a
29
+ wheel. Distribution metadata lives in [pyproject.toml](pyproject.toml).
30
+ Use the interpreter containing that wheel:
31
+
32
+ ```sh
33
+ python -m cso_python bindings examples/two-panel
34
+ python -m cso_python execute examples/two-panel/estimate.cso.py \
35
+ --function estimate --input width=2
36
+ ```
37
+
38
+ `bindings --check` checks generated interfaces without writing or executing
39
+ calculations. `execute` returns a versioned execution response; `export` returns
40
+ CSO JSON. Inspect `python -m cso_python --help` and each subcommand's `--help`
41
+ for options. Paths resolve from the invoking directory. Authored output and
42
+ operational messages go to stderr so stdout contains one JSON response.
43
+
44
+ ## Generated calculation bindings
45
+
46
+ `cso bindings` derives an importable `_cso_bindings` package from your `.cso.py`
47
+ definitions. Each generated `.py` module creates callable handles containing a
48
+ relative source path, function name and interface fingerprint. Its `.pyi` stub
49
+ provides keyword-only signatures and typed dictionaries of public results.
50
+ Generation parses definitions without executing the authored calculations.
51
+
52
+ Importing a handle does not run the calculation. Calling it captures dependencies,
53
+ plans the invocation and records its execution. This keeps composed calculations
54
+ in the document and execution evidence. The generation and planning paths share
55
+ the same definition parser. An outdated interface raises `STALE_BINDINGS`.
56
+
57
+ After workspace setup, run this ordinary Python consumer from the repository root:
58
+
59
+ ```sh
60
+ "$PYTHON" -m cso_python bindings examples/two-panel
61
+ (cd examples/two-panel && "$PYTHON" - <<'PY'
62
+ from _cso_bindings.geometry import rectangle
63
+
64
+ result = rectangle(width=2, height=3)
65
+ print(result["area"]) # 6
66
+ print(result["perimeter"]) # 10
67
+ PY
68
+ )
69
+ ```
70
+
71
+ This uses the same calculation as the composed report. Successful execution
72
+ alone does not establish source-to-document consistency; run `cso verify` or
73
+ `cso pdf` for that check. See [authoring](../../docs/authoring.md#binding-generation-and-project-layout)
74
+ for generation roots, source-control policy and regeneration rules.
75
+
76
+ The generation workflow resembles [Convex's generated function references](https://docs.convex.dev/generated-api/api):
77
+ application functions determine the generated interface that callers import.
78
+ CSO handles invoke local calculations through its capture and execution pipeline.
79
+ This analogy does not prescribe a Git policy. [Convex recommends committing its generated code](https://docs.convex.dev/understanding/best-practices/other-recommendations#check-generated-code-into-version-control)
80
+ so a checkout can type-check immediately; this repository regenerates ignored
81
+ bindings during setup and consumer preparation.
82
+
83
+ A generated handle reuses its captured plan and compiled code while its supplied
84
+ input names, source bytes and assets remain unchanged. Calls through one handle
85
+ run serially because each call updates that handle's execution trace.
86
+
87
+ Successful execution supplies observations; it does not establish formula
88
+ consistency. Use [the verified CLI](../../packages/cso-cli/README.md) for that check.
89
+ The captured path preflights local source and executes captured UTF-8 bytes.
90
+ Older single-file exports retain the development exporter. This is trusted local
91
+ calculation authoring, not isolation for hostile Python.
92
+
93
+ ## Code and checks
94
+
95
+ [Public helpers](src/cso_python/__init__.py), [capture](src/cso_python/source.py),
96
+ [definitions](src/cso_python/definitions.py), [planner](src/cso_python/planner.py),
97
+ [execution](src/cso_python/execution.py) and [bindings](src/cso_python/bindings.py)
98
+ implement the pipeline described in [the code map](../../docs/code-map.md).
99
+
100
+ With the wheel installed, run `python -I tests/run.py` from this package directory.
101
+ The tests use package-owned synthetic fixtures and temporary bindings; no root
102
+ examples or Node are required. [Workspace integration](../../tests/integration/README.md)
103
+ owns actual example, installed cross-package and PDF acceptance.
@@ -0,0 +1,22 @@
1
+ cs_object-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
2
+ cs_object-0.1.0.dist-info/licenses/NOTICE,sha256=_KptAkLL5OwSjpKOyrRWijZ5XHraYzPxJxy5Vwa_q7w,130
3
+ cso_python/__init__.py,sha256=VD3LiyvawRRWJqp-GTB28aEj0UiUgSlIqJj5yi6p3B0,754
4
+ cso_python/__main__.py,sha256=IJlb-VCV1Nde1noTXcUb-KgaQwlyZVJj5Mp8V-dZW9A,1667
5
+ cso_python/annotations.py,sha256=nKURd-tO2X_ZNcLksZoJGu_rl6eZ-HeKoFed67DjMr0,2487
6
+ cso_python/authoring.py,sha256=3XkwOAuQhAyD1tyB9TuFfsS2igi0yaa1LuIehs6tAuk,3189
7
+ cso_python/bindings.py,sha256=QX7__16UKi2t23eK-C55B5-PHALXOaN2EwRhBRBeZ_g,6575
8
+ cso_python/definitions.py,sha256=9EFg20p6FBeulcwRtUMjdPkfwsQFYl75WDZUxpGj7Sw,17475
9
+ cso_python/describe.py,sha256=8VAj-yswsik6IdfFwSl_LJJkYgldOZgt5lTIKWTPioM,4871
10
+ cso_python/execution.py,sha256=V7YmLXJZXZ1I24kLtj5h3B3TRefhBxyUDy5MG6akqLQ,21048
11
+ cso_python/exporter.py,sha256=aiVMWSNcEObRwdNltbLM5d02bDc2lwPBy7NmpH5is68,27849
12
+ cso_python/function_calls.py,sha256=GsyMvp5Hf03-OL5U992jmOZuy4YKkFqu5nt1o9PuEQw,2010
13
+ cso_python/glyphs.py,sha256=qBI0pQyPFfuvcUhPrtQSMyERJKKo78gDDSJdLeI9uY4,3095
14
+ cso_python/handles.py,sha256=IXF6xsmqP1wYeQ18DmRIDFRKmCcey0qcvvM0GKMjBTI,4489
15
+ cso_python/notation.py,sha256=W0dtyBteWIT_MGTpObcnstk693h5wGJjeJEUZUypwCE,23559
16
+ cso_python/planner.py,sha256=4ggKjS6szVjmymmWAMjV-PKJOrGPivslV72PL47LI7A,48992
17
+ cso_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ cso_python/source.py,sha256=5XyBR-bg_Ko6_6NSewvLZEWHe9p3in9I_-HyQBoZgf0,23924
19
+ cs_object-0.1.0.dist-info/METADATA,sha256=nzIpiW1-MyrY86-sRWeO6Cn5kpxVQHwrsZdE5NImT9Y,5018
20
+ cs_object-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
21
+ cs_object-0.1.0.dist-info/top_level.txt,sha256=d42-Q7iIyL8QUCFFlzie3HqwheLVPbjZRLAaWQSQjOE,11
22
+ cs_object-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,4 @@
1
+ CalculationSourceObject
2
+ Copyright 2026 Viktar Beliakou
3
+
4
+ Third-party components retain their own licenses and attribution notices.
@@ -0,0 +1 @@
1
+ cso_python
cso_python/__init__.py ADDED
@@ -0,0 +1,38 @@
1
+ """Public authoring helpers for constrained .cso.py calculations."""
2
+
3
+ from .authoring import (
4
+ CalculationFunction,
5
+ CalculationResults,
6
+ CalculationSpec,
7
+ SectionSpec,
8
+ SymbolSpec,
9
+ calculation,
10
+ document_section,
11
+ documented_result,
12
+ figure,
13
+ given,
14
+ section,
15
+ symbol,
16
+ text,
17
+ )
18
+ from .execution import calculation_call
19
+ from .handles import CalculationHandle, load_calculation
20
+
21
+ __all__ = [
22
+ "CalculationFunction",
23
+ "CalculationResults",
24
+ "CalculationSpec",
25
+ "SectionSpec",
26
+ "SymbolSpec",
27
+ "calculation",
28
+ "calculation_call",
29
+ "document_section",
30
+ "documented_result",
31
+ "figure",
32
+ "given",
33
+ "load_calculation",
34
+ "CalculationHandle",
35
+ "section",
36
+ "symbol",
37
+ "text",
38
+ ]
cso_python/__main__.py ADDED
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+
6
+ from .exporter import add_export_arguments, export_from_args
7
+
8
+
9
+ def main(argv: list[str] | None = None) -> int:
10
+ arguments = sys.argv[1:] if argv is None else argv
11
+ if arguments and arguments[0] == "bindings":
12
+ from .bindings import bindings_from_argv
13
+ return bindings_from_argv(arguments[1:])
14
+ if arguments and arguments[0] == "execute":
15
+ from .execution import execute_from_argv
16
+
17
+ return execute_from_argv(arguments[1:])
18
+ if arguments and arguments[0] == "describe":
19
+ from .describe import describe_from_argv
20
+
21
+ return describe_from_argv(arguments[1:])
22
+ parser = argparse.ArgumentParser(
23
+ prog="python -m cso_python",
24
+ description="Author and export constrained Python calculations. Export is not numerical verification.",
25
+ )
26
+ commands = parser.add_subparsers(dest="command", required=True)
27
+ export = commands.add_parser(
28
+ "export",
29
+ help="Export CalculationSourceObject JSON without numerical verification.",
30
+ description="Export formulas and runtime results as CSO JSON; does not independently verify formulas.",
31
+ )
32
+ commands.add_parser(
33
+ "execute",
34
+ help="Capture source and emit execution evidence for core verification.",
35
+ )
36
+ commands.add_parser(
37
+ "describe", help="Describe a calculation without executing authored code."
38
+ )
39
+ commands.add_parser("bindings", help="Generate typed calculation handles")
40
+ add_export_arguments(export)
41
+ return export_from_args(parser.parse_args(argv))
42
+
43
+
44
+ if __name__ == "__main__":
45
+ raise SystemExit(main(sys.argv[1:]))
@@ -0,0 +1,81 @@
1
+ """Resolve numeric annotation metadata from syntax, without evaluating authored code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ from dataclasses import dataclass
7
+
8
+ from .source import Json, SourceError, authoring_name, kwargs, span
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class Annotation:
13
+ numeric_type: str
14
+ metadata: Json | None = None
15
+
16
+
17
+ def annotation(
18
+ node: ast.expr, module: str, aliases: dict[str, Annotation]
19
+ ) -> Annotation:
20
+ if isinstance(node, ast.Name):
21
+ if node.id in ("float", "int"):
22
+ return Annotation(node.id)
23
+ if node.id in aliases:
24
+ return aliases[node.id]
25
+ if (
26
+ isinstance(node, ast.Subscript)
27
+ and authoring_name(node.value) == "Annotated"
28
+ and isinstance(node.slice, ast.Tuple)
29
+ and len(node.slice.elts) == 2
30
+ and isinstance(node.slice.elts[1], ast.Call)
31
+ and authoring_name(node.slice.elts[1].func) == "symbol"
32
+ ):
33
+ base = annotation(node.slice.elts[0], module, aliases)
34
+ if base.metadata is not None:
35
+ raise SourceError(
36
+ "AMBIGUOUS_METADATA",
37
+ "Only one symbol metadata declaration is allowed",
38
+ location=span(module, node),
39
+ )
40
+ spec = kwargs(
41
+ node.slice.elts[1],
42
+ module,
43
+ {
44
+ "id",
45
+ "root_key",
46
+ "glyph",
47
+ "description",
48
+ "unit",
49
+ "comment",
50
+ "notation_scope",
51
+ },
52
+ {"glyph", "description", "unit"},
53
+ )
54
+ return Annotation(base.numeric_type, spec)
55
+ raise SourceError(
56
+ "UNSUPPORTED_SIGNATURE",
57
+ "Expected float, int or an Annotated numeric alias",
58
+ location=span(module, node),
59
+ )
60
+
61
+
62
+ def symbol_annotation(
63
+ node: ast.AnnAssign, module: str, aliases: dict[str, Annotation]
64
+ ) -> Annotation:
65
+ try:
66
+ declared = annotation(node.annotation, module, aliases)
67
+ except SourceError as error:
68
+ if error.diagnostic["code"] != "UNSUPPORTED_SIGNATURE":
69
+ raise
70
+ raise SourceError(
71
+ "MISSING_METADATA",
72
+ "Use Annotated numeric symbol metadata",
73
+ location=span(module, node),
74
+ ) from error
75
+ if declared.metadata is None:
76
+ raise SourceError(
77
+ "MISSING_METADATA",
78
+ "Annotated calculations require symbol metadata",
79
+ location=span(module, node),
80
+ )
81
+ return declared
@@ -0,0 +1,128 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable
4
+ from contextlib import contextmanager
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, TypeAlias, TypeVar
7
+
8
+ CalculationResults: TypeAlias = dict[str, float]
9
+ CalculationFunction: TypeAlias = Callable[..., CalculationResults]
10
+ _Function = TypeVar("_Function", bound=CalculationFunction)
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class CalculationSpec:
15
+ id: str
16
+ title: str
17
+ schema_version: str
18
+ metadata: dict[str, Any] = field(default_factory=dict)
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class SectionSpec:
23
+ title: str
24
+ id: str | None = None
25
+ root: bool = False
26
+ metadata: dict[str, Any] = field(default_factory=dict)
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class SymbolSpec:
31
+ glyph: str
32
+ description: str
33
+ unit: str
34
+ comment: str = ""
35
+ id: str | None = None
36
+ root_key: str | None = None
37
+ notation_scope: str | None = None
38
+
39
+
40
+ def calculation(
41
+ *,
42
+ id: str,
43
+ title: str,
44
+ schema_version: str = "1.0.0",
45
+ metadata: dict[str, Any] | None = None,
46
+ ) -> Callable[[_Function], _Function]:
47
+ """Attach CalculationSourceObject document metadata to a calculation function."""
48
+
49
+ def decorate(fn: _Function) -> _Function:
50
+ fn.__calculation_source__ = CalculationSpec(
51
+ id=id,
52
+ title=title,
53
+ schema_version=schema_version,
54
+ metadata=metadata or {},
55
+ )
56
+ return fn
57
+
58
+ return decorate
59
+
60
+
61
+ def section(
62
+ *,
63
+ title: str,
64
+ id: str | None = None,
65
+ root: bool = False,
66
+ metadata: dict[str, Any] | None = None,
67
+ ) -> Callable[[_Function], _Function]:
68
+ """Attach CalculationSourceObject section metadata to a calculation function."""
69
+
70
+ def decorate(fn: _Function) -> _Function:
71
+ fn.__calculation_section__ = SectionSpec(
72
+ id=id,
73
+ title=title,
74
+ root=root,
75
+ metadata=metadata or {},
76
+ )
77
+ return fn
78
+
79
+ return decorate
80
+
81
+
82
+ def symbol(
83
+ *,
84
+ glyph: str,
85
+ description: str,
86
+ unit: str,
87
+ comment: str = "",
88
+ id: str | None = None,
89
+ root_key: str | None = None,
90
+ notation_scope: str | None = None,
91
+ ) -> SymbolSpec:
92
+ """Declare CalculationSourceObject symbol metadata for source parsing."""
93
+
94
+ return SymbolSpec(
95
+ glyph=glyph,
96
+ description=description,
97
+ unit=unit,
98
+ comment=comment,
99
+ id=id,
100
+ root_key=root_key,
101
+ notation_scope=notation_scope,
102
+ )
103
+
104
+
105
+ def given(value: float) -> float:
106
+ """Mark a literal input value while preserving normal Python execution."""
107
+
108
+ return value
109
+
110
+
111
+ def documented_result(value: Any) -> Any:
112
+ """Mark a calculated value as an intentional FormulaSheet escape hatch."""
113
+
114
+ return value
115
+
116
+
117
+ def text(*, id: str, content: str) -> None:
118
+ """Place literal review prose; the source parser retains its order."""
119
+
120
+
121
+ def figure(*, id: str, path: str, media_type: str, caption: str, alt: str) -> None:
122
+ """Place a local figure; the source parser captures its asset identity."""
123
+
124
+
125
+ @contextmanager
126
+ def document_section(*, id: str, title: str, metadata: dict[str, Any] | None = None):
127
+ """Group one child level of calculation document content."""
128
+ yield