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.
- embeddedpy/__init__.py +55 -0
- embeddedpy/arrays.py +142 -0
- embeddedpy/bytes.py +65 -0
- embeddedpy/compiler/__init__.py +55 -0
- embeddedpy/compiler/__main__.py +8 -0
- embeddedpy/compiler/api.py +337 -0
- embeddedpy/compiler/cgen_helpers.py +298 -0
- embeddedpy/compiler/checker.py +244 -0
- embeddedpy/compiler/checker_pass1.py +3229 -0
- embeddedpy/compiler/checker_pass2.py +1879 -0
- embeddedpy/compiler/cli.py +310 -0
- embeddedpy/compiler/codegen.py +2407 -0
- embeddedpy/compiler/config.py +186 -0
- embeddedpy/compiler/errors.py +26 -0
- embeddedpy/compiler/frontend.py +381 -0
- embeddedpy/compiler/irtypes.py +663 -0
- embeddedpy/compiler/lang_api.py +163 -0
- embeddedpy/compiler/modules.py +583 -0
- embeddedpy/compiler/preprocessor.py +364 -0
- embeddedpy/compiler/runtime_lib.py +1395 -0
- embeddedpy/compiler/type_symbols.py +278 -0
- embeddedpy/enums.py +20 -0
- embeddedpy/interop.py +444 -0
- embeddedpy/io.py +119 -0
- embeddedpy/memory.py +196 -0
- embeddedpy/pointers.py +552 -0
- embeddedpy/strings.py +68 -0
- embeddedpy/types.py +510 -0
- embeddedpy-0.1.0.dist-info/METADATA +258 -0
- embeddedpy-0.1.0.dist-info/RECORD +34 -0
- embeddedpy-0.1.0.dist-info/WHEEL +5 -0
- embeddedpy-0.1.0.dist-info/entry_points.txt +2 -0
- embeddedpy-0.1.0.dist-info/licenses/LICENSE +21 -0
- embeddedpy-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1879 @@
|
|
|
1
|
+
"""Checker pass 2: precise semantic checking and annotation."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
from typing import List, Optional
|
|
5
|
+
|
|
6
|
+
from . import irtypes as T
|
|
7
|
+
from . import preprocessor as pp
|
|
8
|
+
from .type_symbols import (
|
|
9
|
+
FuncInfo, _ctype_of, _sizeof_size, undefined_name_message,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Pass2:
|
|
14
|
+
"""Pass 2: precise inference and validation of expressions and statements, with annotations for code generation."""
|
|
15
|
+
def _infer_arg_against(self, arg: ast.AST, pt: T.Type) -> T.Type:
|
|
16
|
+
"""Pass 2: when a parameter is declared as array[T], the element type of an argument literal follows the parameter."""
|
|
17
|
+
pr = T.resolve(pt)
|
|
18
|
+
if isinstance(pr, T.Array) and isinstance(arg, ast.List):
|
|
19
|
+
return self._array_literal_type(arg, self._infer_expr, pr)
|
|
20
|
+
return self._infer_expr(arg)
|
|
21
|
+
|
|
22
|
+
def _char_from_str(self, target_type: T.Type, value_node: ast.AST,
|
|
23
|
+
explicit: bool = False) -> Optional[T.Scalar]:
|
|
24
|
+
"""A single-byte character type accepts a literal; on success attach ``_char_codepoint`` and return the target scalar.
|
|
25
|
+
|
|
26
|
+
char takes string literals, schar / uchar take bytes literals: the literal form must match
|
|
27
|
+
the printed form of the type so both tracks agree byte for byte. Cross-form use requires
|
|
28
|
+
explicit construction, where explicit=True skips the form check. A multibyte literal does
|
|
29
|
+
not fit in one byte and is rejected. Returns None when not applicable.
|
|
30
|
+
"""
|
|
31
|
+
tr = T.resolve(target_type)
|
|
32
|
+
if not (isinstance(tr, T.Scalar) and T.is_byte_char(tr)):
|
|
33
|
+
return None
|
|
34
|
+
if not isinstance(value_node, ast.Constant):
|
|
35
|
+
return None
|
|
36
|
+
value = value_node.value
|
|
37
|
+
if not (isinstance(value, str) or isinstance(value, bytes)):
|
|
38
|
+
return None
|
|
39
|
+
if not explicit:
|
|
40
|
+
if tr.text and isinstance(value, bytes):
|
|
41
|
+
self._error(
|
|
42
|
+
value_node,
|
|
43
|
+
f"a {tr.name} takes a string literal; use uchar for bytes "
|
|
44
|
+
f"or write {tr.name}({value!r}) to convert it explicitly",
|
|
45
|
+
)
|
|
46
|
+
return tr
|
|
47
|
+
if not tr.text and isinstance(value, str):
|
|
48
|
+
self._error(
|
|
49
|
+
value_node,
|
|
50
|
+
f"a {tr.name} takes a bytes literal; use char for text "
|
|
51
|
+
f"or write {tr.name}({value!r}) to convert it explicitly",
|
|
52
|
+
)
|
|
53
|
+
return tr
|
|
54
|
+
verb = "convert" if explicit else "assign"
|
|
55
|
+
if isinstance(value, str):
|
|
56
|
+
# Take the first byte of the string encoded as UTF-8; multibyte (non-ASCII) characters do not fit.
|
|
57
|
+
encoded = value.encode("utf-8")
|
|
58
|
+
if len(encoded) == 0:
|
|
59
|
+
self._error(
|
|
60
|
+
value_node,
|
|
61
|
+
f"cannot {verb} an empty string to a {tr.name} "
|
|
62
|
+
"(it has no first character)",
|
|
63
|
+
)
|
|
64
|
+
return tr
|
|
65
|
+
if len(encoded) > 1:
|
|
66
|
+
self._error(
|
|
67
|
+
value_node,
|
|
68
|
+
f"cannot {verb} a {len(encoded)}-byte string literal to a "
|
|
69
|
+
f"{tr.name} (it holds one byte)",
|
|
70
|
+
)
|
|
71
|
+
return tr
|
|
72
|
+
value_node._char_codepoint = encoded[0]
|
|
73
|
+
else:
|
|
74
|
+
if len(value) == 0:
|
|
75
|
+
self._error(
|
|
76
|
+
value_node,
|
|
77
|
+
f"cannot {verb} an empty bytes literal to a {tr.name} "
|
|
78
|
+
"(it has no first byte)",
|
|
79
|
+
)
|
|
80
|
+
return tr
|
|
81
|
+
if len(value) > 1:
|
|
82
|
+
self._error(
|
|
83
|
+
value_node,
|
|
84
|
+
f"cannot {verb} a {len(value)}-byte bytes literal to a "
|
|
85
|
+
f"{tr.name} (it holds one byte)",
|
|
86
|
+
)
|
|
87
|
+
return tr
|
|
88
|
+
value_node._char_codepoint = value[0]
|
|
89
|
+
# Give code generation a definite type (the plain str inference path does not set it)
|
|
90
|
+
value_node._etype = tr
|
|
91
|
+
return tr
|
|
92
|
+
|
|
93
|
+
def _check_make_array(self, node: ast.Call) -> T.Type:
|
|
94
|
+
"""Pass 2: validate make_array arguments and attach a length annotation for code generation."""
|
|
95
|
+
if node.keywords:
|
|
96
|
+
self._error(node, "make_array does not support keyword arguments")
|
|
97
|
+
if len(node.args) != 2:
|
|
98
|
+
self._error(node, "make_array takes two arguments: make_array(element_type, length)")
|
|
99
|
+
elem = self._resolve_annotation(node.args[0])
|
|
100
|
+
length = self._const_length(node.args[1])
|
|
101
|
+
if length is None:
|
|
102
|
+
n_t = self._infer_expr(node.args[1])
|
|
103
|
+
r = T.resolve(n_t)
|
|
104
|
+
if not isinstance(r, T.ConstInt):
|
|
105
|
+
self._error(node.args[1], "make_array length must be a compile-time integer literal")
|
|
106
|
+
length = r.value
|
|
107
|
+
if length <= 0:
|
|
108
|
+
self._error(node.args[1], "make_array length must be a positive integer")
|
|
109
|
+
node._array_elem = elem
|
|
110
|
+
node._array_len = length
|
|
111
|
+
node._is_make_array = True
|
|
112
|
+
node._etype = T.Array(elem, length)
|
|
113
|
+
return node._etype
|
|
114
|
+
|
|
115
|
+
def _check_function(self, fi: FuncInfo) -> None:
|
|
116
|
+
self.func = fi
|
|
117
|
+
self.loop_depth = 0
|
|
118
|
+
body = list(fi.node.body)
|
|
119
|
+
for stmt in body:
|
|
120
|
+
if self._is_docstring(stmt):
|
|
121
|
+
continue
|
|
122
|
+
self._check_stmt(stmt)
|
|
123
|
+
self.func = None
|
|
124
|
+
|
|
125
|
+
@staticmethod
|
|
126
|
+
def _is_aggregate_alias_rhs(value: ast.AST, vt: T.Type) -> bool:
|
|
127
|
+
"""Whether the RHS of an aggregate assignment is a reference to an existing object.
|
|
128
|
+
|
|
129
|
+
Constructing a new value (list literal, struct construction, make_array, copy_aggregate) is allowed;
|
|
130
|
+
binding an existing array/struct variable, field, element, or an aggregate returned by a function
|
|
131
|
+
directly to another name creates a second reference and is rejected at compile time.
|
|
132
|
+
"""
|
|
133
|
+
r = T.resolve(vt)
|
|
134
|
+
if not isinstance(r, (T.Struct, T.Array)):
|
|
135
|
+
return False
|
|
136
|
+
# List literals and any call (construction, make_array, copy_aggregate, function return)
|
|
137
|
+
# produce a new value; only expressions that explicitly reference an existing object create a second reference.
|
|
138
|
+
if isinstance(value, (ast.List, ast.Call)):
|
|
139
|
+
return False
|
|
140
|
+
return True
|
|
141
|
+
|
|
142
|
+
def _reject_aggregate_alias(self, target: ast.expr, value: ast.AST, vt: T.Type) -> None:
|
|
143
|
+
"""Aggregate binding: arrays of unknown length and references to existing objects are rejected at compile time."""
|
|
144
|
+
r = T.resolve(vt)
|
|
145
|
+
if isinstance(r, T.Array) and r.length < 0:
|
|
146
|
+
self._error(
|
|
147
|
+
target,
|
|
148
|
+
"array length cannot be determined for this binding; "
|
|
149
|
+
"use a literal or make_array(T, N)",
|
|
150
|
+
)
|
|
151
|
+
return
|
|
152
|
+
if self._is_aggregate_alias_rhs(value, vt):
|
|
153
|
+
self._error(
|
|
154
|
+
target,
|
|
155
|
+
"cannot assign an aggregate by reference; use copy_aggregate(value) "
|
|
156
|
+
"for an independent copy or construct a new value",
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
def _reject_aggregate_slot(self, target: ast.expr, value_type: T.Type) -> None:
|
|
160
|
+
"""Writing an aggregate as a whole into an array element / struct field degrades to a value copy on the C side, breaking alias semantics; rejected at compile time."""
|
|
161
|
+
r = T.resolve(value_type)
|
|
162
|
+
if isinstance(r, (T.Struct, T.Array)):
|
|
163
|
+
self._error(
|
|
164
|
+
target,
|
|
165
|
+
"cannot assign an aggregate as a whole "
|
|
166
|
+
"to a field or element; assign individual fields or elements instead",
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
def _check_stmt(self, stmt: ast.stmt) -> None:
|
|
170
|
+
if isinstance(stmt, ast.Assign):
|
|
171
|
+
target = stmt.targets[0]
|
|
172
|
+
if isinstance(target, ast.Name):
|
|
173
|
+
alias = self._try_type_alias(stmt, target)
|
|
174
|
+
if alias is not None:
|
|
175
|
+
return
|
|
176
|
+
# A type alias can only be defined with c.typedef(Ptr[T]) / c.typedef(Func[[...], R]);
|
|
177
|
+
# it cannot be overwritten by a plain assignment
|
|
178
|
+
existing = self._lookup(target.id)
|
|
179
|
+
if existing is not None and existing.kind == "ptr_alias":
|
|
180
|
+
self._error(
|
|
181
|
+
target,
|
|
182
|
+
f"{target.id} is a type alias and can only be defined with "
|
|
183
|
+
f"c.typedef(Ptr[T]) or c.typedef(Func[[...], R]); it cannot be reassigned",
|
|
184
|
+
)
|
|
185
|
+
return
|
|
186
|
+
if isinstance(target, ast.Attribute):
|
|
187
|
+
vt = self._infer_expr(stmt.value)
|
|
188
|
+
self._reject_aggregate_slot(target, vt)
|
|
189
|
+
ot = T.resolve(self._infer_expr(target.value))
|
|
190
|
+
# A field assignment target can be a struct value or a pointer base (p->f = v)
|
|
191
|
+
acc = T.struct_field_access(ot)
|
|
192
|
+
if acc is None:
|
|
193
|
+
self._error(target, "can only assign to struct fields")
|
|
194
|
+
st, levels = acc
|
|
195
|
+
self._reject_extern_type_field(target, st, target.attr)
|
|
196
|
+
if target.attr not in st.fields:
|
|
197
|
+
self._error(target, f"struct {st.name} has no field {target.attr}")
|
|
198
|
+
ft = st.fields[target.attr]
|
|
199
|
+
try:
|
|
200
|
+
T.unify(ft, vt)
|
|
201
|
+
except T.TypesMismatch as exc:
|
|
202
|
+
self._error(stmt, str(exc))
|
|
203
|
+
stmt._target_kind = "field"
|
|
204
|
+
stmt._field_obj = target.value
|
|
205
|
+
stmt._field_name = target.attr
|
|
206
|
+
stmt._field_ptr_levels = levels
|
|
207
|
+
return
|
|
208
|
+
if isinstance(target, ast.Subscript):
|
|
209
|
+
vt = self._infer_expr(stmt.value)
|
|
210
|
+
self._reject_aggregate_slot(target, vt)
|
|
211
|
+
bt = T.resolve(self._infer_expr(target.value))
|
|
212
|
+
# Elements of a const array are not writable
|
|
213
|
+
self._check_const_container(target.value)
|
|
214
|
+
# Subscript assignment requires a fixed-length array.
|
|
215
|
+
if isinstance(bt, T.Ptr):
|
|
216
|
+
self._error(
|
|
217
|
+
target,
|
|
218
|
+
"pointers do not support subscripting; write a value with "
|
|
219
|
+
"ptr.poke(p, v)",
|
|
220
|
+
)
|
|
221
|
+
return
|
|
222
|
+
if isinstance(bt, T.Array):
|
|
223
|
+
idx_t = self._infer_expr(target.slice)
|
|
224
|
+
if not (T.is_int(idx_t) or T.is_bool(idx_t)):
|
|
225
|
+
self._error(target.slice, "array subscript must be an integer")
|
|
226
|
+
try:
|
|
227
|
+
T.unify(bt.element, vt)
|
|
228
|
+
except T.TypesMismatch as exc:
|
|
229
|
+
self._error(stmt, str(exc))
|
|
230
|
+
else:
|
|
231
|
+
self._error(target, "subscript-assignment target must be a fixed-length array")
|
|
232
|
+
return
|
|
233
|
+
stmt._target_kind = "subscript"
|
|
234
|
+
stmt._subscript_obj = target.value
|
|
235
|
+
stmt._subscript_idx = target.slice
|
|
236
|
+
stmt._subscript_target_type = bt.element
|
|
237
|
+
return
|
|
238
|
+
sym = self._target_symbol(target)
|
|
239
|
+
if sym.static_object:
|
|
240
|
+
self._error(
|
|
241
|
+
stmt,
|
|
242
|
+
f"{sym.name} is a static C object and cannot be reassigned; "
|
|
243
|
+
"write the initializer in its declaration",
|
|
244
|
+
code="unsupported",
|
|
245
|
+
)
|
|
246
|
+
vt = self._infer_expr(stmt.value)
|
|
247
|
+
ch = self._char_from_str(sym.type, stmt.value)
|
|
248
|
+
if ch is not None:
|
|
249
|
+
vt = ch
|
|
250
|
+
self._reject_aggregate_alias(target, stmt.value, vt)
|
|
251
|
+
self._bind(sym, vt, stmt)
|
|
252
|
+
stmt._symbol = sym
|
|
253
|
+
return
|
|
254
|
+
if isinstance(stmt, ast.AnnAssign):
|
|
255
|
+
self._check_ann_assign(stmt)
|
|
256
|
+
return
|
|
257
|
+
if isinstance(stmt, ast.AugAssign):
|
|
258
|
+
self._check_aug_assign(stmt)
|
|
259
|
+
return
|
|
260
|
+
if isinstance(stmt, ast.Expr):
|
|
261
|
+
if isinstance(stmt.value, ast.Call):
|
|
262
|
+
if getattr(stmt, "_pp_block_decl", False):
|
|
263
|
+
return # named declarations inside a conditional block are compile-time text; pass 1 already validated the arguments
|
|
264
|
+
if self._is_c_include_call(stmt.value):
|
|
265
|
+
return # c.include is handled in _collect_includes
|
|
266
|
+
if pp.is_pp_directive_call(stmt.value):
|
|
267
|
+
return # preprocessor directives are compile-time text; pass 1 already validated the arguments
|
|
268
|
+
if getattr(stmt.value, "_c_stmt", None) is not None:
|
|
269
|
+
return # statement-level builtin (c.barrier()); pass 1 already validated the arguments
|
|
270
|
+
self._infer_expr(stmt.value)
|
|
271
|
+
return
|
|
272
|
+
self._error(stmt, "only function calls or string literals are allowed as expression statements")
|
|
273
|
+
if isinstance(stmt, ast.Return):
|
|
274
|
+
self._check_return(stmt)
|
|
275
|
+
return
|
|
276
|
+
if isinstance(stmt, ast.If):
|
|
277
|
+
if not getattr(stmt, "_pp_if", False):
|
|
278
|
+
self._require_cond(stmt.test)
|
|
279
|
+
for s in stmt.body:
|
|
280
|
+
self._check_stmt(s)
|
|
281
|
+
for s in stmt.orelse:
|
|
282
|
+
self._check_stmt(s)
|
|
283
|
+
return
|
|
284
|
+
if isinstance(stmt, ast.While):
|
|
285
|
+
self._require_cond(stmt.test)
|
|
286
|
+
self.loop_depth += 1
|
|
287
|
+
for s in stmt.body:
|
|
288
|
+
self._check_stmt(s)
|
|
289
|
+
self.loop_depth -= 1
|
|
290
|
+
return
|
|
291
|
+
if isinstance(stmt, ast.For):
|
|
292
|
+
self._check_for(stmt)
|
|
293
|
+
return
|
|
294
|
+
if isinstance(stmt, ast.Break):
|
|
295
|
+
if self.loop_depth == 0:
|
|
296
|
+
self._error(stmt, "'break' must be inside a loop")
|
|
297
|
+
return
|
|
298
|
+
if isinstance(stmt, ast.Continue):
|
|
299
|
+
if self.loop_depth == 0:
|
|
300
|
+
self._error(stmt, "'continue' must be inside a loop")
|
|
301
|
+
return
|
|
302
|
+
if isinstance(stmt, ast.Pass):
|
|
303
|
+
return
|
|
304
|
+
if isinstance(stmt, (ast.Import, ast.ImportFrom)):
|
|
305
|
+
return
|
|
306
|
+
if isinstance(stmt, ast.FunctionDef):
|
|
307
|
+
return
|
|
308
|
+
self._error(stmt, f"statement {type(stmt).__name__} is not supported")
|
|
309
|
+
|
|
310
|
+
def _check_const_container(self, node: ast.AST) -> None:
|
|
311
|
+
"""Elements of a const array are not writable: an assignment such as BUF[0] = 1 must be an error."""
|
|
312
|
+
if not isinstance(node, ast.Name):
|
|
313
|
+
return
|
|
314
|
+
sym = self._lookup(node.id)
|
|
315
|
+
if sym is None or "const" not in sym.quals:
|
|
316
|
+
return
|
|
317
|
+
if isinstance(T.resolve(sym.type), T.Array):
|
|
318
|
+
self._error(node, f"{sym.name} is a const array; its elements cannot be modified")
|
|
319
|
+
|
|
320
|
+
def _check_ann_assign(self, stmt: ast.AnnAssign) -> None:
|
|
321
|
+
target = stmt.target
|
|
322
|
+
assert isinstance(target, ast.Name)
|
|
323
|
+
sym = self._target_symbol(target, check_const=False)
|
|
324
|
+
section = self._annotation_section(stmt.annotation)
|
|
325
|
+
ann, quals = self._resolve_annotated(stmt.annotation)
|
|
326
|
+
current = T.resolve(sym.type)
|
|
327
|
+
# Distinguishing a first declaration from a repeated annotation is done in pass 1 (sym.declared);
|
|
328
|
+
# here only qualifiers are filled in, without repeating the const check.
|
|
329
|
+
sym.quals = self._merge_quals(sym.quals, quals)
|
|
330
|
+
if section:
|
|
331
|
+
sym.section = section
|
|
332
|
+
if stmt.value is None:
|
|
333
|
+
# Plain declaration: pass 1 already fixed the type; here only attach the annotations needed for generation
|
|
334
|
+
if "const" in sym.quals:
|
|
335
|
+
self._error(stmt, "const variable requires an initializer")
|
|
336
|
+
if isinstance(current, T.TVar):
|
|
337
|
+
sym.type = ann
|
|
338
|
+
stmt._symbol = sym
|
|
339
|
+
return
|
|
340
|
+
if "const" in sym.quals:
|
|
341
|
+
# A const variable must be initialized at its declaration (in C, const cannot be assigned later)
|
|
342
|
+
if sym.kind == "global":
|
|
343
|
+
if not self._is_const_expr(stmt.value):
|
|
344
|
+
self._error(
|
|
345
|
+
stmt.value,
|
|
346
|
+
"const global variable initializer must be a compile-time constant"
|
|
347
|
+
" (C requires static initialization)",
|
|
348
|
+
)
|
|
349
|
+
sym.init_node = stmt.value
|
|
350
|
+
else:
|
|
351
|
+
stmt._const_decl = True
|
|
352
|
+
if isinstance(current, T.TVar):
|
|
353
|
+
sym.type = ann
|
|
354
|
+
elif not self._ann_compatible(current, ann):
|
|
355
|
+
self._error(
|
|
356
|
+
target,
|
|
357
|
+
f"annotation of {target.id} is {T.describe(ann)}, "
|
|
358
|
+
f"but it was previously inferred as {T.describe(current)}",
|
|
359
|
+
)
|
|
360
|
+
vt = self._infer_annotated_value(stmt.value, ann)
|
|
361
|
+
ch = self._char_from_str(ann, stmt.value)
|
|
362
|
+
if ch is not None:
|
|
363
|
+
vt = ch
|
|
364
|
+
self._reject_aggregate_alias(target, stmt.value, vt)
|
|
365
|
+
self._bind(sym, vt, stmt)
|
|
366
|
+
stmt._symbol = sym
|
|
367
|
+
|
|
368
|
+
def _infer_annotated_value(self, value: ast.AST, ann: T.Type) -> T.Type:
|
|
369
|
+
"""Pass 2: for an annotated assignment, the annotation takes precedence in deciding the element type."""
|
|
370
|
+
if isinstance(ann, T.Array) and isinstance(value, ast.List):
|
|
371
|
+
return self._array_literal_type(value, self._infer_expr, ann)
|
|
372
|
+
return self._infer_expr(value)
|
|
373
|
+
|
|
374
|
+
def _check_aug_assign(self, stmt: ast.AugAssign) -> None:
|
|
375
|
+
target = stmt.target
|
|
376
|
+
op = stmt.op
|
|
377
|
+
rt = self._infer_expr(stmt.value)
|
|
378
|
+
|
|
379
|
+
if isinstance(target, ast.Subscript):
|
|
380
|
+
bt = T.resolve(self._infer_expr(target.value))
|
|
381
|
+
# Elements of a const array are not writable
|
|
382
|
+
self._check_const_container(target.value)
|
|
383
|
+
# Subscript augmented assignment requires a fixed-length array.
|
|
384
|
+
if isinstance(bt, T.Ptr):
|
|
385
|
+
self._error(
|
|
386
|
+
target,
|
|
387
|
+
"pointers do not support subscripting; write a value with "
|
|
388
|
+
"ptr.poke(p, v)",
|
|
389
|
+
)
|
|
390
|
+
return
|
|
391
|
+
if isinstance(bt, T.Array):
|
|
392
|
+
idx_t = self._infer_expr(target.slice)
|
|
393
|
+
if not (T.is_int(idx_t) or T.is_bool(idx_t)):
|
|
394
|
+
self._error(target.slice, "array subscript must be an integer")
|
|
395
|
+
current = T.resolve(bt.element)
|
|
396
|
+
if not (T.is_numeric(current) and T.is_numeric(rt)):
|
|
397
|
+
self._error(stmt, f"operator {type(op).__name__} is not supported for this type")
|
|
398
|
+
try:
|
|
399
|
+
unified = T.unify(current, rt)
|
|
400
|
+
except T.TypesMismatch as exc:
|
|
401
|
+
self._error(stmt, str(exc))
|
|
402
|
+
if isinstance(op, ast.Div):
|
|
403
|
+
if not T.is_float(current):
|
|
404
|
+
self._error(stmt, "augmented division requires the left operand to be a float")
|
|
405
|
+
op_type: T.Type = T.F64
|
|
406
|
+
else:
|
|
407
|
+
if not T.same(unified, current):
|
|
408
|
+
self._error(stmt, "augmented-assignment result type does not match the target")
|
|
409
|
+
op_type = T.base(current)
|
|
410
|
+
stmt._target_kind = "subscript_aug"
|
|
411
|
+
stmt._subscript_obj = target.value
|
|
412
|
+
stmt._subscript_idx = target.slice
|
|
413
|
+
stmt._subscript_target_type = bt.element
|
|
414
|
+
stmt._aug_op_type = op_type
|
|
415
|
+
stmt._aug_rhs_type = rt
|
|
416
|
+
return
|
|
417
|
+
self._error(target, "subscript augmented-assignment target must be a fixed-length array")
|
|
418
|
+
|
|
419
|
+
assert isinstance(target, ast.Name)
|
|
420
|
+
sym = self._target_symbol(target)
|
|
421
|
+
current = T.resolve(sym.type)
|
|
422
|
+
if isinstance(current, (T.TVar, T.ConstInt, T.ConstFloat)):
|
|
423
|
+
self._error(target, f"variable {target.id} has not been type-inferred before use")
|
|
424
|
+
|
|
425
|
+
# Pointer augmented assignment: p += 1
|
|
426
|
+
if isinstance(current, T.Ptr):
|
|
427
|
+
if not isinstance(op, (ast.Add, ast.Sub)):
|
|
428
|
+
self._error(stmt, "pointers only support += and -=")
|
|
429
|
+
if not (T.is_int(rt) or T.is_bool(rt)):
|
|
430
|
+
self._error(stmt, "pointer offset must be an integer")
|
|
431
|
+
stmt._symbol = sym
|
|
432
|
+
stmt._aug_kind = "ptr_offset"
|
|
433
|
+
stmt._rhs_type = rt
|
|
434
|
+
return
|
|
435
|
+
|
|
436
|
+
if isinstance(op, ast.Add) and T.is_str(current):
|
|
437
|
+
if not T.is_str(rt):
|
|
438
|
+
self._error(stmt, "strings can only be concatenated with strings")
|
|
439
|
+
stmt._symbol = sym
|
|
440
|
+
stmt._rhs_type = rt
|
|
441
|
+
stmt._aug_kind = "str_concat"
|
|
442
|
+
return
|
|
443
|
+
|
|
444
|
+
if not (T.is_numeric(current) and T.is_numeric(rt)):
|
|
445
|
+
self._error(stmt, f"operator {type(op).__name__} is not supported for this type")
|
|
446
|
+
try:
|
|
447
|
+
unified = T.unify(current, rt)
|
|
448
|
+
except T.TypesMismatch as exc:
|
|
449
|
+
self._error(stmt, str(exc))
|
|
450
|
+
|
|
451
|
+
if isinstance(op, ast.Div):
|
|
452
|
+
if not T.is_float(current):
|
|
453
|
+
self._error(stmt, "augmented division requires the left operand to be a float variable")
|
|
454
|
+
stmt._op_type = T.F64
|
|
455
|
+
else:
|
|
456
|
+
if not T.same(unified, current):
|
|
457
|
+
self._error(
|
|
458
|
+
stmt,
|
|
459
|
+
f"{target.id} has type {T.describe(current)}, "
|
|
460
|
+
f"but the operation result is {T.describe(unified)}, with a width mismatch",
|
|
461
|
+
)
|
|
462
|
+
stmt._op_type = T.base(current)
|
|
463
|
+
|
|
464
|
+
stmt._symbol = sym
|
|
465
|
+
stmt._rhs_type = rt
|
|
466
|
+
|
|
467
|
+
def _check_return(self, stmt: ast.Return) -> None:
|
|
468
|
+
if self.func is None:
|
|
469
|
+
self._error(stmt, "'return' is only allowed inside functions")
|
|
470
|
+
assert self.func is not None
|
|
471
|
+
if stmt.value is None:
|
|
472
|
+
# Bare return: no value (C void)
|
|
473
|
+
rt = T.VOID
|
|
474
|
+
else:
|
|
475
|
+
rt = self._infer_expr(stmt.value)
|
|
476
|
+
ch = self._char_from_str(self.func.ret, stmt.value)
|
|
477
|
+
if ch is not None:
|
|
478
|
+
rt = ch
|
|
479
|
+
self.func.has_value_return = True
|
|
480
|
+
try:
|
|
481
|
+
unified = T.unify(self.func.ret, rt)
|
|
482
|
+
except T.TypesMismatch as exc:
|
|
483
|
+
self._error(stmt, f"return type mismatch: {exc}")
|
|
484
|
+
current = T.resolve(self.func.ret)
|
|
485
|
+
if not isinstance(current, T.TVar) and not T.same(unified, current):
|
|
486
|
+
self._error(
|
|
487
|
+
stmt,
|
|
488
|
+
f"function return type is {T.describe(current)}, "
|
|
489
|
+
f"but cannot return {T.describe(unified)}",
|
|
490
|
+
)
|
|
491
|
+
stmt._ret_type = current
|
|
492
|
+
|
|
493
|
+
def _check_for(self, stmt: ast.For) -> None:
|
|
494
|
+
target = stmt.target
|
|
495
|
+
assert isinstance(target, ast.Name)
|
|
496
|
+
it = stmt.iter
|
|
497
|
+
range_sym = self._lookup("range")
|
|
498
|
+
is_range = (
|
|
499
|
+
isinstance(it, ast.Call)
|
|
500
|
+
and isinstance(it.func, ast.Name)
|
|
501
|
+
and it.func.id == "range"
|
|
502
|
+
and range_sym is not None
|
|
503
|
+
and range_sym.kind == "builtin"
|
|
504
|
+
)
|
|
505
|
+
if not is_range:
|
|
506
|
+
# Fixed-length array iteration: for x in buf
|
|
507
|
+
it_t = T.resolve(self._infer_expr(it))
|
|
508
|
+
if not isinstance(it_t, T.Array):
|
|
509
|
+
self._error(it, "for loops only support range(...) or fixed-length array iteration")
|
|
510
|
+
elif it_t.length < 0 and not self._is_len_param(it):
|
|
511
|
+
self._error(it, "the iterated array length must be known at compile time")
|
|
512
|
+
sym = self._target_symbol(target)
|
|
513
|
+
self._bind(sym, it_t.element, target)
|
|
514
|
+
stmt._symbol = sym
|
|
515
|
+
stmt._for_array = it
|
|
516
|
+
stmt._for_array_type = it_t
|
|
517
|
+
stmt._for_array_len = it_t.length
|
|
518
|
+
self.loop_depth += 1
|
|
519
|
+
for s in stmt.body:
|
|
520
|
+
self._check_stmt(s)
|
|
521
|
+
self.loop_depth -= 1
|
|
522
|
+
return
|
|
523
|
+
assert isinstance(it, ast.Call)
|
|
524
|
+
if it.keywords:
|
|
525
|
+
self._error(it, "range does not support keyword arguments")
|
|
526
|
+
if not (1 <= len(it.args) <= 3):
|
|
527
|
+
self._error(it, "range requires 1 to 3 arguments")
|
|
528
|
+
arg_types = []
|
|
529
|
+
for index, a in enumerate(it.args):
|
|
530
|
+
if self._fold_range_arg(a, index):
|
|
531
|
+
arg_types.append(T.I64)
|
|
532
|
+
else:
|
|
533
|
+
arg_types.append(self._infer_expr(a))
|
|
534
|
+
for a, t in zip(it.args, arg_types):
|
|
535
|
+
if not (T.is_int(t) or T.is_bool(t)):
|
|
536
|
+
self._error(a, "range arguments must be integers")
|
|
537
|
+
it._range_types = [T.base(t) for t in arg_types]
|
|
538
|
+
|
|
539
|
+
sym = self._target_symbol(target)
|
|
540
|
+
self._bind(sym, T.I64, target)
|
|
541
|
+
stmt._symbol = sym
|
|
542
|
+
self.loop_depth += 1
|
|
543
|
+
for s in stmt.body:
|
|
544
|
+
self._check_stmt(s)
|
|
545
|
+
self.loop_depth -= 1
|
|
546
|
+
|
|
547
|
+
def _infer_expr(self, node: ast.AST) -> T.Type:
|
|
548
|
+
if isinstance(node, ast.Constant):
|
|
549
|
+
return self._infer_constant(node)
|
|
550
|
+
if isinstance(node, ast.Name):
|
|
551
|
+
if node.id in self._section_bindings:
|
|
552
|
+
self._error(
|
|
553
|
+
node,
|
|
554
|
+
f"section descriptor {node.id} may only be used as a type "
|
|
555
|
+
f"qualifier: {node.id}[T]",
|
|
556
|
+
code="unsupported",
|
|
557
|
+
)
|
|
558
|
+
sym = self._lookup(node.id)
|
|
559
|
+
if sym is None:
|
|
560
|
+
self._error(node, undefined_name_message(node.id), code="name")
|
|
561
|
+
assert sym is not None
|
|
562
|
+
if sym.kind in ("type", "module", "builtin"):
|
|
563
|
+
self._error(
|
|
564
|
+
node, f"{node.id} cannot be used as a value (use it only as a type annotation)", code="name"
|
|
565
|
+
)
|
|
566
|
+
if sym.kind == "func":
|
|
567
|
+
# In expression position a function name decays to a function pointer (as in C):
|
|
568
|
+
# a function name of int32 value -> Ptr[Func[[...], ret]].
|
|
569
|
+
fi = self.functions.get(node.id)
|
|
570
|
+
if fi is None:
|
|
571
|
+
self._error(node, f"function {node.id} is not defined", code="name")
|
|
572
|
+
node._etype = T.TVar()
|
|
573
|
+
return node._etype
|
|
574
|
+
ft = self._func_type_of(fi)
|
|
575
|
+
node._symbol = sym
|
|
576
|
+
node._etype = T.Ptr(ft)
|
|
577
|
+
return node._etype
|
|
578
|
+
if sym.kind == "ptr_type":
|
|
579
|
+
# Ptr itself is a "pointer type constructor": Ptr[T] evaluates to a type value
|
|
580
|
+
node._etype = T.PtrTypeValue(T.TVar())
|
|
581
|
+
node._ptr_ctor = True
|
|
582
|
+
return node._etype
|
|
583
|
+
if sym.kind == "array_type":
|
|
584
|
+
# Array only appears in type annotation position (Array[T]) and cannot be used as a plain value
|
|
585
|
+
self._error(
|
|
586
|
+
node,
|
|
587
|
+
f"{node.id} can only be used in type annotations (e.g. x: Array[int32])",
|
|
588
|
+
code="name",
|
|
589
|
+
)
|
|
590
|
+
node._etype = T.TVar()
|
|
591
|
+
return node._etype
|
|
592
|
+
if sym.kind == "ptr_alias":
|
|
593
|
+
# A type alias lives at the type level and cannot be used as a plain value
|
|
594
|
+
self._error(
|
|
595
|
+
node,
|
|
596
|
+
f"{node.id} is a type alias and cannot be used as a value (only valid in type annotations)",
|
|
597
|
+
code="name",
|
|
598
|
+
)
|
|
599
|
+
node._etype = T.TVar()
|
|
600
|
+
return node._etype
|
|
601
|
+
if sym.kind == "mem_module":
|
|
602
|
+
node._etype = T.VOID
|
|
603
|
+
node._mem_module = True
|
|
604
|
+
return node._etype
|
|
605
|
+
if sym.kind == "io_module":
|
|
606
|
+
node._etype = T.VOID
|
|
607
|
+
node._io_module = True
|
|
608
|
+
return node._etype
|
|
609
|
+
if sym.kind == "strings_module":
|
|
610
|
+
node._etype = T.VOID
|
|
611
|
+
node._strings_module = True
|
|
612
|
+
return node._etype
|
|
613
|
+
if sym.kind == "bytes_module":
|
|
614
|
+
node._etype = T.VOID
|
|
615
|
+
node._bytes_module = True
|
|
616
|
+
return node._etype
|
|
617
|
+
assert sym.type is not None
|
|
618
|
+
node._symbol = sym
|
|
619
|
+
node._etype = sym.type
|
|
620
|
+
return sym.type
|
|
621
|
+
if isinstance(node, ast.BinOp):
|
|
622
|
+
return self._check_binop(node)
|
|
623
|
+
if isinstance(node, ast.UnaryOp):
|
|
624
|
+
return self._check_unary(node)
|
|
625
|
+
if isinstance(node, ast.BoolOp):
|
|
626
|
+
for v in node.values:
|
|
627
|
+
self._require_cond(v)
|
|
628
|
+
node._etype = T.BOOL
|
|
629
|
+
return T.BOOL
|
|
630
|
+
if isinstance(node, ast.Compare):
|
|
631
|
+
return self._check_compare(node)
|
|
632
|
+
if isinstance(node, ast.JoinedStr):
|
|
633
|
+
return self._check_fstring(node)
|
|
634
|
+
if isinstance(node, ast.Call):
|
|
635
|
+
return self._check_call(node)
|
|
636
|
+
if isinstance(node, ast.IfExp):
|
|
637
|
+
self._require_cond(node.test)
|
|
638
|
+
a = self._infer_expr(node.body)
|
|
639
|
+
b = self._infer_expr(node.orelse)
|
|
640
|
+
try:
|
|
641
|
+
unified = T.unify(a, b)
|
|
642
|
+
except T.TypesMismatch as exc:
|
|
643
|
+
self._error(node, str(exc))
|
|
644
|
+
node._etype = unified
|
|
645
|
+
node._branch_type = unified
|
|
646
|
+
return unified
|
|
647
|
+
if isinstance(node, ast.Attribute):
|
|
648
|
+
# Enum member: Mode.RUN
|
|
649
|
+
enum_member = self._enum_member_type(node)
|
|
650
|
+
if enum_member is not None:
|
|
651
|
+
node._etype = enum_member
|
|
652
|
+
node._enum_member = True
|
|
653
|
+
return enum_member
|
|
654
|
+
vt = self._infer_expr(node.value)
|
|
655
|
+
# Struct field: struct value s.f, pointer base p->f / (*p)->f
|
|
656
|
+
acc = T.struct_field_access(vt)
|
|
657
|
+
if acc is not None:
|
|
658
|
+
st, levels = acc
|
|
659
|
+
self._reject_extern_type_field(node, st, node.attr)
|
|
660
|
+
if node.attr not in st.fields:
|
|
661
|
+
self._error(node, f"struct {st.name} has no field {node.attr}")
|
|
662
|
+
node._etype = st.fields[node.attr]
|
|
663
|
+
node._field_struct = st
|
|
664
|
+
node._field_name = node.attr
|
|
665
|
+
node._field_ptr_levels = levels
|
|
666
|
+
return node._etype
|
|
667
|
+
r = T.resolve(vt)
|
|
668
|
+
if isinstance(r, T.Ptr):
|
|
669
|
+
self._error(
|
|
670
|
+
node,
|
|
671
|
+
f"cannot access field {node.attr!r} through a pointer to "
|
|
672
|
+
f"{T.describe(r.target)}",
|
|
673
|
+
)
|
|
674
|
+
self._error(
|
|
675
|
+
node,
|
|
676
|
+
f"{self._member_path(node) or node.attr} cannot be used as a value; "
|
|
677
|
+
"only embeddedpy type casts are allowed",
|
|
678
|
+
)
|
|
679
|
+
if isinstance(node, ast.Subscript):
|
|
680
|
+
# Function pointer type construction: Func[[...], R] is itself a function pointer, stored internally as
|
|
681
|
+
# Ptr(Func(...)) (consistent with _type_expr in pass 1). Must be handled here before
|
|
682
|
+
# _infer_expr(node.value), otherwise Func as a type constructor has no value type and the assertion fails.
|
|
683
|
+
if isinstance(node.value, ast.Name):
|
|
684
|
+
base_sym = self.scope.get(node.value.id)
|
|
685
|
+
if base_sym is not None and base_sym.kind == "func_type":
|
|
686
|
+
node._etype = T.Ptr(self._resolve_func_annotation(node))
|
|
687
|
+
return node._etype
|
|
688
|
+
vt = self._infer_expr(node.value)
|
|
689
|
+
r = T.resolve(vt)
|
|
690
|
+
if isinstance(r, T.PtrTypeValue):
|
|
691
|
+
# Ptr[int32] in expression position: this is a "pointer type value",
|
|
692
|
+
# used for a type alias int32_ptr = Ptr[int32]
|
|
693
|
+
inner = self._resolve_annotation(node.slice)
|
|
694
|
+
node._etype = T.PtrTypeValue(inner)
|
|
695
|
+
node._ptr_type_value = True
|
|
696
|
+
return node._etype
|
|
697
|
+
if isinstance(r, T.Array):
|
|
698
|
+
idx_t = self._infer_expr(node.slice)
|
|
699
|
+
if not (T.is_int(idx_t) or T.is_bool(idx_t)):
|
|
700
|
+
self._error(node.slice, "array subscript must be an integer")
|
|
701
|
+
node._etype = r.element
|
|
702
|
+
node._array_base = node.value
|
|
703
|
+
node._array_index = node.slice
|
|
704
|
+
node._array_target = r.element
|
|
705
|
+
return r.element
|
|
706
|
+
if T.is_bytes(r):
|
|
707
|
+
# A bytes subscript yields a uchar: the result keeps the byte form and does not participate in arithmetic.
|
|
708
|
+
idx_t = self._infer_expr(node.slice)
|
|
709
|
+
if not (T.is_int(idx_t) or T.is_bool(idx_t)):
|
|
710
|
+
self._error(node.slice, "bytes subscript must be an integer")
|
|
711
|
+
node._etype = T.UCHAR
|
|
712
|
+
node._bytes_base = node.value
|
|
713
|
+
node._bytes_index = node.slice
|
|
714
|
+
return T.UCHAR
|
|
715
|
+
if T.is_str(r):
|
|
716
|
+
# A text subscript yields one character (char), indexed by UTF-8 code point.
|
|
717
|
+
idx_t = self._infer_expr(node.slice)
|
|
718
|
+
if not (T.is_int(idx_t) or T.is_bool(idx_t)):
|
|
719
|
+
self._error(node.slice, "string subscript must be an integer")
|
|
720
|
+
node._etype = T.CHAR
|
|
721
|
+
node._str_base = node.value
|
|
722
|
+
node._str_index = node.slice
|
|
723
|
+
return T.CHAR
|
|
724
|
+
if isinstance(r, T.Ptr):
|
|
725
|
+
# Pointers do not support subscripting: read with ptr.peek(p), move with ptr.skip(p, n).
|
|
726
|
+
self._error(
|
|
727
|
+
node,
|
|
728
|
+
"pointers do not support subscripting; read a value with "
|
|
729
|
+
"ptr.peek(p) and move with ptr.skip(p, n)",
|
|
730
|
+
)
|
|
731
|
+
return r.target
|
|
732
|
+
self._error(
|
|
733
|
+
node,
|
|
734
|
+
"subscripting is only allowed on fixed-length arrays, bytes, "
|
|
735
|
+
"or strings",
|
|
736
|
+
)
|
|
737
|
+
return r.element if isinstance(r, T.Array) else T.I32
|
|
738
|
+
if isinstance(node, ast.List):
|
|
739
|
+
return self._array_literal_type(node, self._infer_expr)
|
|
740
|
+
self._error(node, f"expression {type(node).__name__} is not supported")
|
|
741
|
+
|
|
742
|
+
def _infer_constant(self, node: ast.Constant) -> T.Type:
|
|
743
|
+
value = node.value
|
|
744
|
+
if isinstance(value, bool):
|
|
745
|
+
node._etype = T.BOOL
|
|
746
|
+
return T.BOOL
|
|
747
|
+
if isinstance(value, int):
|
|
748
|
+
if not (-(1 << 63) <= value <= (1 << 63) - 1):
|
|
749
|
+
self._error(node, "integer literal is out of int64 range")
|
|
750
|
+
node._etype = T.ConstInt(value)
|
|
751
|
+
return node._etype
|
|
752
|
+
if isinstance(value, float):
|
|
753
|
+
node._etype = T.ConstFloat(value)
|
|
754
|
+
return node._etype
|
|
755
|
+
if isinstance(value, str):
|
|
756
|
+
node._etype = T.STR
|
|
757
|
+
return T.STR
|
|
758
|
+
if isinstance(value, bytes):
|
|
759
|
+
node._etype = T.BYTES
|
|
760
|
+
return T.BYTES
|
|
761
|
+
if value is None:
|
|
762
|
+
self._error(
|
|
763
|
+
node,
|
|
764
|
+
"None is not supported in this language; use 'void' for C's void "
|
|
765
|
+
"(from embeddedpy.types import void) and 'ptr.null()' for a null pointer",
|
|
766
|
+
)
|
|
767
|
+
self._error(node, "complex values are not supported")
|
|
768
|
+
|
|
769
|
+
def _check_binop(self, node: ast.BinOp) -> T.Type:
|
|
770
|
+
lt = self._infer_expr(node.left)
|
|
771
|
+
rt = self._infer_expr(node.right)
|
|
772
|
+
op = node.op
|
|
773
|
+
lr = T.resolve(lt)
|
|
774
|
+
rr = T.resolve(rt)
|
|
775
|
+
lp = isinstance(lr, T.Ptr)
|
|
776
|
+
rp = isinstance(rr, T.Ptr)
|
|
777
|
+
|
|
778
|
+
# Pointer arithmetic
|
|
779
|
+
if lp or rp:
|
|
780
|
+
if isinstance(op, ast.Add):
|
|
781
|
+
if lp and rp:
|
|
782
|
+
self._error(node, "cannot add two pointers")
|
|
783
|
+
ptr_t = lr if lp else rr
|
|
784
|
+
int_t = rt if lp else lt
|
|
785
|
+
if not T.is_int(int_t):
|
|
786
|
+
self._error(node, "pointers can only be added to integers")
|
|
787
|
+
node._etype = ptr_t
|
|
788
|
+
node._ptr_arith = "add"
|
|
789
|
+
node._ptr_is_left = lp
|
|
790
|
+
return ptr_t
|
|
791
|
+
if isinstance(op, ast.Sub):
|
|
792
|
+
if lp and rp:
|
|
793
|
+
if not T.same(lr.target, rr.target):
|
|
794
|
+
self._error(node, "cannot subtract pointers of different types")
|
|
795
|
+
node._etype = T.I64
|
|
796
|
+
node._ptr_arith = "diff"
|
|
797
|
+
return T.I64
|
|
798
|
+
if lp:
|
|
799
|
+
if not T.is_int(rt):
|
|
800
|
+
self._error(node, "pointers can only be subtracted by integers")
|
|
801
|
+
node._etype = lr
|
|
802
|
+
node._ptr_arith = "sub"
|
|
803
|
+
return lr
|
|
804
|
+
self._error(node, "cannot subtract a pointer from an integer")
|
|
805
|
+
self._error(node, f"pointers do not support operator {type(op).__name__}")
|
|
806
|
+
|
|
807
|
+
if isinstance(op, ast.Add) and (T.is_str(lt) or T.is_str(rt)):
|
|
808
|
+
if not (T.is_str(lt) and T.is_str(rt)):
|
|
809
|
+
self._error(node, "strings can only be concatenated with strings")
|
|
810
|
+
node._etype = T.STR
|
|
811
|
+
node._op_type = T.STR
|
|
812
|
+
node._lcast = T.STR
|
|
813
|
+
node._rcast = T.STR
|
|
814
|
+
node._aug_kind = "str_concat"
|
|
815
|
+
return T.STR
|
|
816
|
+
|
|
817
|
+
if not (T.is_numeric(lt) and T.is_numeric(rt)):
|
|
818
|
+
self._error(node, f"operator {type(op).__name__} is not supported for this type")
|
|
819
|
+
|
|
820
|
+
try:
|
|
821
|
+
unified = T.unify(lt, rt)
|
|
822
|
+
except T.TypesMismatch as exc:
|
|
823
|
+
self._error(node, str(exc))
|
|
824
|
+
|
|
825
|
+
if isinstance(T.resolve(unified), T.Enum):
|
|
826
|
+
# Enums in arithmetic are promoted to int following C integer promotion
|
|
827
|
+
unified = T.I32
|
|
828
|
+
|
|
829
|
+
if isinstance(op, ast.Div):
|
|
830
|
+
op_type = T.F64
|
|
831
|
+
result = T.F64
|
|
832
|
+
elif isinstance(op, (ast.FloorDiv, ast.Mod, ast.Pow)):
|
|
833
|
+
if T.is_float(unified):
|
|
834
|
+
op_type = T.F64
|
|
835
|
+
result = T.F64
|
|
836
|
+
else:
|
|
837
|
+
op_type = T.base(unified)
|
|
838
|
+
result = op_type
|
|
839
|
+
elif isinstance(op, (ast.LShift, ast.RShift, ast.BitAnd, ast.BitOr, ast.BitXor)):
|
|
840
|
+
# Enums have an integer underlying type and can take part in bitwise operations (common for register bit definitions)
|
|
841
|
+
if not (
|
|
842
|
+
(T.is_int(lt) or T.is_enum(lt))
|
|
843
|
+
and (T.is_int(rt) or T.is_enum(rt))
|
|
844
|
+
):
|
|
845
|
+
self._error(node, "bitwise operations require integer operands")
|
|
846
|
+
op_type = T.base(unified)
|
|
847
|
+
result = op_type
|
|
848
|
+
elif isinstance(op, (ast.Add, ast.Sub, ast.Mult)):
|
|
849
|
+
if T.is_bool(unified):
|
|
850
|
+
op_type = T.I32
|
|
851
|
+
else:
|
|
852
|
+
op_type = T.base(unified)
|
|
853
|
+
result = op_type
|
|
854
|
+
else:
|
|
855
|
+
self._error(node, f"operator {type(op).__name__} is not supported")
|
|
856
|
+
|
|
857
|
+
node._op_type = op_type
|
|
858
|
+
node._lcast = op_type
|
|
859
|
+
node._rcast = op_type
|
|
860
|
+
node._etype = result
|
|
861
|
+
return result
|
|
862
|
+
|
|
863
|
+
def _check_unary(self, node: ast.UnaryOp) -> T.Type:
|
|
864
|
+
t = self._infer_expr(node.operand)
|
|
865
|
+
node._operand_type = t
|
|
866
|
+
if isinstance(node.op, ast.Not):
|
|
867
|
+
if not (T.is_bool(t) or T.is_int(t) or T.is_ptr(t)):
|
|
868
|
+
self._error(node, "'not' operand must be bool, integer, or pointer")
|
|
869
|
+
node.operand._cond_type = T.base(t) if not T.is_ptr(t) else t
|
|
870
|
+
node._etype = T.BOOL
|
|
871
|
+
return T.BOOL
|
|
872
|
+
r = T.resolve(t)
|
|
873
|
+
if isinstance(r, (T.ConstInt, T.ConstFloat)):
|
|
874
|
+
negate = isinstance(node.op, ast.USub)
|
|
875
|
+
if isinstance(r, T.ConstInt):
|
|
876
|
+
result: T.Type = T.ConstInt(-r.value if negate else r.value)
|
|
877
|
+
else:
|
|
878
|
+
result = T.ConstFloat(-r.value if negate else r.value)
|
|
879
|
+
node._etype = result
|
|
880
|
+
node._operand_type = t
|
|
881
|
+
node._operand_cast = T.base(r)
|
|
882
|
+
return result
|
|
883
|
+
if not T.is_numeric(t):
|
|
884
|
+
self._error(node, f"unary operator {type(node.op).__name__} requires a numeric operand")
|
|
885
|
+
if isinstance(node.op, ast.Invert):
|
|
886
|
+
if not (T.is_int(t) or T.is_bool(t)):
|
|
887
|
+
self._error(node, "'~' operand must be an integer")
|
|
888
|
+
if T.is_bool(t):
|
|
889
|
+
t = T.I32
|
|
890
|
+
node._etype = T.base(t)
|
|
891
|
+
node._operand_cast = T.base(t)
|
|
892
|
+
return node._etype
|
|
893
|
+
|
|
894
|
+
def _check_compare(self, node: ast.Compare) -> T.Type:
|
|
895
|
+
operands = [node.left] + list(node.comparators)
|
|
896
|
+
types = [self._infer_expr(o) for o in operands]
|
|
897
|
+
# Different enums cannot be compared (their underlying type is int, so this is easy to get wrong)
|
|
898
|
+
owners = [
|
|
899
|
+
(getattr(o, "_enum_owner", None), o)
|
|
900
|
+
for o in operands
|
|
901
|
+
if getattr(o, "_enum_owner", None) is not None
|
|
902
|
+
]
|
|
903
|
+
if len(owners) > 1:
|
|
904
|
+
first = owners[0][0]
|
|
905
|
+
for owner, _ in owners[1:]:
|
|
906
|
+
if first.name != owner.name:
|
|
907
|
+
self._error(
|
|
908
|
+
node,
|
|
909
|
+
f"different enums {first.name} and {owner.name} cannot be compared",
|
|
910
|
+
)
|
|
911
|
+
ct = types[0]
|
|
912
|
+
for other in types[1:]:
|
|
913
|
+
try:
|
|
914
|
+
ct = T.unify(ct, other)
|
|
915
|
+
except T.TypesMismatch as exc:
|
|
916
|
+
self._error(node, str(exc))
|
|
917
|
+
if T.is_void(T.resolve(ct)):
|
|
918
|
+
self._error(node, "cannot compare void")
|
|
919
|
+
for mid in node.comparators[:-1]:
|
|
920
|
+
if not isinstance(mid, (ast.Name, ast.Constant)):
|
|
921
|
+
self._error(
|
|
922
|
+
mid, "chained comparison middle operand must be a variable or constant to avoid repeated evaluation"
|
|
923
|
+
)
|
|
924
|
+
node._cmp_type = ct
|
|
925
|
+
node._etype = T.BOOL
|
|
926
|
+
return T.BOOL
|
|
927
|
+
|
|
928
|
+
# ---------------------------------------------------------------- f-string
|
|
929
|
+
|
|
930
|
+
def _check_fstring(self, node: ast.JoinedStr) -> T.Type:
|
|
931
|
+
"""Pass 2: validate f-string field types and translate format specs into C printf specifications."""
|
|
932
|
+
for v in node.values:
|
|
933
|
+
if not isinstance(v, ast.FormattedValue):
|
|
934
|
+
continue
|
|
935
|
+
if v.conversion != -1:
|
|
936
|
+
self._error(v, "f-string conversions (!r / !s / !a) are not supported")
|
|
937
|
+
continue
|
|
938
|
+
ft = self._infer_expr(v.value)
|
|
939
|
+
kind = self._fstring_kind(v.value, ft)
|
|
940
|
+
spec = self._fstring_spec_text(v)
|
|
941
|
+
if spec is None or kind is None:
|
|
942
|
+
v._fmt_kind = None
|
|
943
|
+
v._fmt_cfmt = None
|
|
944
|
+
continue
|
|
945
|
+
cfmt = self._translate_fstring_spec(v, spec, kind)
|
|
946
|
+
# bool with a format spec is handled as an integer (same as Python: f"{True:5}" -> " 1")
|
|
947
|
+
v._fmt_kind = "i64" if kind == "bool" else kind
|
|
948
|
+
v._fmt_cfmt = cfmt
|
|
949
|
+
node._etype = T.STR
|
|
950
|
+
return T.STR
|
|
951
|
+
|
|
952
|
+
def _fstring_kind(self, node: ast.AST, ft: T.Type) -> Optional[str]:
|
|
953
|
+
"""Format category of a field: i64 / u64 / f64 / str / bool."""
|
|
954
|
+
r = T.resolve(ft)
|
|
955
|
+
if T.is_str(r):
|
|
956
|
+
return "str"
|
|
957
|
+
if T.is_bool(r):
|
|
958
|
+
return "bool"
|
|
959
|
+
s = T.base(r)
|
|
960
|
+
if s.category == "float":
|
|
961
|
+
return "f64"
|
|
962
|
+
if s.category == "int":
|
|
963
|
+
return "i64" if s.signed else "u64"
|
|
964
|
+
self._error(
|
|
965
|
+
node,
|
|
966
|
+
f"f-string fields must be numeric, bool or Str, not {T.describe(r)}",
|
|
967
|
+
)
|
|
968
|
+
return None
|
|
969
|
+
|
|
970
|
+
def _fstring_spec_text(self, v: ast.FormattedValue) -> Optional[str]:
|
|
971
|
+
"""Get the literal text of a format spec (only pure literals, no nested fields)."""
|
|
972
|
+
fs = v.format_spec
|
|
973
|
+
if fs is None:
|
|
974
|
+
return None
|
|
975
|
+
if isinstance(fs, ast.Constant) and isinstance(fs.value, str):
|
|
976
|
+
return fs.value
|
|
977
|
+
if isinstance(fs, ast.JoinedStr):
|
|
978
|
+
# CPython parses format_spec into a JoinedStr (which may itself be an f-string)
|
|
979
|
+
parts: List[str] = []
|
|
980
|
+
for item in fs.values:
|
|
981
|
+
if isinstance(item, ast.Constant) and isinstance(item.value, str):
|
|
982
|
+
parts.append(item.value)
|
|
983
|
+
else:
|
|
984
|
+
self._error(
|
|
985
|
+
fs, "f-string format spec must be a literal (nested fields are not supported)"
|
|
986
|
+
)
|
|
987
|
+
return None
|
|
988
|
+
return "".join(parts)
|
|
989
|
+
self._error(fs, "f-string format spec must be a literal")
|
|
990
|
+
return None
|
|
991
|
+
|
|
992
|
+
def _translate_fstring_spec(
|
|
993
|
+
self, v: ast.FormattedValue, spec: str, kind: str
|
|
994
|
+
) -> str:
|
|
995
|
+
"""Translate a Python format spec into a C printf specification.
|
|
996
|
+
|
|
997
|
+
Supports: ``[align][0][width][.precision][type]``
|
|
998
|
+
Does not support: non-zero fill characters, ``^`` centering, ``,`` grouping, ``#`` prefix, nested fields.
|
|
999
|
+
"""
|
|
1000
|
+
i = 0
|
|
1001
|
+
align = ""
|
|
1002
|
+
if spec[:1] in ("<", ">"):
|
|
1003
|
+
align = spec[0]
|
|
1004
|
+
i = 1
|
|
1005
|
+
elif spec[:1] == "^":
|
|
1006
|
+
self._error(v, "f-string alignment '^' (center) is not supported")
|
|
1007
|
+
return ""
|
|
1008
|
+
zero = False
|
|
1009
|
+
if i < len(spec) and spec[i] == "0":
|
|
1010
|
+
zero = True
|
|
1011
|
+
i += 1
|
|
1012
|
+
width = ""
|
|
1013
|
+
while i < len(spec) and spec[i].isdigit():
|
|
1014
|
+
width += spec[i]
|
|
1015
|
+
i += 1
|
|
1016
|
+
precision = ""
|
|
1017
|
+
if i < len(spec) and spec[i] == ".":
|
|
1018
|
+
i += 1
|
|
1019
|
+
while i < len(spec) and spec[i].isdigit():
|
|
1020
|
+
precision += spec[i]
|
|
1021
|
+
i += 1
|
|
1022
|
+
rest = spec[i:]
|
|
1023
|
+
ftype = rest
|
|
1024
|
+
if len(rest) > 1:
|
|
1025
|
+
self._error(v, f"unsupported f-string format spec {spec!r}")
|
|
1026
|
+
return ""
|
|
1027
|
+
if zero and not width:
|
|
1028
|
+
self._error(v, f"unsupported f-string format spec {spec!r}")
|
|
1029
|
+
return ""
|
|
1030
|
+
# The format buffer is allocated from the actual length returned by snprintf(NULL, 0, ...), with no fixed upper bound;
|
|
1031
|
+
# the constraint comes from C99 int: width/precision are parsed as int and overflow beyond INT_MAX,
|
|
1032
|
+
# and snprintf returns a negative value; the value is validated at compile time accordingly.
|
|
1033
|
+
if int(width or 0) > 2147483647 or int(precision or 0) > 2147483647:
|
|
1034
|
+
self._error(v, "f-string width and precision must fit in a C int")
|
|
1035
|
+
return ""
|
|
1036
|
+
if kind == "str":
|
|
1037
|
+
if ftype and ftype != "s":
|
|
1038
|
+
self._error(v, f"format spec {spec!r} is not valid for a Str field")
|
|
1039
|
+
return ""
|
|
1040
|
+
if zero:
|
|
1041
|
+
self._error(v, "zero-padded format spec is not valid for a Str field")
|
|
1042
|
+
return ""
|
|
1043
|
+
ftype = "s"
|
|
1044
|
+
elif kind == "f64":
|
|
1045
|
+
if not ftype:
|
|
1046
|
+
self._error(
|
|
1047
|
+
v,
|
|
1048
|
+
"float fields need an explicit format type (e.g. '.2f'); "
|
|
1049
|
+
"Python's float precision means significant digits, not decimals",
|
|
1050
|
+
)
|
|
1051
|
+
return ""
|
|
1052
|
+
if ftype not in ("f", "F", "e", "E", "g", "G"):
|
|
1053
|
+
self._error(v, f"format spec {spec!r} is not valid for a float field")
|
|
1054
|
+
return ""
|
|
1055
|
+
else: # i64 / u64 / bool
|
|
1056
|
+
if ftype and ftype not in ("d", "x", "X", "o"):
|
|
1057
|
+
self._error(v, f"format spec {spec!r} is not valid for an integer field")
|
|
1058
|
+
return ""
|
|
1059
|
+
if precision:
|
|
1060
|
+
self._error(v, "precision is not valid for an integer field")
|
|
1061
|
+
return ""
|
|
1062
|
+
if align:
|
|
1063
|
+
self._error(v, "alignment is not valid for an integer field")
|
|
1064
|
+
return ""
|
|
1065
|
+
ftype = ftype or "d"
|
|
1066
|
+
out = "%"
|
|
1067
|
+
if align == "<":
|
|
1068
|
+
out += "-"
|
|
1069
|
+
if zero:
|
|
1070
|
+
out += "0"
|
|
1071
|
+
out += width
|
|
1072
|
+
if precision:
|
|
1073
|
+
out += "." + precision
|
|
1074
|
+
out += ftype
|
|
1075
|
+
return out
|
|
1076
|
+
|
|
1077
|
+
def _check_strings_api_call(self, node: ast.Call, api: str) -> T.Type:
|
|
1078
|
+
"""Pass 2: validate strings.xxx arguments and attach annotations for code generation."""
|
|
1079
|
+
node._strings_api = api
|
|
1080
|
+
if node.keywords:
|
|
1081
|
+
self._error(node, f"strings.{api} does not support keyword arguments")
|
|
1082
|
+
args = node.args
|
|
1083
|
+
if api == "from_ptr":
|
|
1084
|
+
if len(args) != 2:
|
|
1085
|
+
self._error(
|
|
1086
|
+
node,
|
|
1087
|
+
"strings.from_ptr requires two arguments: strings.from_ptr(p, n)",
|
|
1088
|
+
)
|
|
1089
|
+
return T.STR
|
|
1090
|
+
pt = self._infer_expr(args[0])
|
|
1091
|
+
nt = self._infer_expr(args[1])
|
|
1092
|
+
if not T.is_ptr(pt):
|
|
1093
|
+
self._error(args[0], "strings.from_ptr first argument must be a pointer")
|
|
1094
|
+
if not (T.is_int(nt) or T.is_bool(nt)):
|
|
1095
|
+
self._error(args[1], "strings.from_ptr length must be an integer")
|
|
1096
|
+
node._etype = T.STR
|
|
1097
|
+
return T.STR
|
|
1098
|
+
if api == "data":
|
|
1099
|
+
if len(args) != 1:
|
|
1100
|
+
self._error(node, "strings.data requires one argument: strings.data(s)")
|
|
1101
|
+
return T.Ptr(T.CHAR)
|
|
1102
|
+
st = self._infer_expr(args[0])
|
|
1103
|
+
if not T.is_str(st):
|
|
1104
|
+
self._error(args[0], "strings.data argument must be a Str")
|
|
1105
|
+
node._etype = T.Ptr(T.CHAR)
|
|
1106
|
+
return T.Ptr(T.CHAR)
|
|
1107
|
+
# byte_len
|
|
1108
|
+
if len(args) != 1:
|
|
1109
|
+
self._error(node, "strings.byte_len requires one argument: strings.byte_len(s)")
|
|
1110
|
+
return T.I64
|
|
1111
|
+
st = self._infer_expr(args[0])
|
|
1112
|
+
if not T.is_str(st):
|
|
1113
|
+
self._error(args[0], "strings.byte_len argument must be a Str")
|
|
1114
|
+
node._etype = T.I64
|
|
1115
|
+
return T.I64
|
|
1116
|
+
|
|
1117
|
+
def _check_bytes_api_call(self, node: ast.Call, api: str) -> T.Type:
|
|
1118
|
+
"""Pass 2: validate bytes.xxx arguments and attach annotations for code generation."""
|
|
1119
|
+
node._bytes_api = api
|
|
1120
|
+
if node.keywords:
|
|
1121
|
+
self._error(node, f"bytes.{api} does not support keyword arguments")
|
|
1122
|
+
args = node.args
|
|
1123
|
+
if api == "from_ptr":
|
|
1124
|
+
if len(args) != 2:
|
|
1125
|
+
self._error(
|
|
1126
|
+
node,
|
|
1127
|
+
"bytes.from_ptr requires two arguments: bytes.from_ptr(p, n)",
|
|
1128
|
+
)
|
|
1129
|
+
return T.BYTES
|
|
1130
|
+
pt = self._infer_expr(args[0])
|
|
1131
|
+
nt = self._infer_expr(args[1])
|
|
1132
|
+
if not T.is_ptr(pt):
|
|
1133
|
+
self._error(args[0], "bytes.from_ptr first argument must be a pointer")
|
|
1134
|
+
if not (T.is_int(nt) or T.is_bool(nt)):
|
|
1135
|
+
self._error(args[1], "bytes.from_ptr length must be an integer")
|
|
1136
|
+
node._etype = T.BYTES
|
|
1137
|
+
return T.BYTES
|
|
1138
|
+
if api == "data":
|
|
1139
|
+
if len(args) != 1:
|
|
1140
|
+
self._error(node, "bytes.data requires one argument: bytes.data(b)")
|
|
1141
|
+
return T.Ptr(T.UCHAR)
|
|
1142
|
+
st = self._infer_expr(args[0])
|
|
1143
|
+
if not T.is_bytes(st):
|
|
1144
|
+
self._error(args[0], "bytes.data argument must be a Bytes")
|
|
1145
|
+
node._etype = T.Ptr(T.UCHAR)
|
|
1146
|
+
return T.Ptr(T.UCHAR)
|
|
1147
|
+
# byte_len
|
|
1148
|
+
if len(args) != 1:
|
|
1149
|
+
self._error(node, "bytes.byte_len requires one argument: bytes.byte_len(b)")
|
|
1150
|
+
return T.I64
|
|
1151
|
+
st = self._infer_expr(args[0])
|
|
1152
|
+
if not T.is_bytes(st):
|
|
1153
|
+
self._error(args[0], "bytes.byte_len argument must be a Bytes")
|
|
1154
|
+
node._etype = T.I64
|
|
1155
|
+
return T.I64
|
|
1156
|
+
|
|
1157
|
+
def _check_call(self, node: ast.Call) -> T.Type:
|
|
1158
|
+
f = node.func
|
|
1159
|
+
if isinstance(f, ast.Name):
|
|
1160
|
+
sym = self._lookup(f.id)
|
|
1161
|
+
if sym is None:
|
|
1162
|
+
if f.id == "make_array":
|
|
1163
|
+
self._error(
|
|
1164
|
+
f,
|
|
1165
|
+
"make_array must be imported: use 'from embeddedpy.arrays import make_array'",
|
|
1166
|
+
code="name",
|
|
1167
|
+
)
|
|
1168
|
+
self._error(f, undefined_name_message(f.id), code="name")
|
|
1169
|
+
assert sym is not None
|
|
1170
|
+
# Function pointer call: the variable (local/global/param) has type Ptr[Func[...]].
|
|
1171
|
+
# The external function pointer type ExternFuncPtr is carried as Ptr[ExternFuncPtr] and hits the same branch.
|
|
1172
|
+
if sym.kind in ("local", "global", "param"):
|
|
1173
|
+
st = T.resolve(sym.type)
|
|
1174
|
+
if isinstance(st, T.Ptr) and isinstance(T.resolve(st.target), T.Func):
|
|
1175
|
+
node.func._symbol = sym
|
|
1176
|
+
return self._check_funcptr_call(node, T.resolve(st.target))
|
|
1177
|
+
if sym.kind == "make_array_func":
|
|
1178
|
+
return self._check_make_array(node)
|
|
1179
|
+
if sym.kind == "auto_func":
|
|
1180
|
+
self._error(
|
|
1181
|
+
node,
|
|
1182
|
+
"auto() can only be used as an enum member value",
|
|
1183
|
+
code="unsupported",
|
|
1184
|
+
)
|
|
1185
|
+
if sym.kind == "type":
|
|
1186
|
+
if isinstance(T.resolve(sym.type), T.Struct):
|
|
1187
|
+
st = T.resolve(sym.type)
|
|
1188
|
+
self._check_struct_ctor(node, st)
|
|
1189
|
+
node._struct_ctor = st
|
|
1190
|
+
node._etype = st
|
|
1191
|
+
return st
|
|
1192
|
+
return self._check_cast(node, sym.type)
|
|
1193
|
+
if sym.kind == "ptr_func":
|
|
1194
|
+
return self._check_ptr_call(node)
|
|
1195
|
+
if sym.kind == "builtin":
|
|
1196
|
+
return self._check_builtin_call(node, f.id)
|
|
1197
|
+
if sym.kind == "sizeof_func":
|
|
1198
|
+
return self._check_sizeof(node)
|
|
1199
|
+
if sym.kind == "copy_aggregate_func":
|
|
1200
|
+
return self._check_copy_aggregate(node)
|
|
1201
|
+
if sym.kind == "func":
|
|
1202
|
+
return self._check_func_call(node)
|
|
1203
|
+
self._error(f, f"{f.id} is not callable", code="name")
|
|
1204
|
+
if isinstance(f, ast.Attribute):
|
|
1205
|
+
api = self._ptr_api_name(f)
|
|
1206
|
+
if api is not None:
|
|
1207
|
+
return self._check_ptr_api_call(node, api)
|
|
1208
|
+
mem_api = self._mem_api_name(f)
|
|
1209
|
+
if mem_api is not None:
|
|
1210
|
+
return self._check_mem_api_call(node, mem_api)
|
|
1211
|
+
io_api = self._io_api_name(f)
|
|
1212
|
+
if io_api is not None:
|
|
1213
|
+
return self._check_io_api_call(node, io_api)
|
|
1214
|
+
strings_api = self._strings_api_name(f)
|
|
1215
|
+
if strings_api is not None:
|
|
1216
|
+
return self._check_strings_api_call(node, strings_api)
|
|
1217
|
+
bytes_api = self._bytes_api_name(f)
|
|
1218
|
+
if bytes_api is not None:
|
|
1219
|
+
return self._check_bytes_api_call(node, bytes_api)
|
|
1220
|
+
c_api = self._c_expr_api_name(f)
|
|
1221
|
+
if c_api is not None:
|
|
1222
|
+
return self._check_c_expr_api_call(node, c_api)
|
|
1223
|
+
self._require_attr_base(f)
|
|
1224
|
+
target = self._member_type(f)
|
|
1225
|
+
if target is not None:
|
|
1226
|
+
return self._check_cast(node, target)
|
|
1227
|
+
# A function pointer stored in a struct field: c.cb(5) (pass 1 already computed the field type)
|
|
1228
|
+
ft = self._field_funcptr_type(f)
|
|
1229
|
+
if ft is not None:
|
|
1230
|
+
return self._check_funcptr_call(node, ft)
|
|
1231
|
+
path = self._member_path(f)
|
|
1232
|
+
if path is not None and path.startswith("embeddedpy"):
|
|
1233
|
+
self._error(node, f"wrapper {path} is not supported", code="import")
|
|
1234
|
+
self._error(f, "unsupported attribute call")
|
|
1235
|
+
self._error(f, "only calls to function names are supported")
|
|
1236
|
+
|
|
1237
|
+
def _check_funcptr_call(self, node: ast.Call, ft: T.Func) -> T.Type:
|
|
1238
|
+
"""Pass 2: validate calls made through a function pointer (argument types/count, return type)."""
|
|
1239
|
+
if len(node.args) != len(ft.args):
|
|
1240
|
+
self._error(
|
|
1241
|
+
node,
|
|
1242
|
+
f"function pointer expects {len(ft.args)} arguments, got {len(node.args)}",
|
|
1243
|
+
)
|
|
1244
|
+
for arg, expected in zip(node.args, ft.args):
|
|
1245
|
+
at = self._infer_expr(arg)
|
|
1246
|
+
if not self._assign_compatible(expected, at):
|
|
1247
|
+
self._error(
|
|
1248
|
+
arg,
|
|
1249
|
+
f"argument type mismatch: expected "
|
|
1250
|
+
f"{T.describe(T.resolve(expected))}, got {T.describe(T.resolve(at))}",
|
|
1251
|
+
)
|
|
1252
|
+
node._funcptr_call = True
|
|
1253
|
+
node._funcptr_type = ft
|
|
1254
|
+
node._etype = ft.ret
|
|
1255
|
+
return ft.ret
|
|
1256
|
+
|
|
1257
|
+
def _check_cast(self, node: ast.Call, target: T.Type) -> T.Type:
|
|
1258
|
+
if node.keywords:
|
|
1259
|
+
self._error(node, "type cast does not support keyword arguments")
|
|
1260
|
+
if len(node.args) != 1:
|
|
1261
|
+
self._error(node, "type cast requires exactly one argument")
|
|
1262
|
+
arg = node.args[0]
|
|
1263
|
+
at = self._infer_expr(arg)
|
|
1264
|
+
tr = T.resolve(target)
|
|
1265
|
+
if T.is_str(tr):
|
|
1266
|
+
# str(x): cannot be a C cast (py_str is a struct), so use a py_str_from_* runtime function.
|
|
1267
|
+
# The source type decides which py_str_from_* to use.
|
|
1268
|
+
if not (T.is_numeric(at) or T.is_str(at) or T.is_byte_char(at)):
|
|
1269
|
+
self._error(arg, "str() conversion only supports numeric, string, or character arguments")
|
|
1270
|
+
node._cast_type = target
|
|
1271
|
+
node._arg_type = at
|
|
1272
|
+
node._etype = target
|
|
1273
|
+
return target
|
|
1274
|
+
if T.is_bytes(tr):
|
|
1275
|
+
# Bytes(x): a byte string is a value with a length; accepts only "already a byte string" or "one byte".
|
|
1276
|
+
if T.is_bytes(at):
|
|
1277
|
+
pass # copy through unchanged
|
|
1278
|
+
elif T.is_byte_char(at):
|
|
1279
|
+
pass # one byte -> a one-byte byte string
|
|
1280
|
+
else:
|
|
1281
|
+
self._error(
|
|
1282
|
+
arg,
|
|
1283
|
+
"Bytes() conversion only supports bytes or character arguments; "
|
|
1284
|
+
"use a bytes literal for a byte sequence",
|
|
1285
|
+
)
|
|
1286
|
+
node._cast_type = target
|
|
1287
|
+
node._arg_type = at
|
|
1288
|
+
node._etype = target
|
|
1289
|
+
return target
|
|
1290
|
+
if not T.is_numeric(at):
|
|
1291
|
+
# Single-byte character types can be constructed from string/bytes literals: take the first byte.
|
|
1292
|
+
# This is an explicit conversion and is not subject to the "literal form" constraint.
|
|
1293
|
+
if T.is_byte_char(target) and isinstance(arg, ast.Constant) and (
|
|
1294
|
+
isinstance(arg.value, str) or isinstance(arg.value, bytes)
|
|
1295
|
+
):
|
|
1296
|
+
ch = self._char_from_str(target, arg, explicit=True)
|
|
1297
|
+
if ch is not None:
|
|
1298
|
+
node._cast_type = target
|
|
1299
|
+
node._arg_type = at
|
|
1300
|
+
node._etype = target
|
|
1301
|
+
return target
|
|
1302
|
+
# Converting a character type to an integer is an allowed explicit conversion (take that byte numeric value).
|
|
1303
|
+
if T.is_byte_char(at) and T.is_numeric(target):
|
|
1304
|
+
node._cast_type = target
|
|
1305
|
+
node._arg_type = at
|
|
1306
|
+
node._etype = target
|
|
1307
|
+
return target
|
|
1308
|
+
# Integer constructors accept a string literal, parse it as a decimal integer literal, and fold it into a constant at compile time; a runtime string value is not accepted.
|
|
1309
|
+
if T.is_int(target) and T.is_str(at):
|
|
1310
|
+
if not isinstance(arg, ast.Constant) or not isinstance(arg.value, str):
|
|
1311
|
+
self._error(arg, "integer literal conversion only accepts a string literal")
|
|
1312
|
+
return target
|
|
1313
|
+
text = arg.value.strip()
|
|
1314
|
+
if not text:
|
|
1315
|
+
self._error(arg, "integer literal conversion requires a decimal integer literal")
|
|
1316
|
+
return target
|
|
1317
|
+
s = 1 if text[0] in "+-" else 0
|
|
1318
|
+
digits = text[s:]
|
|
1319
|
+
if not digits or any(c not in "0123456789" for c in digits):
|
|
1320
|
+
self._error(arg, "integer literal conversion requires a decimal integer literal")
|
|
1321
|
+
return target
|
|
1322
|
+
magnitude = int(digits)
|
|
1323
|
+
parsed = -magnitude if (s == 1 and text[0] == "-") else magnitude
|
|
1324
|
+
if not -(1 << 63) <= parsed <= (1 << 63) - 1:
|
|
1325
|
+
self._error(arg, "integer literal out of range")
|
|
1326
|
+
return target
|
|
1327
|
+
node._cast_const = parsed
|
|
1328
|
+
node._cast_type = target
|
|
1329
|
+
node._arg_type = at
|
|
1330
|
+
node._etype = target
|
|
1331
|
+
return target
|
|
1332
|
+
self._error(arg, "type cast only supports numeric arguments")
|
|
1333
|
+
node._cast_type = target
|
|
1334
|
+
node._arg_type = at
|
|
1335
|
+
node._etype = target
|
|
1336
|
+
return target
|
|
1337
|
+
|
|
1338
|
+
def _check_ptr_call(self, node: ast.Call) -> T.Type:
|
|
1339
|
+
if node.keywords:
|
|
1340
|
+
self._error(node, "ptr does not support keyword arguments")
|
|
1341
|
+
if len(node.args) != 1:
|
|
1342
|
+
self._error(node, "ptr requires one argument")
|
|
1343
|
+
arg = node.args[0]
|
|
1344
|
+
at = self._infer_expr(arg)
|
|
1345
|
+
# Only lvalues (variables, fields, pointer dereferences) can have their address taken
|
|
1346
|
+
if not isinstance(arg, (ast.Name, ast.Attribute, ast.Subscript)):
|
|
1347
|
+
self._error(arg, "ptr can only take the address of a variable, struct field, or pointer subscript")
|
|
1348
|
+
node._ptr_arg = arg
|
|
1349
|
+
node._etype = T.Ptr(at)
|
|
1350
|
+
return node._etype
|
|
1351
|
+
|
|
1352
|
+
def _check_ptr_api_call(self, node: ast.Call, api: str) -> T.Type:
|
|
1353
|
+
"""Pass 2: validate ptr.xxx arguments and attach annotations for code generation."""
|
|
1354
|
+
node._ptr_api = api
|
|
1355
|
+
if node.keywords:
|
|
1356
|
+
self._error(node, f"ptr.{api} does not support keyword arguments")
|
|
1357
|
+
args = node.args
|
|
1358
|
+
if api == "null":
|
|
1359
|
+
# ptr.null(): a null pointer (NULL). The element type is determined by context
|
|
1360
|
+
if len(args) != 0:
|
|
1361
|
+
self._error(node, "ptr.null takes no arguments")
|
|
1362
|
+
node._etype = T.Ptr(T.TVar())
|
|
1363
|
+
return node._etype
|
|
1364
|
+
if api == "ref":
|
|
1365
|
+
if len(args) != 1:
|
|
1366
|
+
self._error(node, "ptr.ref requires one argument")
|
|
1367
|
+
return T.Ptr(T.TVar())
|
|
1368
|
+
arg = args[0]
|
|
1369
|
+
at = self._infer_expr(arg)
|
|
1370
|
+
if not isinstance(arg, (ast.Name, ast.Attribute, ast.Subscript)):
|
|
1371
|
+
self._error(arg, "ptr.ref can only take the address of a variable, struct field, or pointer dereference")
|
|
1372
|
+
r = T.resolve(at)
|
|
1373
|
+
if isinstance(r, T.Array):
|
|
1374
|
+
# Array decay: &arr[0][0], the address of the first element (innermost scalar for multiple dimensions)
|
|
1375
|
+
at = self._array_scalar_elem(at)
|
|
1376
|
+
node._ptrapi_arg = arg
|
|
1377
|
+
node._ptrapi_elem = at
|
|
1378
|
+
node._etype = T.Ptr(at)
|
|
1379
|
+
return node._etype
|
|
1380
|
+
if api == "peek":
|
|
1381
|
+
if len(args) != 1:
|
|
1382
|
+
self._error(node, "ptr.peek requires one argument")
|
|
1383
|
+
return T.TVar()
|
|
1384
|
+
target = self._ptr_target(self._infer_expr(args[0]))
|
|
1385
|
+
if target is None:
|
|
1386
|
+
self._error(args[0], "ptr.peek argument must be a pointer")
|
|
1387
|
+
target = T.TVar()
|
|
1388
|
+
node._etype = target
|
|
1389
|
+
return target
|
|
1390
|
+
if api == "poke":
|
|
1391
|
+
if len(args) != 2:
|
|
1392
|
+
self._error(node, "ptr.poke requires two arguments: ptr.poke(p, v)")
|
|
1393
|
+
return T.VOID
|
|
1394
|
+
target = self._ptr_target(self._infer_expr(args[0]))
|
|
1395
|
+
if target is None:
|
|
1396
|
+
self._error(args[0], "ptr.poke first argument must be a pointer")
|
|
1397
|
+
target = T.TVar()
|
|
1398
|
+
vt = self._infer_expr(args[1])
|
|
1399
|
+
try:
|
|
1400
|
+
T.unify(target, vt)
|
|
1401
|
+
except T.TypesMismatch as exc:
|
|
1402
|
+
self._error(args[1], f"ptr.poke value type mismatch: {exc}")
|
|
1403
|
+
node._ptrapi_arg = args[0]
|
|
1404
|
+
node._ptrapi_value = args[1]
|
|
1405
|
+
node._ptrapi_elem = target
|
|
1406
|
+
node._etype = T.VOID
|
|
1407
|
+
return T.VOID
|
|
1408
|
+
if api == "skip":
|
|
1409
|
+
if len(args) != 2:
|
|
1410
|
+
self._error(node, "ptr.skip requires two arguments: ptr.skip(p, n)")
|
|
1411
|
+
return T.Ptr(T.TVar())
|
|
1412
|
+
target = self._ptr_target(self._infer_expr(args[0]))
|
|
1413
|
+
if target is None:
|
|
1414
|
+
self._error(args[0], "ptr.skip argument must be a pointer")
|
|
1415
|
+
target = T.TVar()
|
|
1416
|
+
nt = self._infer_expr(args[1])
|
|
1417
|
+
if not (T.is_int(nt) or T.is_bool(nt)):
|
|
1418
|
+
self._error(args[1], "ptr.skip offset must be an integer")
|
|
1419
|
+
node._ptrapi_arg = args[0]
|
|
1420
|
+
node._ptrapi_offset = args[1]
|
|
1421
|
+
node._ptrapi_elem = target
|
|
1422
|
+
node._etype = T.Ptr(target)
|
|
1423
|
+
return node._etype
|
|
1424
|
+
if api == "field":
|
|
1425
|
+
if len(args) != 2:
|
|
1426
|
+
self._error(node, 'ptr.field requires two arguments: ptr.field(s, "field_name")')
|
|
1427
|
+
return T.Ptr(T.TVar())
|
|
1428
|
+
st = T.resolve(self._infer_expr(args[0]))
|
|
1429
|
+
name_arg = args[1]
|
|
1430
|
+
if not (
|
|
1431
|
+
isinstance(name_arg, ast.Constant)
|
|
1432
|
+
and isinstance(name_arg.value, str)
|
|
1433
|
+
):
|
|
1434
|
+
self._error(name_arg, "ptr.field field name must be a string literal")
|
|
1435
|
+
return T.Ptr(T.TVar())
|
|
1436
|
+
fname = name_arg.value
|
|
1437
|
+
# The first argument can be a struct value or a pointer to a struct
|
|
1438
|
+
acc = T.struct_field_access(st)
|
|
1439
|
+
if acc is None:
|
|
1440
|
+
self._error(
|
|
1441
|
+
args[0],
|
|
1442
|
+
"ptr.field first argument must be a struct or a pointer to a struct",
|
|
1443
|
+
)
|
|
1444
|
+
return T.Ptr(T.TVar())
|
|
1445
|
+
stc, levels = acc
|
|
1446
|
+
self._reject_extern_type_field(name_arg, stc, fname)
|
|
1447
|
+
if fname not in stc.fields:
|
|
1448
|
+
self._error(name_arg, f"struct {stc.name} has no field {fname}")
|
|
1449
|
+
return T.Ptr(T.TVar())
|
|
1450
|
+
ftype = stc.fields[fname]
|
|
1451
|
+
node._ptrapi_obj = args[0]
|
|
1452
|
+
node._ptrapi_field = fname
|
|
1453
|
+
node._ptrapi_elem = ftype
|
|
1454
|
+
node._ptrapi_ptr_levels = levels
|
|
1455
|
+
node._etype = T.Ptr(ftype)
|
|
1456
|
+
return node._etype
|
|
1457
|
+
# from_int / cast
|
|
1458
|
+
if len(args) != 2:
|
|
1459
|
+
self._error(node, f"ptr.{api} requires two arguments")
|
|
1460
|
+
return T.Ptr(T.TVar())
|
|
1461
|
+
val_t = self._infer_expr(args[0])
|
|
1462
|
+
if api == "from_int":
|
|
1463
|
+
if not (T.is_int(val_t) or T.is_bool(val_t)):
|
|
1464
|
+
self._error(args[0], "ptr.from_int address must be an integer")
|
|
1465
|
+
elif self._ptr_target(val_t) is None:
|
|
1466
|
+
self._error(args[0], "ptr.cast argument must be a pointer")
|
|
1467
|
+
elem = self._resolve_type_arg(args[1])
|
|
1468
|
+
if elem is None:
|
|
1469
|
+
self._error(
|
|
1470
|
+
args[1],
|
|
1471
|
+
f"ptr.{api} second argument must be a type name (e.g. int32)",
|
|
1472
|
+
)
|
|
1473
|
+
elem = T.TVar()
|
|
1474
|
+
node._ptrapi_arg = args[0]
|
|
1475
|
+
node._ptrapi_elem = elem
|
|
1476
|
+
node._etype = T.Ptr(elem)
|
|
1477
|
+
return node._etype
|
|
1478
|
+
|
|
1479
|
+
|
|
1480
|
+
def _check_struct_ctor(self, node: ast.Call, st: T.Struct) -> None:
|
|
1481
|
+
"""Pass 2: validate that constructor arguments match the field types."""
|
|
1482
|
+
if node.args and node.keywords:
|
|
1483
|
+
return # pass 1 already reported an error
|
|
1484
|
+
fields = list(st.fields.items())
|
|
1485
|
+
if node.args:
|
|
1486
|
+
for i, arg in enumerate(node.args):
|
|
1487
|
+
fname, ftype = fields[i]
|
|
1488
|
+
self._check_struct_field(node, st, fname, ftype, arg)
|
|
1489
|
+
else:
|
|
1490
|
+
for kw in node.keywords:
|
|
1491
|
+
fname = kw.arg
|
|
1492
|
+
ftype = st.fields[fname]
|
|
1493
|
+
self._check_struct_field(node, st, fname, ftype, kw.value)
|
|
1494
|
+
|
|
1495
|
+
def _check_struct_field(self, node, st, fname, ftype, value_node) -> None:
|
|
1496
|
+
vt = self._infer_expr(value_node)
|
|
1497
|
+
if not self._assign_compatible(ftype, vt):
|
|
1498
|
+
self._error(
|
|
1499
|
+
value_node,
|
|
1500
|
+
f"field {fname} of struct {st.name} expects "
|
|
1501
|
+
f"{T.describe(T.resolve(ftype))}, got {T.describe(T.resolve(vt))}",
|
|
1502
|
+
)
|
|
1503
|
+
|
|
1504
|
+
def _func_type_of(self, fi) -> T.Func:
|
|
1505
|
+
"""Build the Func part of the function pointer type Ptr[Func[[params...], return]] from a FuncInfo."""
|
|
1506
|
+
param_types = [fi.locals[p].type for p in fi.params]
|
|
1507
|
+
return T.Func(tuple(param_types), fi.ret)
|
|
1508
|
+
|
|
1509
|
+
def _func_sig_match(self, fa: T.Func, fb: T.Func) -> bool:
|
|
1510
|
+
"""Whether two function signatures match (parameter count, each parameter type, return type)."""
|
|
1511
|
+
fa = T.resolve(fa)
|
|
1512
|
+
fb = T.resolve(fb)
|
|
1513
|
+
if len(fa.args) != len(fb.args):
|
|
1514
|
+
return False
|
|
1515
|
+
if not T.same(fa.ret, fb.ret):
|
|
1516
|
+
return False
|
|
1517
|
+
return all(T.same(x, y) for x, y in zip(fa.args, fb.args))
|
|
1518
|
+
|
|
1519
|
+
def _assign_compatible(self, expected, actual) -> bool:
|
|
1520
|
+
e = T.resolve(expected)
|
|
1521
|
+
a = T.resolve(actual)
|
|
1522
|
+
if T.same(e, a):
|
|
1523
|
+
return True
|
|
1524
|
+
# Assignment/passing between function pointers: compare whether signatures match
|
|
1525
|
+
if isinstance(e, T.Ptr) and isinstance(a, T.Ptr):
|
|
1526
|
+
et = T.resolve(e.target)
|
|
1527
|
+
at = T.resolve(a.target)
|
|
1528
|
+
if isinstance(et, T.Func) and isinstance(at, T.Func):
|
|
1529
|
+
return self._func_sig_match(et, at)
|
|
1530
|
+
if isinstance(e, T.Scalar) and e.category == "int" and isinstance(a, T.ConstInt):
|
|
1531
|
+
return True
|
|
1532
|
+
if isinstance(e, T.Scalar) and e.category == "float" and isinstance(a, T.ConstFloat):
|
|
1533
|
+
return True
|
|
1534
|
+
if e is T.BOOL and isinstance(a, T.ConstInt):
|
|
1535
|
+
return True
|
|
1536
|
+
return False
|
|
1537
|
+
|
|
1538
|
+
def _check_copy_aggregate(self, node: ast.Call) -> T.Type:
|
|
1539
|
+
"""Pass 2: validate copy_aggregate arguments and attach annotations for code generation."""
|
|
1540
|
+
if node.keywords:
|
|
1541
|
+
self._error(node, "copy_aggregate does not support keyword arguments")
|
|
1542
|
+
if len(node.args) != 1:
|
|
1543
|
+
self._error(node, "copy_aggregate takes one argument: copy_aggregate(value)")
|
|
1544
|
+
return T.TVar()
|
|
1545
|
+
at = self._infer_expr(node.args[0])
|
|
1546
|
+
r = T.resolve(at)
|
|
1547
|
+
if not isinstance(r, (T.Struct, T.Array)):
|
|
1548
|
+
self._error(node.args[0], "copy_aggregate argument must be an aggregate")
|
|
1549
|
+
node._is_copy_aggregate = True
|
|
1550
|
+
node._etype = r
|
|
1551
|
+
return node._etype
|
|
1552
|
+
|
|
1553
|
+
def _check_mem_api_call(self, node: ast.Call, api: str) -> T.Type:
|
|
1554
|
+
"""Pass 2: validate mem.xxx arguments and attach annotations for code generation."""
|
|
1555
|
+
node._mem_api = api
|
|
1556
|
+
if node.keywords:
|
|
1557
|
+
self._error(node, f"mem.{api} does not support keyword arguments")
|
|
1558
|
+
args = node.args
|
|
1559
|
+
if api == "arena_reset":
|
|
1560
|
+
if args:
|
|
1561
|
+
self._error(node, "mem.arena_reset takes no arguments")
|
|
1562
|
+
node._etype = T.VOID
|
|
1563
|
+
return T.VOID
|
|
1564
|
+
if api == "alloc":
|
|
1565
|
+
if len(args) != 2:
|
|
1566
|
+
self._error(node, "mem.alloc requires two arguments: mem.alloc(element_type, count)")
|
|
1567
|
+
return T.Ptr(T.TVar())
|
|
1568
|
+
elem = self._resolve_type_arg(args[0])
|
|
1569
|
+
if elem is None:
|
|
1570
|
+
self._error(args[0], "mem.alloc first argument must be a type name (e.g. int32)")
|
|
1571
|
+
elem = T.TVar()
|
|
1572
|
+
r = T.resolve(elem)
|
|
1573
|
+
if isinstance(r, (T.Struct, T.Array, T.Enum)) or r is T.STR or r is T.BYTES or r is T.VOID:
|
|
1574
|
+
self._error(
|
|
1575
|
+
args[0],
|
|
1576
|
+
"mem.alloc only supports fixed-width numeric types "
|
|
1577
|
+
"(use an array of structs on the stack instead)",
|
|
1578
|
+
)
|
|
1579
|
+
cnt = self._infer_expr(args[1])
|
|
1580
|
+
if not (T.is_int(cnt) or T.is_bool(cnt)):
|
|
1581
|
+
self._error(args[1], "mem.alloc count must be an integer")
|
|
1582
|
+
node._memapi_elem = elem
|
|
1583
|
+
node._memapi_count = args[1]
|
|
1584
|
+
node._etype = T.Ptr(elem)
|
|
1585
|
+
return node._etype
|
|
1586
|
+
if api == "free":
|
|
1587
|
+
if len(args) != 1:
|
|
1588
|
+
self._error(node, "mem.free requires one argument: mem.free(pointer)")
|
|
1589
|
+
return T.VOID
|
|
1590
|
+
pt = self._infer_expr(args[0])
|
|
1591
|
+
if self._ptr_target(pt) is None:
|
|
1592
|
+
self._error(args[0], "mem.free argument must be a pointer")
|
|
1593
|
+
node._memapi_arg = args[0]
|
|
1594
|
+
node._etype = T.VOID
|
|
1595
|
+
return T.VOID
|
|
1596
|
+
# realloc
|
|
1597
|
+
if len(args) != 2:
|
|
1598
|
+
self._error(node, "mem.realloc requires two arguments: mem.realloc(pointer, count)")
|
|
1599
|
+
return T.Ptr(T.TVar())
|
|
1600
|
+
pt = self._infer_expr(args[0])
|
|
1601
|
+
target = self._ptr_target(pt)
|
|
1602
|
+
if target is None:
|
|
1603
|
+
self._error(args[0], "mem.realloc first argument must be a pointer")
|
|
1604
|
+
target = T.TVar()
|
|
1605
|
+
cnt = self._infer_expr(args[1])
|
|
1606
|
+
if not (T.is_int(cnt) or T.is_bool(cnt)):
|
|
1607
|
+
self._error(args[1], "mem.realloc count must be an integer")
|
|
1608
|
+
node._memapi_arg = args[0]
|
|
1609
|
+
node._memapi_count = args[1]
|
|
1610
|
+
node._memapi_elem = target
|
|
1611
|
+
node._etype = T.Ptr(target)
|
|
1612
|
+
return node._etype
|
|
1613
|
+
|
|
1614
|
+
def _check_c_expr_api_call(self, node: ast.Call, api: str) -> T.Type:
|
|
1615
|
+
"""Pass 2: validate c.clz/ctz/popcount arguments and attach annotations for code generation."""
|
|
1616
|
+
node._c_expr_api = api
|
|
1617
|
+
if node.keywords:
|
|
1618
|
+
self._error(node, f"c.{api} does not support keyword arguments")
|
|
1619
|
+
args = node.args
|
|
1620
|
+
if len(args) != 1:
|
|
1621
|
+
self._error(node, f"c.{api} requires one integer argument: c.{api}(x)")
|
|
1622
|
+
node._etype = T.I32
|
|
1623
|
+
return T.I32
|
|
1624
|
+
at = self._infer_expr(args[0])
|
|
1625
|
+
if not (T.is_int(at) or T.is_bool(at)):
|
|
1626
|
+
self._error(args[0], f"c.{api} argument must be an integer")
|
|
1627
|
+
r = T.resolve(at)
|
|
1628
|
+
node._c_expr_ll = r in (T.I64, T.U64)
|
|
1629
|
+
node._etype = T.I32
|
|
1630
|
+
return T.I32
|
|
1631
|
+
|
|
1632
|
+
def _check_io_api_call(self, node: ast.Call, api: str) -> T.Type:
|
|
1633
|
+
"""Pass 2: validate io.xxx arguments and attach annotations for code generation."""
|
|
1634
|
+
node._io_api = api
|
|
1635
|
+
if node.keywords:
|
|
1636
|
+
self._error(node, f"io.{api} does not support keyword arguments")
|
|
1637
|
+
args = node.args
|
|
1638
|
+
if api == "open":
|
|
1639
|
+
if len(args) != 2:
|
|
1640
|
+
self._error(node, "io.open requires two arguments: io.open(path, mode)")
|
|
1641
|
+
return T.FILE
|
|
1642
|
+
path_t = self._infer_expr(args[0])
|
|
1643
|
+
if not T.is_str(path_t):
|
|
1644
|
+
self._error(args[0], "io.open path must be a string")
|
|
1645
|
+
mode_t = self._infer_expr(args[1])
|
|
1646
|
+
if not T.is_str(mode_t):
|
|
1647
|
+
self._error(args[1], "io.open mode must be a string")
|
|
1648
|
+
node._etype = T.FILE
|
|
1649
|
+
return T.FILE
|
|
1650
|
+
if api == "read":
|
|
1651
|
+
if len(args) != 2:
|
|
1652
|
+
self._error(node, "io.read requires two arguments: io.read(file, capacity)")
|
|
1653
|
+
return T.BYTES
|
|
1654
|
+
ft = self._infer_expr(args[0])
|
|
1655
|
+
if not T.is_file(ft):
|
|
1656
|
+
self._error(args[0], "io.read first argument must be a File")
|
|
1657
|
+
cap_t = self._infer_expr(args[1])
|
|
1658
|
+
if not (T.is_int(cap_t) or T.is_bool(cap_t)):
|
|
1659
|
+
self._error(args[1], "io.read capacity must be an integer")
|
|
1660
|
+
node._etype = T.BYTES
|
|
1661
|
+
return T.BYTES
|
|
1662
|
+
if api == "write":
|
|
1663
|
+
if len(args) != 2:
|
|
1664
|
+
self._error(node, "io.write requires two arguments: io.write(file, data)")
|
|
1665
|
+
return T.I64
|
|
1666
|
+
ft = self._infer_expr(args[0])
|
|
1667
|
+
if not T.is_file(ft):
|
|
1668
|
+
self._error(args[0], "io.write first argument must be a File")
|
|
1669
|
+
dt = self._infer_expr(args[1])
|
|
1670
|
+
if not T.is_bytes(dt):
|
|
1671
|
+
self._error(args[1], "io.write second argument must be a bytes value")
|
|
1672
|
+
node._etype = T.I64
|
|
1673
|
+
return T.I64
|
|
1674
|
+
# close
|
|
1675
|
+
if len(args) != 1:
|
|
1676
|
+
self._error(node, "io.close requires one argument: io.close(file)")
|
|
1677
|
+
return T.VOID
|
|
1678
|
+
ft = self._infer_expr(args[0])
|
|
1679
|
+
if not T.is_file(ft):
|
|
1680
|
+
self._error(args[0], "io.close argument must be a File")
|
|
1681
|
+
node._etype = T.VOID
|
|
1682
|
+
return T.VOID
|
|
1683
|
+
|
|
1684
|
+
def _check_sizeof(self, node: ast.Call) -> T.Type:
|
|
1685
|
+
"""sizeof(T): the number of bytes occupied by a type.
|
|
1686
|
+
|
|
1687
|
+
The C side emits a real sizeof keyword and lets the target platform compiler compute it;
|
|
1688
|
+
the CPython side computes it by the same rules (pointer size depends on the platform).
|
|
1689
|
+
"""
|
|
1690
|
+
if node.keywords:
|
|
1691
|
+
self._error(node, "sizeof does not support keyword arguments")
|
|
1692
|
+
if len(node.args) != 1:
|
|
1693
|
+
self._error(node, "sizeof requires a type argument")
|
|
1694
|
+
arg = node.args[0]
|
|
1695
|
+
t: Optional[T.Type] = None
|
|
1696
|
+
if isinstance(arg, ast.Name):
|
|
1697
|
+
sym = self.scope.get(arg.id)
|
|
1698
|
+
if sym is None:
|
|
1699
|
+
self._error(arg, f"sizeof argument must be a type name; {arg.id} is undefined")
|
|
1700
|
+
assert sym is not None
|
|
1701
|
+
if sym.kind == "type":
|
|
1702
|
+
t = sym.type
|
|
1703
|
+
elif sym.kind == "ptr_alias" and sym.type is not None:
|
|
1704
|
+
# int32_ptr = Ptr[int32] -> sizeof(int32_ptr) is the pointer size
|
|
1705
|
+
t = T.Ptr(T.resolve(sym.type).target)
|
|
1706
|
+
if t is None:
|
|
1707
|
+
self._error(arg, f"sizeof argument must be a type name; {arg.id} is not a type")
|
|
1708
|
+
elif isinstance(arg, ast.Subscript):
|
|
1709
|
+
# sizeof(array[int32]): take the size of the element type
|
|
1710
|
+
t = self._resolve_annotation(arg)
|
|
1711
|
+
else:
|
|
1712
|
+
self._error(arg, "sizeof argument must be a type name (e.g. sizeof(int32))")
|
|
1713
|
+
r = T.resolve(t)
|
|
1714
|
+
if isinstance(r, T.Struct):
|
|
1715
|
+
self._error(arg, "sizeof does not support structs (size depends on alignment)")
|
|
1716
|
+
if isinstance(r, T.Enum):
|
|
1717
|
+
self._error(arg, "sizeof does not support enums (size is compiler-defined)")
|
|
1718
|
+
if r is T.STR or r is T.BYTES:
|
|
1719
|
+
self._error(arg, "sizeof does not support string types (size depends on alignment)")
|
|
1720
|
+
node._sizeof_c = _ctype_of(r)
|
|
1721
|
+
node._builtin = "sizeof"
|
|
1722
|
+
node._arg_types = []
|
|
1723
|
+
node._etype = T.ConstInt(_sizeof_size(r))
|
|
1724
|
+
return node._etype
|
|
1725
|
+
|
|
1726
|
+
def _check_builtin_call(self, node: ast.Call, name: str) -> T.Type:
|
|
1727
|
+
if name == "range":
|
|
1728
|
+
self._error(node, "range can only be used in for loops")
|
|
1729
|
+
if name == "print":
|
|
1730
|
+
return self._check_print(node)
|
|
1731
|
+
if name == "sizeof":
|
|
1732
|
+
return self._check_sizeof(node)
|
|
1733
|
+
if node.keywords:
|
|
1734
|
+
self._error(node, f"{name} does not support keyword arguments")
|
|
1735
|
+
if name == "input":
|
|
1736
|
+
return self._check_input(node)
|
|
1737
|
+
if name in ("min", "max"):
|
|
1738
|
+
if len(node.args) != 2:
|
|
1739
|
+
self._error(node, f"{name} requires two arguments")
|
|
1740
|
+
a = self._infer_expr(node.args[0])
|
|
1741
|
+
b = self._infer_expr(node.args[1])
|
|
1742
|
+
try:
|
|
1743
|
+
unified = T.unify(a, b)
|
|
1744
|
+
except T.TypesMismatch as exc:
|
|
1745
|
+
self._error(node, str(exc))
|
|
1746
|
+
node._etype = unified
|
|
1747
|
+
node._arg_types = [a, b]
|
|
1748
|
+
node._builtin = name
|
|
1749
|
+
return unified
|
|
1750
|
+
if len(node.args) != 1:
|
|
1751
|
+
self._error(node, f"{name} requires one argument")
|
|
1752
|
+
at = self._infer_expr(node.args[0])
|
|
1753
|
+
node._builtin = name
|
|
1754
|
+
node._arg_types = [at]
|
|
1755
|
+
if name == "len":
|
|
1756
|
+
if T.is_str(at):
|
|
1757
|
+
node._etype = T.I64
|
|
1758
|
+
return T.I64
|
|
1759
|
+
if T.is_bytes(at):
|
|
1760
|
+
node._etype = T.I64
|
|
1761
|
+
return T.I64
|
|
1762
|
+
r = T.resolve(at)
|
|
1763
|
+
if isinstance(r, T.Array):
|
|
1764
|
+
if r.length < 0 and not self._is_len_param(node.args[0]):
|
|
1765
|
+
self._error(node, "len does not support arrays of unknown length")
|
|
1766
|
+
if r.length >= 0:
|
|
1767
|
+
# The length of a fixed-length array is a compile-time constant, represented in the type as a constant integer,
|
|
1768
|
+
# so len(a) can be assigned directly to an integer variable of any width.
|
|
1769
|
+
node._etype = T.ConstInt(r.length)
|
|
1770
|
+
node._len_const = r.length
|
|
1771
|
+
return node._etype
|
|
1772
|
+
node._etype = T.I64
|
|
1773
|
+
return T.I64
|
|
1774
|
+
self._error(node, "len only supports strings or fixed-length arrays")
|
|
1775
|
+
if name == "abs":
|
|
1776
|
+
if not T.is_numeric(at):
|
|
1777
|
+
self._error(node, "abs requires a numeric argument")
|
|
1778
|
+
node._etype = T.I32 if T.is_bool(at) else T.base(at)
|
|
1779
|
+
return node._etype
|
|
1780
|
+
if name == "int":
|
|
1781
|
+
if not T.is_numeric(at):
|
|
1782
|
+
self._error(node, "int only supports numeric arguments")
|
|
1783
|
+
node._etype = T.I64
|
|
1784
|
+
return T.I64
|
|
1785
|
+
if name == "float":
|
|
1786
|
+
if not T.is_numeric(at):
|
|
1787
|
+
self._error(node, "float only supports numeric arguments")
|
|
1788
|
+
node._etype = T.F64
|
|
1789
|
+
return T.F64
|
|
1790
|
+
if name == "str":
|
|
1791
|
+
if not (T.is_numeric(at) or T.is_str(at)):
|
|
1792
|
+
self._error(node, "str only supports numeric or string arguments")
|
|
1793
|
+
node._etype = T.STR
|
|
1794
|
+
return T.STR
|
|
1795
|
+
self._error(node, f"builtin function {name} is not supported")
|
|
1796
|
+
|
|
1797
|
+
def _check_input(self, node: ast.Call) -> T.Type:
|
|
1798
|
+
"""input() / input(prompt): read one line from standard input, return str."""
|
|
1799
|
+
if len(node.args) > 1:
|
|
1800
|
+
self._error(node, "input takes at most one argument")
|
|
1801
|
+
arg_types: List[T.Type] = []
|
|
1802
|
+
if node.args:
|
|
1803
|
+
at = self._infer_expr(node.args[0])
|
|
1804
|
+
if not T.is_str(at):
|
|
1805
|
+
self._error(node.args[0], "input prompt must be a string")
|
|
1806
|
+
arg_types.append(T.base(at))
|
|
1807
|
+
node._builtin = "input"
|
|
1808
|
+
node._arg_types = arg_types
|
|
1809
|
+
node._etype = T.STR
|
|
1810
|
+
return T.STR
|
|
1811
|
+
|
|
1812
|
+
def _check_print(self, node: ast.Call) -> T.Type:
|
|
1813
|
+
sep: Optional[str] = None
|
|
1814
|
+
end: Optional[str] = None
|
|
1815
|
+
for kw in node.keywords:
|
|
1816
|
+
if kw.arg not in ("sep", "end"):
|
|
1817
|
+
self._error(kw, "print only supports the 'sep' and 'end' keywords")
|
|
1818
|
+
if not isinstance(kw.value, ast.Constant) or not isinstance(
|
|
1819
|
+
kw.value.value, str
|
|
1820
|
+
):
|
|
1821
|
+
self._error(kw, "print 'sep'/'end' must be string constants")
|
|
1822
|
+
if kw.arg == "sep":
|
|
1823
|
+
sep = kw.value.value
|
|
1824
|
+
else:
|
|
1825
|
+
end = kw.value.value
|
|
1826
|
+
arg_types = []
|
|
1827
|
+
for arg in node.args:
|
|
1828
|
+
t = self._infer_expr(arg)
|
|
1829
|
+
if not (T.is_int(t) or T.is_float(t) or T.is_bool(t) or T.is_str(t)
|
|
1830
|
+
or T.is_bytes(t) or T.is_enum(t) or T.is_char(t)):
|
|
1831
|
+
self._error(arg, f"print does not support type {T.describe(t)}")
|
|
1832
|
+
arg_types.append(T.I32 if T.is_enum(t) else T.base(t))
|
|
1833
|
+
node._builtin = "print"
|
|
1834
|
+
node._arg_types = arg_types
|
|
1835
|
+
node._sep = sep
|
|
1836
|
+
node._end = end
|
|
1837
|
+
node._etype = T.VOID
|
|
1838
|
+
return T.VOID
|
|
1839
|
+
|
|
1840
|
+
def _check_func_call(self, node: ast.Call) -> T.Type:
|
|
1841
|
+
f = node.func
|
|
1842
|
+
assert isinstance(f, ast.Name)
|
|
1843
|
+
fi = self.functions[f.id]
|
|
1844
|
+
if node.keywords:
|
|
1845
|
+
self._error(node, f"call to {fi.name} does not support keyword arguments")
|
|
1846
|
+
if len(node.args) != len(fi.params):
|
|
1847
|
+
self._error(
|
|
1848
|
+
node,
|
|
1849
|
+
f"{fi.name} expects {len(fi.params)} argument(s), but {len(node.args)} was/were given",
|
|
1850
|
+
)
|
|
1851
|
+
arg_types = []
|
|
1852
|
+
for arg, pname in zip(node.args, fi.params):
|
|
1853
|
+
pt = fi.locals[pname].type
|
|
1854
|
+
assert pt is not None
|
|
1855
|
+
pr = T.resolve(pt)
|
|
1856
|
+
ch = self._char_from_str(pr, arg)
|
|
1857
|
+
if ch is not None:
|
|
1858
|
+
# A string literal passed to a char parameter: take the first character (_char_from_str already marked the node)
|
|
1859
|
+
at = ch
|
|
1860
|
+
else:
|
|
1861
|
+
at = self._infer_arg_against(arg, pt)
|
|
1862
|
+
arg_types.append(at)
|
|
1863
|
+
try:
|
|
1864
|
+
unified = T.unify(pt, at)
|
|
1865
|
+
except T.TypesMismatch as exc:
|
|
1866
|
+
self._error(
|
|
1867
|
+
arg, f"argument {pname} of call to {fi.name}: {exc}"
|
|
1868
|
+
)
|
|
1869
|
+
current = T.resolve(pt)
|
|
1870
|
+
if not isinstance(current, T.TVar) and not T.same(unified, current):
|
|
1871
|
+
self._error(
|
|
1872
|
+
arg,
|
|
1873
|
+
f"argument {pname} has type {T.describe(current)}, "
|
|
1874
|
+
f"but a value of type {T.describe(unified)} was passed",
|
|
1875
|
+
)
|
|
1876
|
+
node._fi = fi
|
|
1877
|
+
node._arg_types = arg_types
|
|
1878
|
+
node._etype = T.resolve(fi.ret)
|
|
1879
|
+
return node._etype
|