embeddedpy 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.

Potentially problematic release.


This version of embeddedpy might be problematic. Click here for more details.

@@ -0,0 +1,278 @@
1
+ """Type inference and subset semantics checking.
2
+
3
+ Approach: whole-program monomorphic inference; function signatures are
4
+ unified from annotations or call sites, variable types are fixed at first
5
+ assignment, and a type change is a compile-time error.
6
+ """
7
+
8
+ import ast
9
+ from dataclasses import dataclass, field
10
+ from typing import Dict, List, Optional, Tuple
11
+
12
+ from . import irtypes as T
13
+
14
+ # Type path table: embeddedpy.types.<name> -> compile-time scalar type.
15
+ # The module name comes from the language library itself (__module__) and
16
+ # matches the package path.
17
+ import embeddedpy.types as _lang_types
18
+
19
+ BUILTIN_FUNCS = {
20
+ "print",
21
+ "input",
22
+ "len",
23
+ "abs",
24
+ "min",
25
+ "max",
26
+ "range",
27
+ }
28
+
29
+ def undefined_name_message(name: str) -> str:
30
+ """Error message text for "name is not defined"."""
31
+ return f"name {name} is not defined"
32
+
33
+ # Non-scalar special names exported by embeddedpy are registered by category
34
+ # in lang_api.CATEGORY_SPECIALS; the category registry is the single source.
35
+
36
+ # C type qualifiers: only allowed in type annotations (x: const[int32]).
37
+ # The value is the text emitted into C; rendering is in
38
+ # cgen_helpers._quals_prefix.
39
+ QUALIFIER_KINDS = {
40
+ "qualifier_const": "const",
41
+ "qualifier_volatile": "volatile",
42
+ }
43
+
44
+ # Display name shown to the user on a bare-qualifier error; empty means reuse
45
+ # the value from QUALIFIER_KINDS.
46
+ QUALIFIER_DISPLAY = {}
47
+
48
+
49
+ def _ctype_of(t: T.Type) -> str:
50
+ """Return the C type text for a type (pointer carries *, array uses its element type)."""
51
+ r = T.resolve(t)
52
+ if isinstance(r, T.Ptr):
53
+ return _ctype_of(r.target) + " *"
54
+ if isinstance(r, T.Array):
55
+ return _ctype_of(r.element)
56
+ if isinstance(r, (T.Struct, T.Enum)):
57
+ return r.c_name
58
+ return T.base(r).ctype
59
+
60
+
61
+ # Pointer size (64-bit platform); the C side is computed by the target
62
+ # platform's compiler, this is only a type-level approximation.
63
+ _PTR_SIZE = 8
64
+
65
+
66
+ def _sizeof_size(t: T.Type) -> int:
67
+ """Number of bytes the type occupies (consistent with CPython's sizeof)."""
68
+ r = T.resolve(t)
69
+ if isinstance(r, T.Ptr):
70
+ return _PTR_SIZE
71
+ if isinstance(r, T.Array):
72
+ return _sizeof_size(r.element)
73
+ s = T.base(r)
74
+ return max(s.bits, 0) // 8
75
+
76
+ # Dynamic methods disabled for fixed-width arrays (to preserve "fixed-width"
77
+ # semantics and give a friendly error).
78
+ FORBIDDEN_ARRAY_METHODS = {
79
+ "append", "pop", "insert", "extend", "remove", "clear", "sort", "reverse",
80
+ }
81
+
82
+ # Pure functional pointer API: ptr.ref / null / peek / poke / skip / field /
83
+ # from_int / cast
84
+ PTR_API_NAMES = (
85
+ "ref",
86
+ "null",
87
+ "peek",
88
+ "poke",
89
+ "skip",
90
+ "field",
91
+ "from_int",
92
+ "cast",
93
+ )
94
+
95
+ # C-specific heap memory management API: mem.alloc / free / realloc /
96
+ # arena_reset
97
+ MEM_API_NAMES = ("alloc", "free", "realloc", "arena_reset")
98
+
99
+ # File I/O API names under the embeddedpy.io category
100
+ IO_API_NAMES = ("open", "read", "write", "close")
101
+
102
+ # Text buffer API names under the embeddedpy.strings category
103
+ STRINGS_API_NAMES = ("data", "byte_len", "from_ptr")
104
+
105
+ # Byte buffer API names under the embeddedpy.bytes category
106
+ BYTES_API_NAMES = ("data", "byte_len", "from_ptr")
107
+
108
+ # "Expression-level" builtins under the c namespace (have a return value, can
109
+ # be used as assignment/return/argument): bit-operation builtins.
110
+ # These are not preprocessor directives or decorators; they are real
111
+ # expressions, dispatched the same three-pass way as ptr/mem.
112
+ C_EXPR_API_NAMES = ("clz", "ctz", "popcount")
113
+
114
+ # "Statement-level" builtins under the c namespace (standalone statements,
115
+ # emit one line of C, no return value): memory barriers.
116
+ C_STMT_API_NAMES = ("barrier",)
117
+
118
+ TYPE_PATH_MAP: Dict[str, T.Scalar] = {}
119
+ for _name in _lang_types.__all__:
120
+ _scalar = (
121
+ T.INT_TYPES.get(_name)
122
+ or T.FLOAT_TYPES.get(_name)
123
+ or T.CHAR_TYPES.get(_name)
124
+ or T.REEXPORTED_TYPES.get(_name)
125
+ or T.VOID_TYPES.get(_name)
126
+ )
127
+ if _scalar is None:
128
+ continue
129
+ # The key uses the **category module name** (embeddedpy.types.<name>), not
130
+ # the object's __module__: re-exported Bool / Str / Bytes are builtins
131
+ # objects whose __module__ is "builtins", which would never match the
132
+ # embeddedpy.types.Str the user writes.
133
+ TYPE_PATH_MAP[f"{_lang_types.__name__}.{_name}"] = _scalar
134
+
135
+
136
+ @dataclass
137
+ class Symbol:
138
+ """A name in the scope: type, C name, qualifiers, declaration location, and init info."""
139
+ kind: str # global / local / param / func / type / module / builtin
140
+ name: str
141
+ type: Optional[T.Type] = None
142
+ c_name: str = ""
143
+ module_path: str = ""
144
+ # Type qualifiers (const / volatile), from annotations like x: const[int32]
145
+ quals: List[str] = field(default_factory=list)
146
+ # Whether it has already been declared via annotation (distinguishes
147
+ # "first declaration" from "re-annotation = assignment").
148
+ declared: bool = False
149
+ # Initial value expression for global variables (const globals need static
150
+ # initialization at the declaration site).
151
+ init_node: Optional[ast.AST] = None
152
+ # Constant value of a const global (known at compile time, usable in
153
+ # constant expressions).
154
+ const_value: Optional[int] = None
155
+ # Value of a c.define macro (macros are typeless, just text substitution;
156
+ # Symbol keeps the value for codegen output).
157
+ macro_value: object = None
158
+ # The C section the variable belongs to (c.section(".noinit")[T]): a global
159
+ # with a section name is a real static object on the C side.
160
+ section: str = ""
161
+ # Real static C object (uninitialized global / section-named global): does
162
+ # not use the arena pointer representation; the file header emits its
163
+ # definition, and top-level statements do not assign to it.
164
+ static_object: bool = False
165
+
166
+
167
+ @dataclass
168
+ class FuncInfo:
169
+ """Information about a function definition: return value, parameters and locals, and whether it is an external declaration."""
170
+ name: str
171
+ node: ast.FunctionDef
172
+ ret: T.Type
173
+ locals: Dict[str, Symbol] = field(default_factory=dict)
174
+ params: List[str] = field(default_factory=list)
175
+ has_value_return: bool = False
176
+ # External C function declaration (@c.extern_function): only emit an extern
177
+ # declaration, no function body.
178
+ is_extern: bool = False
179
+ extern_c_name: str = ""
180
+ # Exported symbol (@c.export("Reset_Handler")): defined in this translation
181
+ # unit, with the user-given C name, external linkage, and a used attribute;
182
+ # mutually exclusive with is_extern (defined elsewhere).
183
+ export_c_name: str = ""
184
+ # Declaration modifiers: @c.inline -> static inline;
185
+ # @c.section(".ramfunc") -> section attribute.
186
+ is_inline: bool = False
187
+ section: str = ""
188
+ # Declaration modifiers (extended): @c.weak -> weak symbol;
189
+ # @c.aligned(N) -> alignment in bytes;
190
+ # @c.visibility("hidden"|"default"|"protected") -> symbol visibility.
191
+ is_weak: bool = False
192
+ align: int = 0
193
+ visibility: str = ""
194
+
195
+
196
+ @dataclass
197
+ class ModuleInfo:
198
+ """Module info summarized during the checking phase: global symbols, function table, include and bare-call registrations."""
199
+ filename: str
200
+ globals: Dict[str, Symbol]
201
+ functions: Dict[str, FuncInfo]
202
+ scope: Dict[str, Symbol]
203
+ # Headers to #include: (header filename, is-system-header).
204
+ includes: List[Tuple[str, bool]] = field(default_factory=list)
205
+ # Bare-call registrations with no Python name (c.extern_const(...) /
206
+ # c.define(...) assign nothing). These declarations have no LHS so they
207
+ # cannot enter the scope (otherwise they would be resolved as valid Python
208
+ # names), but codegen still needs to emit declarations/macro definitions.
209
+ decls: List["Symbol"] = field(default_factory=list)
210
+
211
+
212
+ # ----------------------------------------------------------- for-range constant folding
213
+
214
+ # Only pure integer arithmetic is recognized; if it contains variables,
215
+ # function calls, or floats, folding is abandoned and falls back to regular
216
+ # type inference.
217
+ _INT_BINOPS = {
218
+ ast.Add: lambda a, b: a + b,
219
+ ast.Sub: lambda a, b: a - b,
220
+ ast.Mult: lambda a, b: a * b,
221
+ ast.FloorDiv: lambda a, b: a // b,
222
+ ast.Mod: lambda a, b: a % b,
223
+ ast.Pow: lambda a, b: a ** b,
224
+ ast.LShift: lambda a, b: a << b,
225
+ ast.RShift: lambda a, b: a >> b,
226
+ ast.BitAnd: lambda a, b: a & b,
227
+ ast.BitOr: lambda a, b: a | b,
228
+ ast.BitXor: lambda a, b: a ^ b,
229
+ }
230
+ _FOLD_LIMIT = 1 << 128
231
+
232
+
233
+ def fold_int_expr(node: ast.AST) -> Optional[int]:
234
+ """Evaluate a compile-time integer constant expression using Python integer
235
+ semantics; returns None if it is not a constant.
236
+
237
+ for-range arguments are int64_t on the C side, so constants are folded
238
+ first and then emitted as 64-bit literals to avoid wraparound from 32-bit
239
+ inference. Folding is abandoned when the exponent/shift is too large or the
240
+ result overflows, to avoid hanging the compiler.
241
+ """
242
+ if isinstance(node, ast.Constant):
243
+ if isinstance(node.value, int) and not isinstance(node.value, bool):
244
+ return node.value
245
+ return None
246
+ if isinstance(node, ast.UnaryOp):
247
+ value = fold_int_expr(node.operand)
248
+ if value is None:
249
+ return None
250
+ if isinstance(node.op, ast.USub):
251
+ return -value
252
+ if isinstance(node.op, ast.UAdd):
253
+ return value
254
+ if isinstance(node.op, ast.Invert):
255
+ return ~value
256
+ return None
257
+ if isinstance(node, ast.BinOp):
258
+ op = _INT_BINOPS.get(type(node.op))
259
+ if op is None:
260
+ return None
261
+ left = fold_int_expr(node.left)
262
+ right = fold_int_expr(node.right)
263
+ if left is None or right is None:
264
+ return None
265
+ if abs(left) > _FOLD_LIMIT or abs(right) > _FOLD_LIMIT:
266
+ return None
267
+ # An exponent/shift that is too large would hang the compiler and cannot
268
+ # fit in int64 anyway.
269
+ if isinstance(node.op, (ast.Pow, ast.LShift)) and not 0 <= right <= 128:
270
+ return None
271
+ try:
272
+ result = op(left, right)
273
+ except (ZeroDivisionError, ValueError, OverflowError, MemoryError):
274
+ return None
275
+ if abs(result) > _FOLD_LIMIT:
276
+ return None
277
+ return result
278
+ return None
embeddedpy/enums.py ADDED
@@ -0,0 +1,20 @@
1
+ """Enum category of embeddedpy: auto().
2
+
3
+ External usage: `from embeddedpy.enums import auto`.
4
+
5
+ The ``Enum`` type itself lives in ``embeddedpy.types`` (it is a language-level type
6
+ with member semantics); this module only provides **the function for auto-assigning
7
+ enum members**.
8
+ """
9
+
10
+ from .types import _Auto
11
+
12
+
13
+ def auto() -> _Auto:
14
+ """Auto-assign an enum member: one greater than the value of the previous member."""
15
+ return _Auto()
16
+
17
+
18
+ __all__ = [
19
+ "auto",
20
+ ]