pyinto 0.0.1__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.
Files changed (55) hide show
  1. pyinto/__init__.py +15 -0
  2. pyinto/admission.py +154 -0
  3. pyinto/analysis/__init__.py +5 -0
  4. pyinto/analysis/closures.py +83 -0
  5. pyinto/api.py +62 -0
  6. pyinto/constructs/__init__.py +224 -0
  7. pyinto/constructs/admission.py +592 -0
  8. pyinto/constructs/base.py +101 -0
  9. pyinto/constructs/classes.py +582 -0
  10. pyinto/constructs/collections.py +366 -0
  11. pyinto/constructs/control.py +500 -0
  12. pyinto/constructs/formatting.py +65 -0
  13. pyinto/constructs/functions.py +497 -0
  14. pyinto/constructs/intrinsic.py +294 -0
  15. pyinto/constructs/operations.py +593 -0
  16. pyinto/constructs/type_rules.py +58 -0
  17. pyinto/constructs/types.py +340 -0
  18. pyinto/constructs/updates.py +58 -0
  19. pyinto/constructs/values.py +148 -0
  20. pyinto/frontend/__init__.py +5 -0
  21. pyinto/frontend/annotations.py +154 -0
  22. pyinto/frontend/classes.py +550 -0
  23. pyinto/frontend/context.py +154 -0
  24. pyinto/frontend/decorator_effects.py +86 -0
  25. pyinto/frontend/decorators.py +195 -0
  26. pyinto/frontend/docstrings.py +18 -0
  27. pyinto/frontend/errors.py +15 -0
  28. pyinto/frontend/expressions.py +708 -0
  29. pyinto/frontend/functions.py +779 -0
  30. pyinto/frontend/imports.py +99 -0
  31. pyinto/frontend/interface_mapping.py +329 -0
  32. pyinto/frontend/parser.py +252 -0
  33. pyinto/frontend/statement_services.py +85 -0
  34. pyinto/frontend/statements.py +748 -0
  35. pyinto/interface_mapping/__init__.py +23 -0
  36. pyinto/interface_mapping/declarations.py +189 -0
  37. pyinto/interface_mapping/registry.py +299 -0
  38. pyinto/interfaces/__init__.py +9 -0
  39. pyinto/interfaces/builtins.py +43 -0
  40. pyinto/interfaces/language.py +156 -0
  41. pyinto/intrinsics.py +155 -0
  42. pyinto/model/__init__.py +5 -0
  43. pyinto/model/value_types.py +55 -0
  44. pyinto/realizations/__init__.py +13 -0
  45. pyinto/realizations/artifacts.py +39 -0
  46. pyinto/realizations/call_layout.py +121 -0
  47. pyinto/realizations/host.py +84 -0
  48. pyinto/realizations/layout.py +124 -0
  49. pyinto/realizations/registry.py +555 -0
  50. pyinto/realizations/regulation.py +312 -0
  51. pyinto-0.0.1.dist-info/METADATA +127 -0
  52. pyinto-0.0.1.dist-info/RECORD +55 -0
  53. pyinto-0.0.1.dist-info/WHEEL +5 -0
  54. pyinto-0.0.1.dist-info/licenses/LICENSE +21 -0
  55. pyinto-0.0.1.dist-info/top_level.txt +1 -0
pyinto/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """pyinto 0.0.1: experimental Python-AST-to-Construct pipeline."""
2
+
3
+ from pyinto.api import convert, realize
4
+ from pyinto.constructs import Construct, ConstructError, Program
5
+ from pyinto.frontend import PythonFrontend, UnsupportedPython
6
+
7
+ __all__ = [
8
+ "Construct",
9
+ "ConstructError",
10
+ "Program",
11
+ "PythonFrontend",
12
+ "UnsupportedPython",
13
+ "convert",
14
+ "realize",
15
+ ]
pyinto/admission.py ADDED
@@ -0,0 +1,154 @@
1
+ """Target-neutral admission contracts owned by Construct providers.
2
+
3
+ Providers declare each concrete Construct, including those whose current
4
+ realization admission requirements are empty. A Target Pack merely declares
5
+ which concrete obligation keys it supports; it cannot invent or waive them.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable, Iterable
11
+ from dataclasses import dataclass
12
+ from types import MappingProxyType
13
+
14
+ from pyinto.constructs.base import Construct
15
+ from pyinto.constructs.types import ConstructError
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class AdmissionRule:
20
+ """A provider-defined, Target-independent group of semantic obligations.
21
+
22
+ A contract ending in ``.*`` declares an *open family* of concrete names.
23
+ This never authorizes a Target to use wildcard ``supports`` declarations.
24
+ """
25
+
26
+ name: str
27
+ constructs: tuple[type[Construct], ...]
28
+ guarded_fields: frozenset[str]
29
+ contracts: frozenset[str]
30
+ resolve: Callable[[Construct], frozenset[str]]
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class AdmissionDeclaration:
35
+ """Explicit provider-owned admission policy for one *exact* Construct type.
36
+
37
+ An empty ``rules`` tuple is an intentional declaration that no additional
38
+ runtime admission keys have yet been established for this Construct, NOT a
39
+ claim that arbitrary Target recipes preserve its semantics.
40
+ """
41
+
42
+ construct: type[Construct]
43
+ rules: tuple[AdmissionRule, ...] = ()
44
+
45
+
46
+ def _matches_contract(name: str, declared: frozenset[str]) -> bool:
47
+ return name in declared or any(
48
+ token.endswith(".*") and name.startswith(token[:-1]) for token in declared
49
+ )
50
+
51
+
52
+ def collect_contracts(
53
+ node: Construct, rules: Iterable[AdmissionRule]
54
+ ) -> frozenset[str]:
55
+ """Extract only explicit, provider-defined obligations, without inference."""
56
+ required: set[str] = set()
57
+ for rule in rules:
58
+ if type(node) in rule.constructs:
59
+ names = rule.resolve(node)
60
+ if not all(_matches_contract(name, rule.contracts) for name in names):
61
+ raise ValueError(f"Admission rule {rule.name} emitted undeclared key")
62
+ required.update(names)
63
+ return frozenset(required)
64
+
65
+
66
+ class AdmissionRegistry:
67
+ """Immutable provider catalog, independent of any selected Target Pack.
68
+
69
+ Exact type registration ensures that subclassing a known Construct never
70
+ silently inherits an admission policy that did not examine its new fields.
71
+ """
72
+
73
+ def __init__(self, declarations: Iterable[AdmissionDeclaration] = ()) -> None:
74
+ policies: dict[type[Construct], tuple[AdmissionRule, ...]] = {}
75
+ rule_names: dict[str, AdmissionRule] = {}
76
+ for declaration in declarations:
77
+ cls = declaration.construct
78
+ if not isinstance(cls, type) or not issubclass(cls, Construct):
79
+ raise TypeError("Admission declaration requires a Construct type")
80
+ if cls in policies:
81
+ raise ValueError(f"Duplicate Construct admission: {cls.__name__}")
82
+ if len({rule.name for rule in declaration.rules}) != len(declaration.rules):
83
+ raise ValueError("Duplicate admission rule names")
84
+ for rule in declaration.rules:
85
+ if cls not in rule.constructs:
86
+ raise ValueError(
87
+ f"Admission rule {rule.name} does not cover {cls.__name__}"
88
+ )
89
+ if not rule.name or not rule.contracts or not rule.constructs:
90
+ raise ValueError("Invalid admission rule declaration")
91
+ if not rule.guarded_fields <= set(
92
+ getattr(cls, "__dataclass_fields__", {})
93
+ ):
94
+ raise ValueError(
95
+ f"Admission rule {rule.name} guards unknown fields"
96
+ )
97
+ other = rule_names.setdefault(rule.name, rule)
98
+ if other is not rule:
99
+ raise ValueError("Duplicate admission rule names")
100
+ policies[cls] = declaration.rules
101
+ self._policies = MappingProxyType(policies)
102
+
103
+ @property
104
+ def declarations(self) -> tuple[AdmissionDeclaration, ...]:
105
+ return tuple(
106
+ AdmissionDeclaration(cls, rules) for cls, rules in self._policies.items()
107
+ )
108
+
109
+ def require_baseline(self, baseline: AdmissionRegistry) -> None:
110
+ """Require an unchanged provider-owned baseline, allowing additions.
111
+
112
+ This check is independent of any particular Interface. It is used by
113
+ the Host to protect its Language Construct policies from replacement.
114
+ """
115
+ for cls, rules in baseline._policies.items():
116
+ if cls not in self._policies or self._policies[cls] != rules:
117
+ raise ValueError(
118
+ f"Missing or replaced baseline Construct admission: {cls.__name__}"
119
+ )
120
+
121
+ def extend(self, declarations: Iterable[AdmissionDeclaration]) -> AdmissionRegistry:
122
+ """Provider-only extension. Existing policies cannot be replaced."""
123
+ return AdmissionRegistry((*self.declarations, *tuple(declarations)))
124
+
125
+ def _rules_for(self, node: Construct) -> tuple[AdmissionRule, ...]:
126
+ try:
127
+ return self._policies[type(node)]
128
+ except KeyError as exc:
129
+ raise ConstructError(
130
+ f"Unregistered Construct admission: {type(node).__name__}"
131
+ ) from exc
132
+
133
+ def check_tree(self, root: Construct) -> None:
134
+ """Reject undeclared children even if a Template ignores their Slots.
135
+
136
+ This is an inventory check, not a requirement that all children are
137
+ realized. Whether omission preserves meaning remains a separate issue.
138
+ """
139
+ visited: set[int] = set()
140
+ pending: list[object] = [root]
141
+ while pending:
142
+ item = pending.pop()
143
+ if isinstance(item, Construct):
144
+ if id(item) in visited:
145
+ continue
146
+ visited.add(id(item))
147
+ self._rules_for(item)
148
+ pending.extend(item.parts().values())
149
+ elif isinstance(item, (tuple, list)):
150
+ pending.extend(item)
151
+
152
+ def required_contracts(self, node: Construct) -> frozenset[str]:
153
+ """Fail closed on unregistered concrete Construct types."""
154
+ return collect_contracts(node, self._rules_for(node))
@@ -0,0 +1,5 @@
1
+ """Read-only analysis of existing, target-independent Constructs."""
2
+
3
+ from pyinto.analysis.closures import lexical_captures
4
+
5
+ __all__ = ["lexical_captures"]
@@ -0,0 +1,83 @@
1
+ """Derive *static* free lexical bindings without a Closure Construct.
2
+
3
+ No source is executed and no runtime closure object is created. Captures are
4
+ symbol declarations, not per-invocation environments. The latter, including
5
+ escaping values and distinct calls of one factory, remains a Realization duty.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pyinto.constructs import (
11
+ Construct,
12
+ ConstructError,
13
+ FunctionCall,
14
+ FunctionDefinition,
15
+ Reference,
16
+ Symbol,
17
+ )
18
+
19
+
20
+ def lexical_captures(definition: FunctionDefinition) -> tuple[Symbol, ...]:
21
+ """Find direct non-module lexical dependencies of one function body.
22
+
23
+ A captured Symbol belongs to a strict enclosing function scope. Function
24
+ declaration references (including direct calls to an enclosing function)
25
+ use their existing stable ``FunctionSignature.value_symbol``. The result
26
+ contains each declaration once, in first-use order, preserving *identity*.
27
+
28
+ Nested function bodies are excluded: each function's own captures can be
29
+ inspected separately. A Realization that needs transitively retained
30
+ environments must analyze the nested definitions and their escape paths;
31
+ this function does not infer liveness or allocate runtime frames.
32
+ """
33
+ if not isinstance(definition, FunctionDefinition):
34
+ raise TypeError("lexical_captures requires a FunctionDefinition")
35
+
36
+ current_scope = (*definition.signature.scope, definition.signature.name)
37
+ try:
38
+ own_value_symbol = definition.signature.value_symbol
39
+ except ConstructError:
40
+ own_value_symbol = None
41
+ seen: set[int] = set()
42
+ result: list[Symbol] = []
43
+
44
+ def consider(symbol: Symbol) -> None:
45
+ owner = symbol.scope
46
+ if (
47
+ not owner # Module-level bindings are not captured lexical locals.
48
+ or len(owner) >= len(current_scope)
49
+ or current_scope[: len(owner)] != owner
50
+ or symbol is own_value_symbol
51
+ ):
52
+ return
53
+ key = id(symbol)
54
+ if key not in seen:
55
+ seen.add(key)
56
+ result.append(symbol)
57
+
58
+ def visit(item: object) -> None:
59
+ if isinstance(item, FunctionDefinition):
60
+ # Child definitions have their own frame and capture set.
61
+ return
62
+ if isinstance(item, Reference):
63
+ consider(item.symbol)
64
+ if isinstance(item, FunctionCall):
65
+ signature = item.signature
66
+ if signature is not definition.signature:
67
+ # An unshaped Port function can still be directly called.
68
+ # Its declaration is already available through the signature.
69
+ try:
70
+ symbol = signature.value_symbol
71
+ except ConstructError:
72
+ symbol = None
73
+ if symbol is not None:
74
+ consider(symbol)
75
+ if isinstance(item, Construct):
76
+ for child in item.parts().values():
77
+ visit(child)
78
+ elif isinstance(item, (tuple, list)):
79
+ for child in item:
80
+ visit(child)
81
+
82
+ visit(definition.body)
83
+ return tuple(result)
pyinto/api.py ADDED
@@ -0,0 +1,62 @@
1
+ """Public conversion entrances; Constructs are independent of Realization."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pyinto.admission import AdmissionRegistry
6
+ from pyinto.constructs import Construct
7
+ from pyinto.frontend import PythonFrontend
8
+ from pyinto.interface_mapping.registry import InterfaceMappingRegistry
9
+ from pyinto.intrinsics import IntrinsicRegistry
10
+ from pyinto.realizations.host import RealizationHost
11
+ from pyinto.realizations.registry import RealizationRegistry
12
+
13
+
14
+ def realize(
15
+ program: Construct,
16
+ *,
17
+ realizations: RealizationRegistry,
18
+ admission: AdmissionRegistry | None = None,
19
+ ) -> object:
20
+ """Realize an existing Model with an explicitly selected Target Pack.
21
+
22
+ Construct trees are never modified. No target is selected implicitly.
23
+ """
24
+ if not isinstance(program, Construct):
25
+ raise TypeError("A Construct is required")
26
+ if not isinstance(realizations, RealizationRegistry):
27
+ raise TypeError("A validated RealizationRegistry is required")
28
+ if admission is not None and not isinstance(admission, AdmissionRegistry):
29
+ raise TypeError("An AdmissionRegistry is required")
30
+ return RealizationHost(realizations, admission=admission).run(program)
31
+
32
+
33
+ def convert(
34
+ source: str,
35
+ *,
36
+ realizations: RealizationRegistry,
37
+ interface_mappings: InterfaceMappingRegistry | None = None,
38
+ intrinsics: IntrinsicRegistry | None = None,
39
+ admission: AdmissionRegistry | None = None,
40
+ ) -> object:
41
+ """Normalize Python text, then request the selected Target's artifact."""
42
+ if not isinstance(source, str):
43
+ raise TypeError("Python source must be a string")
44
+ if not isinstance(realizations, RealizationRegistry):
45
+ raise TypeError("A validated RealizationRegistry is required")
46
+ if interface_mappings is not None and not isinstance(
47
+ interface_mappings, InterfaceMappingRegistry
48
+ ):
49
+ raise TypeError(
50
+ "An InterfaceMappingRegistry is required for interface_mappings"
51
+ )
52
+ if intrinsics is not None and not isinstance(intrinsics, IntrinsicRegistry):
53
+ raise TypeError("An IntrinsicRegistry is required")
54
+ return realize(
55
+ PythonFrontend(
56
+ interface_mappings=interface_mappings, intrinsics=intrinsics
57
+ ).parse(source),
58
+ realizations=realizations,
59
+ admission=admission
60
+ if admission is not None
61
+ else (interface_mappings.admission if interface_mappings is not None else None),
62
+ )
@@ -0,0 +1,224 @@
1
+ """Target-neutral Construct Model, organized by semantic responsibility.
2
+
3
+ Modules contain the definitions; this namespace gathers the Model vocabulary.
4
+ """
5
+
6
+ from .base import (
7
+ Construct,
8
+ Value,
9
+ )
10
+ from .classes import (
11
+ ClassDefinition,
12
+ ClassMethodCall,
13
+ ClassReceiverCreation,
14
+ ClassReference,
15
+ ClassSignature,
16
+ FieldDefinition,
17
+ FieldInitialize,
18
+ FieldRead,
19
+ FieldWrite,
20
+ InstanceCreation,
21
+ MethodCall,
22
+ MethodDispatch,
23
+ )
24
+ from .collections import (
25
+ DictElement,
26
+ DictElementAssign,
27
+ DictEntry,
28
+ DictValue,
29
+ ListElement,
30
+ ListElementAssign,
31
+ ListValue,
32
+ Membership,
33
+ SliceValue,
34
+ TupleElement,
35
+ TupleValue,
36
+ )
37
+ from .control import (
38
+ SUPPORTED_EXCEPTION_NAMES,
39
+ Assign,
40
+ Block,
41
+ Branch,
42
+ Break,
43
+ Call,
44
+ ContextEntry,
45
+ Continue,
46
+ ExceptHandler,
47
+ ExpressionStatement,
48
+ For,
49
+ Initialize,
50
+ IterationEntry,
51
+ Pass,
52
+ Program,
53
+ Raise,
54
+ Range,
55
+ Try,
56
+ UnpackAssign,
57
+ While,
58
+ With,
59
+ )
60
+ from .formatting import FormattedString, PrintValues
61
+ from .functions import (
62
+ FunctionCall,
63
+ FunctionDefinition,
64
+ FunctionSignature,
65
+ FunctionValueCall,
66
+ LambdaValue,
67
+ Parameter,
68
+ Return,
69
+ )
70
+ from .intrinsic import (
71
+ IntrinsicCall,
72
+ IntrinsicDefinition,
73
+ IntrinsicListType,
74
+ IntrinsicTypeVar,
75
+ )
76
+ from .operations import (
77
+ Absolute,
78
+ Arithmetic,
79
+ BooleanAggregate,
80
+ BooleanNot,
81
+ BooleanOperation,
82
+ Comparison,
83
+ ComparisonChain,
84
+ Extremum,
85
+ FloatingArithmetic,
86
+ FloatingComparison,
87
+ FloatingUnary,
88
+ IntegerSum,
89
+ IntegerTrueDivision,
90
+ IntegerUnary,
91
+ Length,
92
+ StringComparison,
93
+ StringConcat,
94
+ StringContains,
95
+ StringElement,
96
+ StringRepeat,
97
+ )
98
+ from .types import (
99
+ CallableType,
100
+ ConstructError,
101
+ DictType,
102
+ Identifier,
103
+ InstanceType,
104
+ ListType,
105
+ MethodKind,
106
+ ParameterRole,
107
+ PortType,
108
+ Symbol,
109
+ TupleType,
110
+ ValueKind,
111
+ ValueType,
112
+ )
113
+ from .updates import AugAssign, AugAssignMode
114
+ from .values import (
115
+ BooleanLiteral,
116
+ ConditionalExpression,
117
+ FloatingLiteral,
118
+ Literal,
119
+ NoneLiteral,
120
+ Reference,
121
+ )
122
+
123
+ __all__ = [
124
+ "SUPPORTED_EXCEPTION_NAMES",
125
+ "Absolute",
126
+ "Arithmetic",
127
+ "Assign",
128
+ "AugAssign",
129
+ "AugAssignMode",
130
+ "Block",
131
+ "BooleanAggregate",
132
+ "BooleanLiteral",
133
+ "BooleanNot",
134
+ "BooleanOperation",
135
+ "Branch",
136
+ "Break",
137
+ "Call",
138
+ "CallableType",
139
+ "ClassDefinition",
140
+ "ClassMethodCall",
141
+ "ClassReceiverCreation",
142
+ "ClassReference",
143
+ "ClassSignature",
144
+ "Comparison",
145
+ "ComparisonChain",
146
+ "ConditionalExpression",
147
+ "Construct",
148
+ "ConstructError",
149
+ "ContextEntry",
150
+ "Continue",
151
+ "DictElement",
152
+ "DictElementAssign",
153
+ "DictEntry",
154
+ "DictType",
155
+ "DictValue",
156
+ "ExceptHandler",
157
+ "ExpressionStatement",
158
+ "Extremum",
159
+ "FieldDefinition",
160
+ "FieldInitialize",
161
+ "FieldRead",
162
+ "FieldWrite",
163
+ "FloatingArithmetic",
164
+ "FloatingComparison",
165
+ "FloatingLiteral",
166
+ "FloatingUnary",
167
+ "For",
168
+ "FormattedString",
169
+ "FunctionCall",
170
+ "FunctionDefinition",
171
+ "FunctionSignature",
172
+ "FunctionValueCall",
173
+ "Identifier",
174
+ "Initialize",
175
+ "InstanceCreation",
176
+ "InstanceType",
177
+ "IntegerSum",
178
+ "IntegerTrueDivision",
179
+ "IntegerUnary",
180
+ "IntrinsicCall",
181
+ "IntrinsicDefinition",
182
+ "IntrinsicListType",
183
+ "IntrinsicTypeVar",
184
+ "IterationEntry",
185
+ "LambdaValue",
186
+ "Length",
187
+ "ListElement",
188
+ "ListElementAssign",
189
+ "ListType",
190
+ "ListValue",
191
+ "Literal",
192
+ "Membership",
193
+ "MethodCall",
194
+ "MethodDispatch",
195
+ "MethodKind",
196
+ "NoneLiteral",
197
+ "Parameter",
198
+ "ParameterRole",
199
+ "Pass",
200
+ "PortType",
201
+ "PrintValues",
202
+ "Program",
203
+ "Raise",
204
+ "Range",
205
+ "Reference",
206
+ "Return",
207
+ "SliceValue",
208
+ "StringComparison",
209
+ "StringConcat",
210
+ "StringContains",
211
+ "StringElement",
212
+ "StringRepeat",
213
+ "Symbol",
214
+ "Try",
215
+ "TupleElement",
216
+ "TupleType",
217
+ "TupleValue",
218
+ "UnpackAssign",
219
+ "Value",
220
+ "ValueKind",
221
+ "ValueType",
222
+ "While",
223
+ "With",
224
+ ]