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,3229 @@
1
+ """Checker pass 1: type unification, inference, and import/symbol registration."""
2
+
3
+ import ast
4
+ import re
5
+ from dataclasses import replace
6
+ from typing import Dict, List, Optional, Tuple
7
+
8
+ from . import irtypes as T
9
+ from . import runtime_lib
10
+ from . import preprocessor as pp
11
+ from .errors import CompileError, Diagnostic
12
+ from .type_symbols import (
13
+ Symbol, FuncInfo,
14
+ QUALIFIER_KINDS, QUALIFIER_DISPLAY, FORBIDDEN_ARRAY_METHODS,
15
+ PTR_API_NAMES, MEM_API_NAMES, IO_API_NAMES,
16
+ STRINGS_API_NAMES, BYTES_API_NAMES,
17
+ C_EXPR_API_NAMES, C_STMT_API_NAMES,
18
+ TYPE_PATH_MAP, undefined_name_message,
19
+ )
20
+ from .lang_api import (
21
+ CATEGORY_SPECIALS, category_hint, type_import_hint,
22
+ )
23
+
24
+ # Total width of @c.word(W): C's bit-field backing integer has only these four widths, and W directly determines the storage type.
25
+ _VALID_WORD_BITS = (8, 16, 32, 64)
26
+ # Segment names must enter C string literals verbatim, so only safe characters that need no escaping are allowed.
27
+ _SECTION_NAME_RE = re.compile(r"^[A-Za-z0-9_.$-]+$")
28
+ # The C symbol name of @c.export: must be a valid C identifier and must not collide with compiler-reserved entry names
29
+ _C_SYMBOL_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
30
+
31
+
32
+ class Pass1:
33
+ """Pass 1 check: register imports, types, and top-level declarations; roughly compute expression types so global variables can be typed."""
34
+ def _is_docstring(self, stmt: ast.stmt) -> bool:
35
+ return isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant) \
36
+ and isinstance(stmt.value.value, str)
37
+
38
+ def _register_imports(self) -> None:
39
+ """Register import statements.
40
+
41
+ Language symbols are layered by category: they can only be imported from embeddedpy.<category>,
42
+ and the name must belong to the category it comes from (cross-category imports error out).
43
+ """
44
+ for stmt in self.tree.body:
45
+ if isinstance(stmt, ast.Import):
46
+ for alias in stmt.names:
47
+ path = alias.name
48
+ if path not in CATEGORY_SPECIALS:
49
+ self._error(
50
+ stmt,
51
+ f"can only import from embeddedpy category modules ({category_hint()}); "
52
+ f"cannot import {path}",
53
+ code="import",
54
+ )
55
+ continue
56
+ bound = alias.asname or path.split(".")[0]
57
+ # import a.b binds the root name a (Python semantics),
58
+ # attribute-chain expansion form: embeddedpy.types.int32
59
+ module_path = path if alias.asname else bound
60
+ self.scope[bound] = Symbol(
61
+ kind="module", name=bound, module_path=module_path
62
+ )
63
+ elif isinstance(stmt, ast.ImportFrom):
64
+ module = stmt.module or ""
65
+ if module == "embeddedpy":
66
+ # All types are provided by embeddedpy.types; the top-level embeddedpy accepts no names.
67
+ for alias in stmt.names:
68
+ self._error(
69
+ stmt,
70
+ f"cannot import {alias.name!r} from embeddedpy; "
71
+ f"import it from its category module instead "
72
+ f"({type_import_hint(alias.name)})",
73
+ code="import",
74
+ )
75
+ continue
76
+ specials = CATEGORY_SPECIALS.get(module)
77
+ if specials is None:
78
+ self._error(
79
+ stmt,
80
+ f"can only import from embeddedpy category modules ({category_hint()}); "
81
+ f"cannot import from {module or '.'}",
82
+ code="import",
83
+ )
84
+ continue
85
+ for alias in stmt.names:
86
+ kind = specials.get(alias.name)
87
+ if kind is None:
88
+ self._error(
89
+ stmt,
90
+ f"{module} has no attribute named {alias.name}",
91
+ code="import",
92
+ )
93
+ continue
94
+ bound = alias.asname or alias.name
95
+ if kind == "scalar":
96
+ target = TYPE_PATH_MAP.get(f"{module}.{alias.name}")
97
+ self.scope[bound] = Symbol(
98
+ kind="type", name=bound, type=target
99
+ )
100
+ elif kind == "file_type":
101
+ # File is a runtime handle type (py_file struct on the C side)
102
+ self.scope[bound] = Symbol(
103
+ kind="type", name=bound, type=T.FILE
104
+ )
105
+ elif kind == "enum_base":
106
+ # Enum is an enum base-class marker, handled as a type in scope
107
+ self.scope[bound] = Symbol(
108
+ kind="type", name=bound, type=T.TVar()
109
+ )
110
+ elif kind in ("struct_base", "union_base"):
111
+ # Struct / Union are aggregate base-class markers, handled as types in scope
112
+ self.scope[bound] = Symbol(
113
+ kind="type", name=bound, type=T.TVar()
114
+ )
115
+ else:
116
+ self.scope[bound] = Symbol(kind=kind, name=bound)
117
+
118
+ def _collect_globals(self) -> None:
119
+ names: List[str] = []
120
+
121
+ def visit(stmts: List[ast.stmt]) -> None:
122
+ for stmt in stmts:
123
+ if isinstance(stmt, ast.Assign):
124
+ targets = [stmt.targets[0]]
125
+ self._add(names, targets)
126
+ elif isinstance(stmt, (ast.AnnAssign, ast.AugAssign)):
127
+ self._add(names, [stmt.target])
128
+ elif isinstance(stmt, (ast.For,)):
129
+ self._add(names, [stmt.target])
130
+ visit(stmt.body)
131
+ visit(stmt.orelse)
132
+ elif isinstance(stmt, (ast.If, ast.While)):
133
+ visit(stmt.body)
134
+ visit(stmt.orelse)
135
+ # Assignments inside a function body belong to function-local variables; module-level function names are not global variables
136
+
137
+ visit(self.tree.body)
138
+ for name in names:
139
+ if name in self.globals:
140
+ continue
141
+ sym = Symbol(kind="global", name=name, type=T.TVar(), c_name=f"g_{name}")
142
+ self.globals[name] = sym
143
+ if name in self.scope:
144
+ self._error(self.tree, f"name {name} is already defined", code="name")
145
+ self.scope[name] = sym
146
+
147
+ def _add(self, names: List[str], targets: List[ast.AST]) -> None:
148
+ for t in targets:
149
+ if isinstance(t, ast.Name):
150
+ names.append(t.id)
151
+
152
+ def _is_c_include_call(self, node: ast.AST) -> bool:
153
+ """Determine whether this is a c.include(...) call."""
154
+ if not isinstance(node, ast.Call):
155
+ return False
156
+ func = node.func
157
+ return (
158
+ isinstance(func, ast.Attribute)
159
+ and func.attr == "include"
160
+ and isinstance(func.value, ast.Name)
161
+ and func.value.id == "c"
162
+ )
163
+
164
+ @staticmethod
165
+ def _c_registration_call_name(node: ast.AST) -> Optional[str]:
166
+ """Determine whether this is a c.extern_type(...) / c.extern_const(...) call, returning the member name.
167
+
168
+ These two calls are **pure compile-time registrations** and must be written on the RHS of an assignment (``A = c.extern_type("A")``).
169
+ Written as a standalone statement or used as a value is meaningless; give a clear error rather than letting it fall into the general expression inference.
170
+ """
171
+ if not isinstance(node, ast.Call):
172
+ return None
173
+ func = node.func
174
+ if not (
175
+ isinstance(func, ast.Attribute)
176
+ and func.attr in (
177
+ "extern_type", "extern_const", "typedef", "extern_var", "define"
178
+ )
179
+ and isinstance(func.value, ast.Name)
180
+ and func.value.id == "c"
181
+ ):
182
+ return None
183
+ return func.attr
184
+
185
+ def _c_member_name(self, f: ast.Attribute) -> Optional[str]:
186
+ """Identify c.xxx (c is the C interop namespace), returning the member name; None otherwise."""
187
+ base = f.value
188
+ if not isinstance(base, ast.Name):
189
+ return None
190
+ sym = self._lookup(base.id)
191
+ if sym is None or sym.kind != "c_module":
192
+ return None
193
+ return f.attr
194
+
195
+ def _collect_includes(self) -> None:
196
+ """Collect the module-top-level c.include("header.h") calls.
197
+
198
+ c.include must be a standalone statement at module top level (cannot be written inside an expression),
199
+ because it corresponds to C's #include preprocessor directive.
200
+ """
201
+ for stmt in ast.walk(self.tree):
202
+ if not isinstance(stmt, ast.Expr):
203
+ continue
204
+ call = stmt.value
205
+ if not isinstance(call, ast.Call):
206
+ continue
207
+ func = call.func
208
+ if not (isinstance(func, ast.Attribute)
209
+ and func.attr == "include"
210
+ and isinstance(func.value, ast.Name)
211
+ and func.value.id == "c"):
212
+ continue
213
+ if getattr(stmt, "_pp_block_decl", False):
214
+ # An include inside a conditional block is emitted in place within #if in source order, not promoted to the file header,
215
+ # otherwise the same line would be emitted twice and the branch selection would lose its meaning.
216
+ _, err = pp.render_decl_directive(call)
217
+ if err is not None:
218
+ self._error(call, err, code="unsupported")
219
+ continue
220
+ if stmt not in self.tree.body:
221
+ self._error(
222
+ stmt,
223
+ "c.include must appear at module top level (it maps to a C #include directive)",
224
+ code="unsupported",
225
+ )
226
+ if call.keywords:
227
+ system = False
228
+ for kw in call.keywords:
229
+ if kw.arg != "system":
230
+ self._error(
231
+ call,
232
+ f"c.include does not support keyword argument {kw.arg}",
233
+ code="unsupported",
234
+ )
235
+ if not (isinstance(kw.value, ast.Constant) and kw.value.value is True):
236
+ self._error(
237
+ call,
238
+ "c.include 'system' argument must be True (system headers use <>)",
239
+ code="unsupported",
240
+ )
241
+ system = True
242
+ else:
243
+ system = False
244
+ if len(call.args) not in (1, 2):
245
+ self._error(
246
+ call,
247
+ "c.include requires a header name; the optional second argument is system=True",
248
+ code="unsupported",
249
+ )
250
+ header_node = call.args[0]
251
+ if not (isinstance(header_node, ast.Constant)
252
+ and isinstance(header_node.value, str)):
253
+ self._error(call, "c.include header name must be a string", code="unsupported")
254
+ if len(call.args) == 2:
255
+ flag = call.args[1]
256
+ if not (isinstance(flag, ast.Constant) and flag.value is True):
257
+ self._error(
258
+ call,
259
+ "c.include second argument must be system=True (system headers use <>)",
260
+ code="unsupported",
261
+ )
262
+ system = True
263
+ entry = (header_node.value, system)
264
+ if entry not in self.includes:
265
+ self.includes.append(entry)
266
+
267
+ def _scan_bare_decls(self) -> None:
268
+ """Register bare calls that "do not assign": c.extern_const("NAME", v) / c.define("NAME", v).
269
+
270
+ The names of these two calls are written in the arguments and need no LHS: the C track only emits a declaration / macro definition,
271
+ and the CPython track has no name to bind either (the return value is simply discarded). So they **do not enter scope**
272
+ (otherwise ``LIMIT`` would be resolved as a real Python name, diverging from the dev track),
273
+ and are instead stored separately in self.decls for codegen to consume.
274
+
275
+ Other registration-class members (extern_type / typedef / extern_var) must bind a name,
276
+ so bare calls still error out at the _type_stmt gate.
277
+ """
278
+ seen = set()
279
+ for stmt in self.tree.body:
280
+ if not isinstance(stmt, ast.Expr) or not isinstance(stmt.value, ast.Call):
281
+ continue
282
+ call = stmt.value
283
+ reg = self._c_registration_call_name(call)
284
+ if reg not in ("extern_const", "define"):
285
+ continue
286
+ if call.keywords or len(call.args) != 2:
287
+ self._error(call, f"c.{reg} requires exactly (name: str, value)")
288
+ name_arg, val_arg = call.args
289
+ if not (isinstance(name_arg, ast.Constant)
290
+ and isinstance(name_arg.value, str) and name_arg.value):
291
+ self._error(
292
+ name_arg, f"c.{reg} name must be a non-empty string literal"
293
+ )
294
+ c_name = name_arg.value
295
+ if (reg, c_name) in seen:
296
+ self._error(call, f"c.{reg} {c_name!r} is already declared")
297
+ seen.add((reg, c_name))
298
+ if reg == "define":
299
+ self._check_macro_name(name_arg, c_name)
300
+ if c_name in self._macro_c_names:
301
+ self._error(call, f"macro {c_name} is already declared")
302
+ self._macro_c_names.add(c_name)
303
+
304
+ if reg == "extern_const":
305
+ lit = self._const_literal_value(val_arg)
306
+ if lit is None:
307
+ self._error(
308
+ val_arg,
309
+ "c.extern_const value must be an integer or float literal",
310
+ )
311
+ const_type: T.Type = (
312
+ T.ConstInt(int(lit)) if isinstance(lit, int)
313
+ else T.ConstFloat(float(lit))
314
+ )
315
+ self.decls.append(Symbol(
316
+ kind="extern_const", name=c_name, type=const_type,
317
+ c_name=c_name, quals=["const"],
318
+ const_value=int(lit) if isinstance(lit, int) else None,
319
+ ))
320
+ else:
321
+ if not isinstance(val_arg, ast.Constant):
322
+ self._error(
323
+ val_arg,
324
+ "c.define value must be an integer, float, or string literal",
325
+ )
326
+ lit = val_arg.value
327
+ if isinstance(lit, bool) or not isinstance(lit, (int, float, str)):
328
+ self._error(
329
+ val_arg,
330
+ "c.define value must be an integer, float, or string literal",
331
+ )
332
+ self.decls.append(Symbol(
333
+ kind="macro", name=c_name, c_name=c_name,
334
+ type=T.ConstInt(lit) if isinstance(lit, int) else T.STR,
335
+ macro_value=lit,
336
+ ))
337
+ stmt._bare_decl = True
338
+
339
+ def _register_type_aliases(self) -> None:
340
+ """Pre-bind type aliases, external declaration names, and segment descriptors: ``int32_ptr = c.typedef(Ptr[int32])``,
341
+ ``A = c.extern_type("A")``, ``isr_sec = c.section(".isr_vector")``, etc.
342
+
343
+ Must be completed before _register_functions -- function parameter annotations
344
+ (def f(p: Ptr[A])) need these names.
345
+ """
346
+ self._second_pass = False
347
+ for stmt in self.tree.body:
348
+ if not isinstance(stmt, ast.Assign):
349
+ continue
350
+ target = stmt.targets[0]
351
+ if not isinstance(target, ast.Name):
352
+ continue
353
+ if self._try_section_binding(stmt, target):
354
+ continue
355
+ if self._try_extern_type(stmt, target):
356
+ continue
357
+ if self._try_extern_const(stmt, target):
358
+ continue
359
+ if self._try_extern_var(stmt, target):
360
+ continue
361
+ if self._try_macro(stmt, target):
362
+ continue
363
+ self._try_type_alias(stmt, target)
364
+ self._check_section_bindings()
365
+
366
+ @staticmethod
367
+ def _is_section_call(node: ast.AST) -> bool:
368
+ """Determine whether this is a ``c.section(...)`` call."""
369
+ if not isinstance(node, ast.Call):
370
+ return False
371
+ f = node.func
372
+ return (
373
+ isinstance(f, ast.Attribute)
374
+ and f.attr == "section"
375
+ and isinstance(f.value, ast.Name)
376
+ and f.value.id == "c"
377
+ )
378
+
379
+ def _try_section_binding(self, stmt: ast.Assign, target: ast.Name) -> bool:
380
+ """Identify ``name = c.section(".x")``: register the segment name as a compile-time descriptor.
381
+
382
+ A descriptor is neither a value nor a type; it only has meaning at the ``name[T]`` position in annotations; the binding
383
+ statement itself generates no C code. The name is chosen by the user by semantics; the compiler recognizes it by the bound value,
384
+ not by the name. Segment-name validation is done once here; the annotation site only looks it up.
385
+ """
386
+ value = stmt.value
387
+ if not self._is_section_call(value):
388
+ return False
389
+ if getattr(stmt, "_pp_block_decl", False):
390
+ self._error(
391
+ stmt,
392
+ "section descriptor binding must be at module top level",
393
+ code="unsupported",
394
+ )
395
+ if value.keywords or len(value.args) != 1:
396
+ self._error(
397
+ value,
398
+ 'section descriptor requires exactly one section name: '
399
+ 'name = c.section(".noinit")',
400
+ )
401
+ return False
402
+ arg = value.args[0]
403
+ if not (isinstance(arg, ast.Constant)
404
+ and isinstance(arg.value, str) and arg.value):
405
+ self._error(arg, "c.section name must be a non-empty string literal")
406
+ return False
407
+ name = arg.value
408
+ if not _SECTION_NAME_RE.match(name):
409
+ self._error(
410
+ arg,
411
+ "c.section name contains unsupported characters; "
412
+ "use letters, digits, '_', '.', '$' or '-'",
413
+ code="unsupported",
414
+ )
415
+ if target.id in self._section_bindings:
416
+ self._error(
417
+ target,
418
+ f"section descriptor {target.id} is already bound",
419
+ code="name",
420
+ )
421
+ self._section_bindings[target.id] = name
422
+ sym = self.scope.get(target.id)
423
+ if sym is not None:
424
+ sym.kind = "section"
425
+ sym.type = T.VOID
426
+ # Descriptors occupy no C storage: remove them from the globals table to avoid generating a g_<name> variable in the file header
427
+ self.globals.pop(target.id, None)
428
+ stmt._section_binding = True
429
+ return True
430
+
431
+ def _check_section_bindings(self) -> None:
432
+ """Segment descriptors are only allowed as a single ordinary top-level assignment; all other positions are rejected."""
433
+ for node in ast.walk(self.tree):
434
+ if not isinstance(node, ast.Assign):
435
+ continue
436
+ if getattr(node, "_section_binding", False):
437
+ continue
438
+ if self._is_section_call(node.value):
439
+ self._error(
440
+ node,
441
+ "section descriptor binding must be a module-level "
442
+ 'assignment: name = c.section(".noinit")',
443
+ code="unsupported",
444
+ )
445
+
446
+ def _try_extern_type(self, stmt: ast.Assign, target: ast.Name) -> bool:
447
+ """Identify ``A = c.extern_type("A")``: register a type name whose definition authority lies in an external header.
448
+
449
+ The compiler only registers its name and does not emit a typedef; the C-side name is provided by c.include
450
+ through the included header. The field table is always empty, so field access errors out in both checker passes.
451
+ """
452
+ value = stmt.value
453
+ if not isinstance(value, ast.Call):
454
+ return False
455
+ f = value.func
456
+ if not (isinstance(f, ast.Attribute)
457
+ and f.attr == "extern_type"
458
+ and isinstance(f.value, ast.Name)
459
+ and f.value.id == "c"):
460
+ return False
461
+ if value.keywords or len(value.args) not in (1, 2):
462
+ self._error(
463
+ value,
464
+ "c.extern_type requires (name) for a struct, "
465
+ "(name, Func[[...], ret]) for a function pointer, or "
466
+ "(name, fixed-width numeric type) for a native C scalar",
467
+ )
468
+ arg = value.args[0]
469
+ if not (isinstance(arg, ast.Constant)
470
+ and isinstance(arg.value, str) and arg.value):
471
+ self._error(
472
+ value,
473
+ "c.extern_type type name must be a non-empty string literal",
474
+ )
475
+ c_name = arg.value
476
+ if len(value.args) == 2:
477
+ # The 2-arg form has two shapes. Func[[...], ret] is an external function pointer type name;
478
+ # the fixed-width numeric type name treats C native scalars (size_t / ptrdiff_t / ...)
479
+ # as value registrations: the C name is spelled verbatim, and type checking follows the fixed-width semantics of the specified width.
480
+ sig_node = value.args[1]
481
+ sig_ok = (
482
+ isinstance(sig_node, ast.Subscript)
483
+ and isinstance(sig_node.value, ast.Name)
484
+ and sig_node.value.id == "Func"
485
+ )
486
+ if sig_ok:
487
+ sig = self._resolve_func_annotation(sig_node)
488
+ extern_t = T.Ptr(
489
+ T.ExternFuncPtr(
490
+ args=sig.args, ret=sig.ret, name=target.id, c_name=c_name
491
+ )
492
+ )
493
+ else:
494
+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", c_name):
495
+ self._error(
496
+ value,
497
+ "c.extern_type scalar form requires a plain C identifier "
498
+ "as the type name",
499
+ )
500
+ base_type = self._resolve_type_arg(sig_node)
501
+ if base_type is None and isinstance(sig_node, ast.Name):
502
+ base_type = TYPE_PATH_MAP.get(sig_node.id)
503
+ base = T.resolve(base_type) if base_type is not None else None
504
+ if not isinstance(base, T.Scalar) or base.category not in ("int", "float"):
505
+ self._error(
506
+ sig_node,
507
+ "c.extern_type scalar form requires a fixed-width numeric "
508
+ "type as the second argument (e.g. uint64)",
509
+ )
510
+ extern_t = T.Scalar(
511
+ name=c_name,
512
+ ctype=c_name,
513
+ bits=base.bits,
514
+ signed=base.signed,
515
+ category=base.category,
516
+ )
517
+ else:
518
+ extern_t = T.ExternType(name=target.id, c_name=c_name)
519
+ seen = getattr(self, "_extern_type_seen", None)
520
+ if seen is None:
521
+ seen = set()
522
+ self._extern_type_seen = seen
523
+ if target.id in seen:
524
+ self._error(target, f"external type {target.id} is already declared")
525
+ seen.add(target.id)
526
+ sym = self.scope.get(target.id)
527
+ if sym is None:
528
+ self._error(target, undefined_name_message(target.id), code="name")
529
+ existing = T.resolve(sym.type) if sym.type is not None else None
530
+ if isinstance(existing, T.ExternType):
531
+ if existing.c_name != c_name:
532
+ self._error(
533
+ target,
534
+ f"{target.id} is already bound to external type {existing.c_name!r}",
535
+ )
536
+ stmt._extern_type = True
537
+ return True
538
+ if sym.kind != "global" or not isinstance(existing, T.TVar):
539
+ self._error(target, f"{target.id} has already been assigned")
540
+ sym.kind = "type"
541
+ sym.type = extern_t
542
+ # Type names occupy no storage: remove from globals to avoid codegen generating a g_A variable declaration
543
+ self.globals.pop(target.id, None)
544
+ stmt._extern_type = True
545
+ return True
546
+
547
+ @staticmethod
548
+ def _const_literal_value(node: ast.AST) -> Optional[object]:
549
+ """Get an integer/float value from a literal node, supporting a leading minus (UnaryOp USub).
550
+
551
+ Only int / float literals are accepted (bool is excluded because it is not an integer constant).
552
+ """
553
+ if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) \
554
+ and not isinstance(node.value, bool):
555
+ return node.value
556
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
557
+ inner = Pass1._const_literal_value(node.operand)
558
+ if inner is not None:
559
+ return -inner
560
+ return None
561
+
562
+ def _try_extern_const(self, stmt: ast.Assign, target: ast.Name) -> bool:
563
+ """Identify ``MAX = c.extern_const("MAX", 256)``: register the constant name from the header file.
564
+
565
+ The compiler only registers its name and does not emit a definition; the C-side reference writes the name MAX directly,
566
+ and the definition is provided by the header brought in via ``c.include``. value is used to determine the CPython-track
567
+ placeholder value type (integer -> ConstInt, float -> ConstFloat), and participates in constant expressions;
568
+ the C track does not emit it. The statement itself is skipped in both checker passes and codegen (same as extern_type).
569
+ """
570
+ value = stmt.value
571
+ if not isinstance(value, ast.Call):
572
+ return False
573
+ f = value.func
574
+ if not (isinstance(f, ast.Attribute)
575
+ and f.attr == "extern_const"
576
+ and isinstance(f.value, ast.Name)
577
+ and f.value.id == "c"):
578
+ return False
579
+ if value.keywords or len(value.args) != 2:
580
+ self._error(value, "c.extern_const requires exactly (name: str, value)")
581
+ name_arg = value.args[0]
582
+ val_arg = value.args[1]
583
+ if not (isinstance(name_arg, ast.Constant)
584
+ and isinstance(name_arg.value, str) and name_arg.value):
585
+ self._error(
586
+ name_arg, "c.extern_const name must be a non-empty string literal"
587
+ )
588
+ c_name = name_arg.value
589
+ lit = self._const_literal_value(val_arg)
590
+ if lit is None:
591
+ self._error(
592
+ val_arg, "c.extern_const value must be an integer or float literal"
593
+ )
594
+ # Type: integer -> ConstInt, float -> ConstFloat (same mechanism as module-level X = 5)
595
+ const_type: T.Type = (
596
+ T.ConstInt(int(lit)) if isinstance(lit, int) else T.ConstFloat(float(lit))
597
+ )
598
+ seen = getattr(self, "_extern_const_seen", None)
599
+ if seen is None:
600
+ seen = set()
601
+ self._extern_const_seen = seen
602
+ if target.id in seen:
603
+ self._error(target, f"external constant {target.id} is already declared")
604
+ seen.add(target.id)
605
+ sym = self.scope.get(target.id)
606
+ if sym is None:
607
+ self._error(target, undefined_name_message(target.id), code="name")
608
+ existing = T.resolve(sym.type) if sym.type is not None else None
609
+ if isinstance(existing, (T.ConstInt, T.ConstFloat)):
610
+ # An external constant of the same name was already registered: both name and value must match
611
+ if sym.c_name != c_name or existing.value != lit:
612
+ self._error(
613
+ target, f"{target.id} is already bound to external constant {c_name!r}"
614
+ )
615
+ stmt._extern_const = True
616
+ return True
617
+ if sym.kind != "global" or not isinstance(existing, T.TVar):
618
+ self._error(target, f"{target.id} has already been assigned")
619
+ sym.kind = "extern_const"
620
+ sym.type = const_type
621
+ sym.c_name = c_name
622
+ sym.quals = ["const"]
623
+ # Integer constant values participate in constant expressions (e.g. make_array length); floats do not
624
+ sym.const_value = int(lit) if isinstance(lit, int) else None
625
+ # External constants occupy no storage: remove from globals to avoid codegen generating a g_MAX variable declaration
626
+ self.globals.pop(target.id, None)
627
+ stmt._extern_const = True
628
+ return True
629
+
630
+ def _try_extern_var(self, stmt: ast.Assign, target: ast.Name) -> bool:
631
+ """Identify ``shared = c.extern_var("shared", int32)``: register an external C variable.
632
+
633
+ In H mode only ``extern <T> shared;`` is emitted; in C mode **nothing is emitted at all** -- the definition comes from the external
634
+ translation unit and is resolved at link time. type is a type name (e.g. ``int32``), used to determine the H-side
635
+ declaration type; name must match the external C variable's name verbatim.
636
+ """
637
+ value = stmt.value
638
+ if not isinstance(value, ast.Call):
639
+ return False
640
+ f = value.func
641
+ if not (isinstance(f, ast.Attribute)
642
+ and f.attr == "extern_var"
643
+ and isinstance(f.value, ast.Name)
644
+ and f.value.id == "c"):
645
+ return False
646
+ if value.keywords or len(value.args) != 2:
647
+ self._error(value, "c.extern_var requires exactly (name: str, type)")
648
+ return False
649
+ name_arg, type_arg = value.args[0], value.args[1]
650
+ if not (isinstance(name_arg, ast.Constant)
651
+ and isinstance(name_arg.value, str) and name_arg.value):
652
+ self._error(
653
+ name_arg, "c.extern_var name must be a non-empty string literal"
654
+ )
655
+ return False
656
+ c_name = name_arg.value
657
+ ann, quals = self._resolve_annotated(type_arg)
658
+ seen = getattr(self, "_extern_var_seen", None)
659
+ if seen is None:
660
+ seen = set()
661
+ self._extern_var_seen = seen
662
+ if target.id in seen:
663
+ self._error(target, f"external variable {target.id} is already declared")
664
+ seen.add(target.id)
665
+ sym = self.scope.get(target.id)
666
+ if sym is None:
667
+ self._error(target, undefined_name_message(target.id), code="name")
668
+ existing = T.resolve(sym.type) if sym.type is not None else None
669
+ if sym.kind != "global" or not isinstance(existing, T.TVar):
670
+ self._error(target, f"{target.id} has already been assigned")
671
+ sym.kind = "extern_var"
672
+ sym.type = ann
673
+ sym.quals = quals
674
+ sym.c_name = c_name
675
+ # External variables occupy no storage: remove from globals to avoid codegen generating a g_shared variable declaration
676
+ self.globals.pop(target.id, None)
677
+ stmt._extern_var = True
678
+ return True
679
+
680
+ def _check_macro_name(self, node: ast.AST, c_name: str) -> None:
681
+ """A macro is a plain text substitution by the preprocessor: its name must not collide with the compiler-inlined runtime identifiers.
682
+
683
+ Runtime code is inlined into the output by the compiler and is invisible to the user; when a macro name collides with an identifier inside it, that identifier gets replaced
684
+ (e.g. ``#define b 1`` would turn ``py_block *b`` into ``py_block *1``).
685
+ The reserved words are derived from the fragment C text, and the fragment set is the sole source.
686
+ """
687
+ if c_name in runtime_lib.RESERVED_IDENTIFIERS:
688
+ self._error(
689
+ node,
690
+ f"c.define macro name {c_name!r} collides with an identifier "
691
+ f"used by the inlined runtime; choose a different macro name",
692
+ )
693
+
694
+ def _try_macro(self, stmt: ast.Assign, target: ast.Name) -> bool:
695
+ """Identify ``BUFSZ = c.define("BUFSZ", 256)``: register a C macro.
696
+
697
+ Both H and C sides emit ``#define BUFSZ 256``; value also serves as the CPython-track placeholder value.
698
+ value must be an int / float / string literal. Macros do not participate in type checking.
699
+
700
+ The macro name must equal the bound name: only when names match do both tracks reference the same name, so the macro value can be used
701
+ as a compile-time constant (e.g. make_array length); a mismatched name errors out.
702
+ """
703
+ value = stmt.value
704
+ if not isinstance(value, ast.Call):
705
+ return False
706
+ f = value.func
707
+ if not (isinstance(f, ast.Attribute)
708
+ and f.attr == "define"
709
+ and isinstance(f.value, ast.Name)
710
+ and f.value.id == "c"):
711
+ return False
712
+ if value.keywords or len(value.args) != 2:
713
+ self._error(value, "c.define requires exactly (name: str, value)")
714
+ return False
715
+ name_arg, val_arg = value.args[0], value.args[1]
716
+ if not (isinstance(name_arg, ast.Constant)
717
+ and isinstance(name_arg.value, str) and name_arg.value):
718
+ self._error(
719
+ name_arg, "c.define name must be a non-empty string literal"
720
+ )
721
+ return False
722
+ c_name = name_arg.value
723
+ # After multi-module merging, target.id carries a ``module_name__`` prefix; the macro-name constraint targets the binding name
724
+ # written in the user source code, and diagnostics must show the name the user can see.
725
+ binding = getattr(stmt, "_embeddedpy_orig_name", target.id)
726
+ if c_name != binding:
727
+ self._error(
728
+ name_arg,
729
+ f"c.define macro name {c_name!r} must match the binding name "
730
+ f"{binding!r}; write {c_name} = c.define({c_name!r}, value) "
731
+ f"or use a bare c.define({c_name!r}, value) call",
732
+ )
733
+ self._check_macro_name(name_arg, c_name)
734
+ if not isinstance(val_arg, ast.Constant):
735
+ self._error(val_arg, "c.define value must be an integer, float, or string literal")
736
+ return False
737
+ lit = val_arg.value
738
+ if isinstance(lit, bool) or not isinstance(lit, (int, float, str)):
739
+ self._error(val_arg, "c.define value must be an integer, float, or string literal")
740
+ return False
741
+ seen = getattr(self, "_macro_seen", None)
742
+ if seen is None:
743
+ seen = set()
744
+ self._macro_seen = seen
745
+ if target.id in seen:
746
+ self._error(target, f"macro {target.id} is already declared")
747
+ seen.add(target.id)
748
+ # On the C side there can be only one #define with the same name: cross-module/bare-call and assignment forms are all checked for duplicates here
749
+ if c_name in self._macro_c_names:
750
+ self._error(name_arg, f"macro {c_name} is already declared")
751
+ self._macro_c_names.add(c_name)
752
+ sym = self.scope.get(target.id)
753
+ if sym is None:
754
+ self._error(target, undefined_name_message(target.id), code="name")
755
+ existing = T.resolve(sym.type) if sym.type is not None else None
756
+ if sym.kind != "global" or not isinstance(existing, T.TVar):
757
+ self._error(target, f"{target.id} has already been assigned")
758
+ sym.kind = "macro"
759
+ sym.c_name = c_name
760
+ sym.macro_value = lit
761
+ # A macro used as a value in an expression still needs a type: take the type of its literal value
762
+ # (int macro -> ConstInt, float macro -> ConstFloat, string macro -> text type).
763
+ # This does not change the positioning of "macros are text substitution and do not participate in type checking" -- it only lets print/arithmetic
764
+ # locations that use the macro value infer the same C type as a literal.
765
+ if isinstance(lit, bool):
766
+ sym.type = T.ConstInt(int(lit))
767
+ elif isinstance(lit, int):
768
+ sym.type = T.ConstInt(lit)
769
+ sym.const_value = lit
770
+ elif isinstance(lit, float):
771
+ sym.type = T.ConstFloat(lit)
772
+ else:
773
+ sym.type = T.STR
774
+ # A macro is not a variable: remove it from globals but keep it in scope for reference resolution (c_name = macro name)
775
+ self.globals.pop(target.id, None)
776
+ stmt._macro = True
777
+ return True
778
+
779
+ def _register_functions(self) -> None:
780
+ for stmt in self.tree.body:
781
+ if not isinstance(stmt, ast.FunctionDef):
782
+ continue
783
+ if (stmt.name in self.functions or stmt.name in self.globals
784
+ or stmt.name in self.scope):
785
+ self._error(stmt, f"name {stmt.name} is already defined", code="name")
786
+ args = stmt.args
787
+ params: List[str] = []
788
+ local_syms: Dict[str, Symbol] = {}
789
+ all_args = list(args.posonlyargs) + list(args.args)
790
+ for arg in all_args:
791
+ if arg.annotation:
792
+ if self._has_section_wrapper(arg.annotation):
793
+ self._error(
794
+ arg.annotation,
795
+ "section descriptor qualifier is only supported on module-level variables",
796
+ code="unsupported",
797
+ )
798
+ ann, quals = self._resolve_annotated(arg.annotation)
799
+ else:
800
+ ann, quals = T.TVar(), []
801
+ sym = Symbol(
802
+ kind="param",
803
+ name=arg.arg,
804
+ type=ann,
805
+ c_name=f"v_{arg.arg}",
806
+ quals=quals,
807
+ )
808
+ if "const" in quals and isinstance(T.resolve(ann), T.Ptr):
809
+ self._error(
810
+ arg.annotation,
811
+ "const-qualified pointer parameters are not supported"
812
+ " (writes through the pointer cannot be checked statically)",
813
+ )
814
+ local_syms[arg.arg] = sym
815
+ params.append(arg.arg)
816
+ # The return type comes only from the annotation on the function declaration.
817
+ if stmt.returns is None:
818
+ self._error(
819
+ stmt,
820
+ f"function {stmt.name} must declare a return type",
821
+ )
822
+ ret = self._resolve_annotation(stmt.returns)
823
+ for name in self._collect_locals(stmt):
824
+ if name not in local_syms:
825
+ local_syms[name] = Symbol(
826
+ kind="local", name=name, type=T.TVar(), c_name=f"v_{name}"
827
+ )
828
+ fi = FuncInfo(
829
+ name=stmt.name, node=stmt, ret=ret, locals=local_syms, params=params
830
+ )
831
+ # Functions decorated with @c.extern_function only generate an extern declaration on the C track;
832
+ # the function body is a CPython-track mock and must still fully pass the two checker passes.
833
+ c_name = self._extern_c_name(stmt)
834
+ export_name = self._export_c_name(stmt)
835
+ if c_name is not None and export_name:
836
+ self._error(
837
+ stmt,
838
+ "@c.export cannot be combined with @c.extern_function "
839
+ "(the definition must be in this translation unit)",
840
+ code="unsupported",
841
+ )
842
+ if c_name is not None:
843
+ fi.is_extern = True
844
+ fi.extern_c_name = c_name
845
+ if export_name:
846
+ fi.export_c_name = export_name
847
+ fi.is_inline, fi.section, fi.is_weak, fi.align, fi.visibility = (
848
+ self._function_decorators(stmt)
849
+ )
850
+ self.functions[stmt.name] = fi
851
+ sym = Symbol(
852
+ kind="func",
853
+ name=stmt.name,
854
+ c_name=export_name or (c_name if c_name is not None else f"f_{stmt.name}"),
855
+ )
856
+ self.scope[stmt.name] = sym
857
+ self._check_function_c_names()
858
+
859
+ def _check_function_c_names(self) -> None:
860
+ """A single C symbol name can only correspond to one function, to avoid an exported name colliding with an internal name."""
861
+ seen: Dict[str, str] = {}
862
+ for fi in self.functions.values():
863
+ cn = fi.export_c_name or (fi.extern_c_name if fi.is_extern else f"f_{fi.name}")
864
+ if cn == "main":
865
+ self._error(fi.node, "C symbol name 'main' is reserved "
866
+ "for the generated entry point", code="name")
867
+ if cn in seen:
868
+ self._error(
869
+ fi.node,
870
+ f"duplicate C symbol name '{cn}' (functions '{seen[cn]}' and '{fi.name}')",
871
+ code="name",
872
+ )
873
+ seen[cn] = fi.name
874
+
875
+ def _export_c_name(self, stmt: ast.FunctionDef) -> str:
876
+ """If the function is decorated with @c.export, return its exported C symbol name."""
877
+ name = ""
878
+ for dec in stmt.decorator_list:
879
+ target = dec.func if isinstance(dec, ast.Call) else dec
880
+ if not (isinstance(target, ast.Attribute)
881
+ and target.attr == "export"
882
+ and isinstance(target.value, ast.Name)
883
+ and target.value.id == "c"):
884
+ continue
885
+ if name:
886
+ self._error(dec, "duplicate @c.export decorator", code="unsupported")
887
+ arg = dec.args[0] if isinstance(dec, ast.Call) and dec.args else None
888
+ if not (isinstance(arg, ast.Constant) and isinstance(arg.value, str)):
889
+ self._error(
890
+ dec,
891
+ '@c.export requires exactly one C symbol name: @c.export("Reset_Handler")',
892
+ code="unsupported",
893
+ )
894
+ value = arg.value
895
+ if not _C_SYMBOL_RE.match(value):
896
+ self._error(
897
+ dec,
898
+ "@c.export name must be a valid C identifier",
899
+ code="unsupported",
900
+ )
901
+ name = value
902
+ return name
903
+
904
+ def _extern_c_name(self, stmt: ast.FunctionDef) -> Optional[str]:
905
+ """If the function is decorated with @c.extern_function, return its C-side symbol name."""
906
+ for dec in stmt.decorator_list:
907
+ target = dec.func if isinstance(dec, ast.Call) else dec
908
+ if not (isinstance(target, ast.Attribute)
909
+ and target.attr == "extern_function"
910
+ and isinstance(target.value, ast.Name)
911
+ and target.value.id == "c"):
912
+ continue
913
+ if isinstance(dec, ast.Attribute):
914
+ return stmt.name
915
+ if dec.args and isinstance(dec.args[0], ast.Constant) \
916
+ and isinstance(dec.args[0].value, str):
917
+ return dec.args[0].value
918
+ raise CompileError(
919
+ [
920
+ Diagnostic(
921
+ message="@c.extern_function requires an external function name: @c.extern_function(\"HAL_Init\")",
922
+ line=getattr(stmt, "lineno", 0),
923
+ col=getattr(stmt, "col_offset", 0),
924
+ filename=self.filename,
925
+ code="unsupported",
926
+ )
927
+ ]
928
+ )
929
+ return None
930
+
931
+ def _register_structs(self) -> None:
932
+ """Register aggregate and enum types. Two passes: first build empty shells, then resolve fields (forward references allowed)."""
933
+ # Pass 1: create the type object and register it in scope
934
+ for stmt in self.tree.body:
935
+ if not isinstance(stmt, ast.ClassDef):
936
+ continue
937
+ if stmt.name in self.scope:
938
+ self._error(stmt, f"name {stmt.name} is already defined", code="name")
939
+ if self._is_enum_class(stmt):
940
+ enum = T.Enum(name=stmt.name, c_name=stmt.name)
941
+ self.scope[stmt.name] = Symbol(
942
+ kind="type", name=stmt.name, type=enum
943
+ )
944
+ else:
945
+ packed, word_bits, align = self._class_decorators(stmt)
946
+ struct = T.Struct(
947
+ name=stmt.name,
948
+ c_name=stmt.name,
949
+ is_union=self._is_union_class(stmt),
950
+ packed=packed,
951
+ word_bits=word_bits,
952
+ align=align,
953
+ )
954
+ self.scope[stmt.name] = Symbol(
955
+ kind="type", name=stmt.name, type=struct
956
+ )
957
+
958
+ # Pass 2: resolve fields (aggregate) or member values (enum)
959
+ for stmt in self.tree.body:
960
+ if not isinstance(stmt, ast.ClassDef):
961
+ continue
962
+ sym = self.scope[stmt.name]
963
+ if self._is_enum_class(stmt):
964
+ assert isinstance(sym.type, T.Enum)
965
+ self._resolve_enum_members(stmt, sym.type)
966
+ continue
967
+ struct = sym.type
968
+ assert isinstance(struct, T.Struct)
969
+ for item in stmt.body:
970
+ if (
971
+ isinstance(item, ast.Expr)
972
+ and isinstance(item.value, ast.Constant)
973
+ and isinstance(item.value.value, str)
974
+ ):
975
+ continue # docstring
976
+ assert isinstance(item, ast.AnnAssign)
977
+ fname = item.target.id
978
+ if self._has_section_wrapper(item.annotation):
979
+ self._error(
980
+ item.annotation,
981
+ "section descriptor qualifier is only supported on module-level variables",
982
+ code="unsupported",
983
+ )
984
+ ftype = self._resolve_annotation(item.annotation, allow_bits=True)
985
+ resolved = T.resolve(ftype)
986
+ if isinstance(resolved, T.Struct) and resolved is struct:
987
+ self._error(
988
+ item,
989
+ f"struct {stmt.name} cannot be self-referential; use a pointer (self-reference is not supported)",
990
+ )
991
+ struct.fields[fname] = ftype
992
+ self._validate_layout(stmt, struct)
993
+
994
+ def _is_enum_class(self, stmt: ast.ClassDef) -> bool:
995
+ """Determine whether a class is an enum (base class is Enum)."""
996
+ if len(stmt.bases) != 1:
997
+ return False
998
+ base = stmt.bases[0]
999
+ return isinstance(base, ast.Name) and base.id == "Enum"
1000
+
1001
+ def _is_union_class(self, stmt: ast.ClassDef) -> bool:
1002
+ """Determine whether a class is a union (base class is Union)."""
1003
+ if len(stmt.bases) != 1:
1004
+ return False
1005
+ base = stmt.bases[0]
1006
+ return isinstance(base, ast.Name) and base.id == "Union"
1007
+
1008
+ def _class_decorators(self, stmt: ast.ClassDef) -> Tuple[bool, int, int]:
1009
+ """Parse @c.packed / @c.word(W) / @c.aligned(N), returning (is_packed, total_bit_width, alignment_bytes)."""
1010
+ packed = False
1011
+ word_bits = 0
1012
+ align = 0
1013
+ for dec in stmt.decorator_list:
1014
+ call = dec if isinstance(dec, ast.Call) else None
1015
+ target = dec.func if isinstance(dec, ast.Call) else dec
1016
+ if not (
1017
+ isinstance(target, ast.Attribute)
1018
+ and isinstance(target.value, ast.Name)
1019
+ and target.value.id == "c"
1020
+ ):
1021
+ self._error(dec, "unknown decorator on a struct or union", code="unsupported")
1022
+ name = target.attr
1023
+ if name == "packed":
1024
+ if packed:
1025
+ self._error(dec, "duplicate @c.packed decorator", code="unsupported")
1026
+ packed = True
1027
+ continue
1028
+ if name == "word":
1029
+ if word_bits:
1030
+ self._error(dec, "duplicate @c.word decorator", code="unsupported")
1031
+ if call is None or len(call.args) != 1:
1032
+ self._error(dec, "@c.word requires exactly one width: @c.word(32)", code="unsupported")
1033
+ arg = call.args[0]
1034
+ if not (
1035
+ isinstance(arg, ast.Constant)
1036
+ and isinstance(arg.value, int)
1037
+ and not isinstance(arg.value, bool)
1038
+ ):
1039
+ self._error(dec, "@c.word width must be an integer literal", code="unsupported")
1040
+ if arg.value not in _VALID_WORD_BITS:
1041
+ self._error(
1042
+ dec,
1043
+ "@c.word width must be one of 8, 16, 32, 64",
1044
+ code="unsupported",
1045
+ )
1046
+ word_bits = arg.value
1047
+ continue
1048
+ if name == "aligned":
1049
+ if align:
1050
+ self._error(dec, "duplicate @c.aligned decorator", code="unsupported")
1051
+ if call is None or len(call.args) != 1:
1052
+ self._error(dec, "@c.aligned requires exactly one integer width: @c.aligned(16)", code="unsupported")
1053
+ arg = call.args[0]
1054
+ if not (
1055
+ isinstance(arg, ast.Constant)
1056
+ and isinstance(arg.value, int)
1057
+ and not isinstance(arg.value, bool)
1058
+ and arg.value > 0
1059
+ ):
1060
+ self._error(dec, "@c.aligned width must be a positive integer literal", code="unsupported")
1061
+ if arg.value & (arg.value - 1) != 0:
1062
+ self._error(dec, "@c.aligned width must be a power of two", code="unsupported")
1063
+ align = arg.value
1064
+ continue
1065
+ self._error(
1066
+ dec, f"unknown decorator @c.{name} on a struct or union", code="unsupported"
1067
+ )
1068
+ return packed, word_bits, align
1069
+
1070
+ def _function_decorators(self, stmt: ast.FunctionDef) -> Tuple[bool, str, bool, int, str]:
1071
+ """Parse @c.inline / @c.section("...") / @c.weak / @c.aligned(N) /
1072
+ @c.visibility("..."); returns (is_inline, section_name, is_weak, align_bytes, visibility)."""
1073
+ is_inline = False
1074
+ section = ""
1075
+ is_weak = False
1076
+ align = 0
1077
+ visibility = ""
1078
+ for dec in stmt.decorator_list:
1079
+ call = dec if isinstance(dec, ast.Call) else None
1080
+ target = dec.func if isinstance(dec, ast.Call) else dec
1081
+ if not (
1082
+ isinstance(target, ast.Attribute)
1083
+ and isinstance(target.value, ast.Name)
1084
+ and target.value.id == "c"
1085
+ ):
1086
+ self._error(dec, "unknown decorator on a function", code="unsupported")
1087
+ name = target.attr
1088
+ if name in ("extern_function", "export", "inline"):
1089
+ if name == "inline":
1090
+ is_inline = True
1091
+ continue
1092
+ if name == "section":
1093
+ if section:
1094
+ self._error(dec, "duplicate @c.section decorator", code="unsupported")
1095
+ if call is None or len(call.args) != 1:
1096
+ self._error(
1097
+ dec,
1098
+ "@c.section requires exactly one section name: @c.section(\".ramfunc\")",
1099
+ code="unsupported",
1100
+ )
1101
+ arg = call.args[0]
1102
+ if not (isinstance(arg, ast.Constant) and isinstance(arg.value, str)):
1103
+ self._error(dec, "@c.section name must be a string literal", code="unsupported")
1104
+ if not _SECTION_NAME_RE.match(arg.value):
1105
+ self._error(
1106
+ dec,
1107
+ "@c.section name contains unsupported characters; "
1108
+ "use letters, digits, '_', '.', '$' or '-'",
1109
+ code="unsupported",
1110
+ )
1111
+ section = arg.value
1112
+ continue
1113
+ if name == "weak":
1114
+ if is_weak:
1115
+ self._error(dec, "duplicate @c.weak decorator", code="unsupported")
1116
+ if call is not None:
1117
+ self._error(dec, "@c.weak does not take arguments", code="unsupported")
1118
+ is_weak = True
1119
+ continue
1120
+ if name == "aligned":
1121
+ if align:
1122
+ self._error(dec, "duplicate @c.aligned decorator", code="unsupported")
1123
+ if call is None or len(call.args) != 1:
1124
+ self._error(dec, "@c.aligned requires exactly one integer width: @c.aligned(16)", code="unsupported")
1125
+ arg = call.args[0]
1126
+ if not (
1127
+ isinstance(arg, ast.Constant)
1128
+ and isinstance(arg.value, int)
1129
+ and not isinstance(arg.value, bool)
1130
+ and arg.value > 0
1131
+ ):
1132
+ self._error(dec, "@c.aligned width must be a positive integer literal", code="unsupported")
1133
+ if arg.value & (arg.value - 1) != 0:
1134
+ self._error(dec, "@c.aligned width must be a power of two", code="unsupported")
1135
+ align = arg.value
1136
+ continue
1137
+ if name == "visibility":
1138
+ if visibility:
1139
+ self._error(dec, "duplicate @c.visibility decorator", code="unsupported")
1140
+ if call is None or len(call.args) != 1:
1141
+ self._error(dec, "@c.visibility requires exactly one string: @c.visibility(\"hidden\")", code="unsupported")
1142
+ arg = call.args[0]
1143
+ if not (
1144
+ isinstance(arg, ast.Constant)
1145
+ and isinstance(arg.value, str)
1146
+ and arg.value in ("hidden", "default", "protected")
1147
+ ):
1148
+ self._error(dec, "@c.visibility name must be 'hidden', 'default' or 'protected'", code="unsupported")
1149
+ visibility = arg.value
1150
+ continue
1151
+ self._error(dec, f"unknown decorator @c.{name} on a function", code="unsupported")
1152
+ return is_inline, section, is_weak, align, visibility
1153
+
1154
+ def _validate_layout(self, stmt: ast.ClassDef, struct: T.Struct) -> None:
1155
+ """Bit-field layout validation: the total width is written only once; the storage type and trailing padding are computed by the compiler."""
1156
+ widths: List[int] = [
1157
+ r.width
1158
+ for ftype in struct.fields.values()
1159
+ for r in [T.resolve(ftype)]
1160
+ if isinstance(r, T.Bits)
1161
+ ]
1162
+ if not widths and not struct.word_bits:
1163
+ return
1164
+ if widths and not struct.word_bits:
1165
+ self._error(
1166
+ stmt,
1167
+ f"{stmt.name} has Bits[N] fields; declare the total width once with @c.word(W)",
1168
+ code="type",
1169
+ )
1170
+ if struct.word_bits and len(widths) != len(struct.fields):
1171
+ self._error(
1172
+ stmt,
1173
+ f"@c.word({struct.word_bits}) requires every field of {stmt.name} to be Bits[N]",
1174
+ code="type",
1175
+ )
1176
+ # Union members share the same storage; the bit count takes the widest member; struct accumulates them.
1177
+ used = max(widths) if struct.is_union else sum(widths)
1178
+ if used > struct.word_bits:
1179
+ self._error(
1180
+ stmt,
1181
+ f"{stmt.name} bit fields use {used} bits but "
1182
+ f"@c.word({struct.word_bits}) declares {struct.word_bits}",
1183
+ code="type",
1184
+ )
1185
+ # The backing integer type is uniquely determined by the total width; the user does not write the storage type.
1186
+ ctype = f"uint{struct.word_bits}_t"
1187
+ for fname, ftype in struct.fields.items():
1188
+ r = T.resolve(ftype)
1189
+ if isinstance(r, T.Bits):
1190
+ struct.fields[fname] = replace(
1191
+ r,
1192
+ ctype=ctype,
1193
+ bits=struct.word_bits,
1194
+ signed=False,
1195
+ category="int",
1196
+ storage_bits=struct.word_bits,
1197
+ )
1198
+
1199
+ def _resolve_enum_members(self, stmt: ast.ClassDef, enum: T.Enum) -> None:
1200
+ """Parse the value of an enum member.
1201
+
1202
+ The member value must be an integer literal or auto() (auto-increment).
1203
+ """
1204
+ next_value = 0
1205
+ for item in stmt.body:
1206
+ if (
1207
+ isinstance(item, ast.Expr)
1208
+ and isinstance(item.value, ast.Constant)
1209
+ and isinstance(item.value.value, str)
1210
+ ):
1211
+ continue # docstring
1212
+ assert isinstance(item, ast.Assign)
1213
+ mname = item.targets[0].id
1214
+ if mname in enum.members:
1215
+ self._error(item, f"enum {enum.name} member {mname} is already defined", code="name")
1216
+ value = self._enum_member_value(item.value, next_value)
1217
+ enum.members[mname] = value
1218
+ next_value = value + 1
1219
+
1220
+ def _enum_member_value(self, node: ast.AST, next_value: int) -> int:
1221
+ """Compute an enum member's value: an integer literal or auto()."""""
1222
+ if isinstance(node, ast.Constant) and isinstance(node.value, int) \
1223
+ and not isinstance(node.value, bool):
1224
+ return node.value
1225
+ # auto(): automatically take the next available value
1226
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) \
1227
+ and node.func.id == "auto":
1228
+ return next_value
1229
+ self._error(
1230
+ node,
1231
+ "enum member value must be an integer literal or auto()",
1232
+ code="unsupported",
1233
+ )
1234
+ return 0
1235
+
1236
+ def _collect_locals(self, func: ast.FunctionDef) -> List[str]:
1237
+ names: List[str] = []
1238
+
1239
+ class Collector(ast.NodeVisitor):
1240
+ def visit_FunctionDef(inner, node: ast.FunctionDef) -> None:
1241
+ if node is not func:
1242
+ return # nested functions were already rejected at the gate; nothing to do here
1243
+ for stmt in node.body:
1244
+ inner.visit(stmt)
1245
+
1246
+ def visit_Assign(inner, node: ast.Assign) -> None:
1247
+ for target in node.targets:
1248
+ if isinstance(target, ast.Name):
1249
+ names.append(target.id)
1250
+ inner.visit(node.value)
1251
+
1252
+ def visit_AnnAssign(inner, node: ast.AnnAssign) -> None:
1253
+ if isinstance(node.target, ast.Name):
1254
+ names.append(node.target.id)
1255
+ if node.value is not None:
1256
+ inner.visit(node.value)
1257
+
1258
+ def visit_AugAssign(inner, node: ast.AugAssign) -> None:
1259
+ if isinstance(node.target, ast.Name):
1260
+ names.append(node.target.id)
1261
+ inner.visit(node.value)
1262
+
1263
+ def visit_For(inner, node: ast.For) -> None:
1264
+ if isinstance(node.target, ast.Name):
1265
+ names.append(node.target.id)
1266
+ inner.visit(node.iter)
1267
+ for stmt in node.body:
1268
+ inner.visit(stmt)
1269
+
1270
+ def visit_If(inner, node: ast.If) -> None:
1271
+ inner.visit(node.test)
1272
+ for stmt in node.body:
1273
+ inner.visit(stmt)
1274
+ for stmt in node.orelse:
1275
+ inner.visit(stmt)
1276
+
1277
+ def visit_While(inner, node: ast.While) -> None:
1278
+ inner.visit(node.test)
1279
+ for stmt in node.body:
1280
+ inner.visit(stmt)
1281
+
1282
+ def generic_visit(inner, node: ast.AST) -> None:
1283
+ for child in ast.iter_child_nodes(node):
1284
+ inner.visit(child)
1285
+
1286
+ Collector().visit(func)
1287
+ return names
1288
+
1289
+ def _resolve_annotation(self, node: ast.AST, allow_bits: bool = False) -> T.Type:
1290
+ if isinstance(node, ast.Constant) and node.value is None:
1291
+ # None is Python's "empty value", not "no value"; C's no-value is void.
1292
+ self._error(
1293
+ node,
1294
+ "None is not a type in this language; use 'void' for C's void "
1295
+ "(from embeddedpy.types import void)",
1296
+ code="type",
1297
+ )
1298
+ if isinstance(node, ast.Name):
1299
+ if node.id in self._section_bindings:
1300
+ self._error(
1301
+ node,
1302
+ f"section descriptor {node.id} may only be used as a type "
1303
+ f"qualifier: {node.id}[T]",
1304
+ code="unsupported",
1305
+ )
1306
+ # Type names have a single source: import. The built-in type list has been cleared,
1307
+ # so every type here must first be imported via from embeddedpy.<category> import.
1308
+ sym = self.scope.get(node.id)
1309
+ if sym is not None and sym.kind == "type":
1310
+ assert sym.type is not None
1311
+ return sym.type
1312
+ # Pointer type alias: int32_ptr = Ptr[int32] -> p: int32_ptr
1313
+ if sym is not None and sym.kind == "ptr_alias":
1314
+ assert sym.type is not None
1315
+ return T.Ptr(sym.type.target)
1316
+ if sym is not None and sym.kind in QUALIFIER_KINDS:
1317
+ disp = QUALIFIER_DISPLAY.get(sym.kind, QUALIFIER_KINDS[sym.kind])
1318
+ self._error(
1319
+ node,
1320
+ f"{disp} must be written as {disp}[T]",
1321
+ )
1322
+ self._error(node, self._type_name_error(node.id))
1323
+ if isinstance(node, ast.Attribute):
1324
+ target = self._member_type(node)
1325
+ if target is not None:
1326
+ return target
1327
+ self._error(node, "unknown type annotation")
1328
+ if isinstance(node, ast.Subscript):
1329
+ # Generic type annotations: Ptr[T] / Array[T] / Func[[...], R]
1330
+ if isinstance(node.value, ast.Name):
1331
+ sym = self.scope.get(node.value.id)
1332
+ if sym is not None and sym.kind == "ptr_type":
1333
+ inner = self._resolve_annotation(node.slice)
1334
+ return T.Ptr(inner)
1335
+ if sym is not None and sym.kind == "array_type":
1336
+ # Array[T]: fixed-width array (length inferred/specified outside the type)
1337
+ inner = self._resolve_annotation(node.slice)
1338
+ return T.Array(inner, -1)
1339
+ if sym is not None and sym.kind == "func_type":
1340
+ # Func[[...], R] is itself a function pointer; internally the compiler still stores it as Ptr(Func)
1341
+ return T.Ptr(self._resolve_func_annotation(node))
1342
+ if sym is not None and sym.kind == "bits_type":
1343
+ # Bits[N] is only a field-level bit-width declaration, not a complete C object type.
1344
+ if not allow_bits:
1345
+ self._error(
1346
+ node,
1347
+ "Bits[N] is only allowed as a struct or union field type",
1348
+ code="type",
1349
+ )
1350
+ width_node = node.slice
1351
+ if not (
1352
+ isinstance(width_node, ast.Constant)
1353
+ and isinstance(width_node.value, int)
1354
+ and not isinstance(width_node.value, bool)
1355
+ ):
1356
+ self._error(node, "Bits[N] width must be an integer literal", code="type")
1357
+ width = width_node.value
1358
+ if not 1 <= width <= 64:
1359
+ self._error(node, "Bits[N] width must be between 1 and 64", code="type")
1360
+ # The backing integer type here is only a placeholder; @c.word(W) validation replaces it by total width.
1361
+ storage = 8 if width <= 8 else 16 if width <= 16 else 32 if width <= 32 else 64
1362
+ return T.Bits(
1363
+ name=f"Bits[{width}]",
1364
+ ctype=f"uint{storage}_t",
1365
+ bits=storage,
1366
+ signed=False,
1367
+ category="int",
1368
+ width=width,
1369
+ storage_bits=storage,
1370
+ )
1371
+ if sym is None:
1372
+ self._error(
1373
+ node,
1374
+ type_import_hint(node.value.id),
1375
+ code="import",
1376
+ )
1377
+ self._error(
1378
+ node,
1379
+ "only Ptr[T], Array[T], Bits[N] and Func[[...], R] "
1380
+ "subscript type annotations are supported",
1381
+ )
1382
+ self._error(node, "only scalar type annotations are supported")
1383
+
1384
+ def _section_descriptor(self, node: ast.AST) -> "Optional[str]":
1385
+ """Return the segment name when the node is a registered segment-descriptor name."""
1386
+ if isinstance(node, ast.Name):
1387
+ return self._section_bindings.get(node.id)
1388
+ return None
1389
+
1390
+ def _has_section_wrapper(self, node: ast.AST) -> bool:
1391
+ """Whether a segment descriptor appears in the annotation (used to reject non-global-variable positions like parameters / fields)."""
1392
+ return any(
1393
+ isinstance(n, ast.Name) and n.id in self._section_bindings
1394
+ for n in ast.walk(node)
1395
+ )
1396
+
1397
+ def _annotation_section(self, node: ast.AST) -> str:
1398
+ """Get the segment name of the outermost ``desc[T]`` in the annotation, or an empty string if none.
1399
+
1400
+ Segment-name validity was already validated where ``desc = c.section("...")`` is bound; here we only look it up.
1401
+ """
1402
+ if not isinstance(node, ast.Subscript):
1403
+ return ""
1404
+ return self._section_descriptor(node.value) or ""
1405
+
1406
+ def _resolve_annotated(self, node: ast.AST) -> Tuple[T.Type, List[str]]:
1407
+ """Parse a type annotation, returning (type, modifier_list).
1408
+
1409
+ Supports modifier forms like const[T] / volatile[T],
1410
+ corresponding to C's `const int32_t x;` / `volatile int32_t x;`.
1411
+ The segment descriptor in ``desc[T]`` only affects where the output lands and does not change the type, so it is simply stripped.
1412
+ """
1413
+ if isinstance(node, ast.Subscript) and self._section_descriptor(node.value):
1414
+ return self._resolve_annotated(node.slice)
1415
+ if isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name):
1416
+ sym = self.scope.get(node.value.id)
1417
+ if sym is not None and sym.kind in QUALIFIER_KINDS:
1418
+ inner, inner_quals = self._resolve_annotated(node.slice)
1419
+ qual = QUALIFIER_KINDS[sym.kind]
1420
+ return inner, [qual] + inner_quals
1421
+ return self._resolve_annotation(node), []
1422
+
1423
+ def _resolve_func_annotation(self, node: ast.Subscript) -> T.Type:
1424
+ """Parse Func[[param_types...], return_type] into T.Func.
1425
+
1426
+ The caller decides whether to wrap it in Ptr:
1427
+ - bare ``Func[[...], R]`` → ``T.Ptr(T.Func(...))`` (it is itself a function pointer)
1428
+ - ``Ptr[Func[[...], R]]`` → ``T.Ptr(T.Ptr(T.Func(...)))`` (pointer to function pointer)
1429
+ """
1430
+ sl = node.slice
1431
+ if not isinstance(sl, ast.Tuple) or len(sl.elts) != 2:
1432
+ self._error(node, "Func must be used as Func[[argtypes...], rettype]")
1433
+ return T.Func((), T.TVar())
1434
+ arg_list, ret_node = sl.elts
1435
+ if not isinstance(arg_list, ast.List):
1436
+ self._error(node, "Func argument types must be a list: Func[[...], ret]")
1437
+ return T.Func((), T.TVar())
1438
+ args = tuple(self._resolve_annotation(a) for a in arg_list.elts)
1439
+ ret = self._resolve_annotation(ret_node)
1440
+ return T.Func(args, ret)
1441
+
1442
+ def _merge_quals(self, old: List[str], new: List[str]) -> List[str]:
1443
+ """Merge modifiers, preserving order and avoiding duplicates."""
1444
+ merged = list(old)
1445
+ for q in new:
1446
+ if q not in merged:
1447
+ merged.append(q)
1448
+ return merged
1449
+
1450
+ def _type_name_error(self, name: str) -> str:
1451
+ """Error text when a type name is unavailable; for valid but unimported names, give an import suggestion."""
1452
+ return type_import_hint(name)
1453
+
1454
+ def _member_path(self, node: ast.AST) -> Optional[str]:
1455
+ if isinstance(node, ast.Name):
1456
+ sym = self.scope.get(node.id)
1457
+ if sym is not None and sym.kind == "module":
1458
+ return sym.module_path
1459
+ return None
1460
+ if isinstance(node, ast.Attribute):
1461
+ base = self._member_path(node.value)
1462
+ if base is None:
1463
+ return None
1464
+ return f"{base}.{node.attr}"
1465
+ return None
1466
+
1467
+ def _member_type(self, node: ast.Attribute) -> Optional[T.Scalar]:
1468
+ path = self._member_path(node)
1469
+ if path is None:
1470
+ return None
1471
+ return TYPE_PATH_MAP.get(path)
1472
+
1473
+ def _enum_member_type(self, node: ast.Attribute) -> Optional[T.Type]:
1474
+ """Enum member access Mode.RUN: return the integer value of that member.
1475
+
1476
+ Enum values are determined at compile time, so they are represented with ConstInt,
1477
+ and can directly participate in constant expressions (e.g. make_array(T, N)).
1478
+ """
1479
+ base = node.value
1480
+ if not isinstance(base, ast.Name):
1481
+ return None
1482
+ sym = self.scope.get(base.id)
1483
+ if sym is None or sym.kind != "type" or sym.type is None:
1484
+ return None
1485
+ enum = T.resolve(sym.type)
1486
+ if not isinstance(enum, T.Enum):
1487
+ return None
1488
+ if node.attr not in enum.members:
1489
+ self._error(node, f"enum {enum.name} has no member {node.attr}")
1490
+ # Record the ownership, for use when comparing to detect "mixing two different enums"
1491
+ node._enum_owner = enum
1492
+ return T.ConstInt(enum.members[node.attr])
1493
+
1494
+ def _lookup(self, name: str) -> Optional[Symbol]:
1495
+ if self.func is not None and name in self.func.locals:
1496
+ return self.func.locals[name]
1497
+ sym = self.scope.get(name)
1498
+ if sym is not None:
1499
+ return sym
1500
+ return self.builtins.get(name)
1501
+
1502
+ def _target_symbol(
1503
+ self, target: ast.Name, allow_const: bool = False, check_const: bool = True
1504
+ ) -> Symbol:
1505
+ sym = self._lookup(target.id)
1506
+ if sym is None:
1507
+ self._error(target, undefined_name_message(target.id), code="name")
1508
+ assert sym is not None
1509
+ if check_const and not allow_const and "const" in sym.quals:
1510
+ self._error(target, f"{sym.name} is a const variable and cannot be assigned")
1511
+ if sym.kind not in ("local", "param", "global", "ptr_alias"):
1512
+ self._error(target, f"{target.id} cannot be assigned to", code="name")
1513
+ return sym
1514
+
1515
+ def _is_len_param(self, node: ast.AST) -> bool:
1516
+ """Array parameter: the length is passed by the caller as <name>_len and is known at runtime."""
1517
+ if not isinstance(node, ast.Name):
1518
+ return False
1519
+ sym = getattr(node, "_symbol", None)
1520
+ if sym is None or sym.kind != "param" or sym.type is None:
1521
+ return False
1522
+ return isinstance(T.resolve(sym.type), T.Array)
1523
+
1524
+ def _bind(self, sym: Symbol, typ: T.Type, node: ast.AST, context: str = "") -> None:
1525
+ current = T.resolve(sym.type)
1526
+ assert sym.type is not None
1527
+ if isinstance(current, T.TVar):
1528
+ sym.type = T.unify(sym.type, typ)
1529
+ if T.is_void(T.resolve(sym.type)):
1530
+ self._error(node, f"{context}cannot assign void to {sym.name}")
1531
+ return
1532
+ try:
1533
+ unified = T.unify(sym.type, typ)
1534
+ except T.TypesMismatch as exc:
1535
+ self._error(node, f"{context}{sym.name}: {exc}")
1536
+ if T.is_void(T.resolve(unified)):
1537
+ self._error(node, f"{context}cannot assign void to {sym.name}")
1538
+ # The length of an array annotation array[T] is unknown (-1) and is filled in with the actual length on first assignment
1539
+ if isinstance(current, T.Array) and current.length < 0:
1540
+ resolved = T.resolve(unified)
1541
+ if isinstance(resolved, T.Array) and resolved.length >= 0:
1542
+ sym.type = resolved
1543
+ return
1544
+ if not T.same(unified, current):
1545
+ self._error(
1546
+ node,
1547
+ f"{context}{sym.name} has type {T.describe(current)}, "
1548
+ f"which cannot be assigned a value of type {T.describe(unified)}",
1549
+ )
1550
+
1551
+ def _type_function(self, fi: FuncInfo) -> None:
1552
+ self.func = fi
1553
+ for stmt in fi.node.body:
1554
+ if self._is_docstring(stmt):
1555
+ continue
1556
+ self._type_stmt(stmt)
1557
+ self.func = None
1558
+
1559
+ @staticmethod
1560
+ def _extern_has_mock_body(fi: FuncInfo) -> bool:
1561
+ """If an extern function body has statements besides docstring / pass, it is a CPython-track mock."""
1562
+ body = [
1563
+ stmt
1564
+ for stmt in fi.node.body
1565
+ if not isinstance(stmt, ast.Pass)
1566
+ and not (
1567
+ isinstance(stmt, ast.Expr)
1568
+ and isinstance(stmt.value, ast.Constant)
1569
+ and isinstance(stmt.value.value, str)
1570
+ )
1571
+ ]
1572
+ return bool(body)
1573
+
1574
+ def _finish_function(self, fi: FuncInfo) -> None:
1575
+ ret = T.resolve(fi.ret)
1576
+ if fi.is_extern and not self._extern_has_mock_body(fi):
1577
+ # Pure declaration: the implementation is provided by an external library on the C side, so no return statement is required
1578
+ return
1579
+ if not T.is_void(ret) and not fi.has_value_return and not self._header_mode:
1580
+ self._error(
1581
+ fi.node,
1582
+ f"function {fi.name} is declared to return {T.describe(ret)} but has no return value",
1583
+ code="missing-return",
1584
+ )
1585
+
1586
+ def _reject_extern_type_field(self, node: ast.AST, st: T.Struct, field: str) -> None:
1587
+ """External types have no field table: field read/write must be rejected at compile time to avoid dual-track divergence.
1588
+
1589
+ c.extern_type only registers a name; the CPython track cannot access the field layout from the header;
1590
+ allowing field access would make the same code produce different results on the two tracks.
1591
+ """
1592
+ if isinstance(st, T.ExternType):
1593
+ self._error(
1594
+ node,
1595
+ f"external type {st.c_name!r} has no field table in embeddedpy; "
1596
+ f"field {field!r} cannot be accessed (use an extern getter instead)",
1597
+ code="unsupported",
1598
+ )
1599
+
1600
+ @staticmethod
1601
+ def _is_aggregate_alias_rhs(value: ast.AST, vt: T.Type) -> bool:
1602
+ """In an aggregate-type assignment, whether the RHS is "a reference to an already-existing object".
1603
+
1604
+ Construction of new values (list literal, struct construction, make_array, copy_aggregate) is allowed;
1605
+ directly binding an existing array/struct variable, field, element, or function-returned aggregate to another
1606
+ name is equivalent to creating a second reference and is rejected at compile time.
1607
+ """
1608
+ r = T.resolve(vt)
1609
+ if not isinstance(r, (T.Struct, T.Array)):
1610
+ return False
1611
+ # List literals and any call (construction, make_array, copy_aggregate, function return)
1612
+ # all produce new values; only an expression that explicitly references an existing object creates a second reference.
1613
+ if isinstance(value, (ast.List, ast.Call)):
1614
+ return False
1615
+ return True
1616
+
1617
+ def _reject_aggregate_alias(self, target: ast.expr, value: ast.AST, vt: T.Type) -> None:
1618
+ """Aggregate-type binding: arrays of unknown length, and references to already-existing objects, are rejected at compile time."""
1619
+ r = T.resolve(vt)
1620
+ if isinstance(r, T.Array) and r.length < 0:
1621
+ self._error(
1622
+ target,
1623
+ "array length cannot be determined for this binding; "
1624
+ "use a literal or make_array(T, N)",
1625
+ )
1626
+ return
1627
+ if self._is_aggregate_alias_rhs(value, vt):
1628
+ self._error(
1629
+ target,
1630
+ "cannot assign an aggregate by reference; use copy_aggregate(value) "
1631
+ "for an independent copy or construct a new value",
1632
+ )
1633
+
1634
+ def _reject_aggregate_slot(self, target: ast.expr, value_type: T.Type) -> None:
1635
+ """Writing a whole aggregate type into an array element / struct field degrades into a value copy on the C side, breaking aliasing semantics, so it is rejected at compile time."""
1636
+ r = T.resolve(value_type)
1637
+ if isinstance(r, (T.Struct, T.Array)):
1638
+ self._error(
1639
+ target,
1640
+ "cannot assign an aggregate as a whole "
1641
+ "to a field or element; assign individual fields or elements instead",
1642
+ )
1643
+
1644
+ def _type_stmt(self, stmt: ast.stmt) -> None:
1645
+ if isinstance(stmt, ast.Assign):
1646
+ target = stmt.targets[0]
1647
+ if isinstance(target, ast.Name):
1648
+ alias = self._try_type_alias(stmt, target)
1649
+ if alias is not None:
1650
+ return
1651
+ # A type alias cannot be overwritten by an ordinary value
1652
+ existing = self._lookup(target.id)
1653
+ if existing is not None and existing.kind == "ptr_alias":
1654
+ self._error(
1655
+ target,
1656
+ f"{target.id} is a type alias and can only be defined with "
1657
+ f"c.typedef(Ptr[T]) or c.typedef(Func[[...], R]); "
1658
+ f"it cannot be reassigned",
1659
+ )
1660
+ return
1661
+ if isinstance(target, ast.Attribute):
1662
+ vt = self._type_expr(stmt.value)
1663
+ self._reject_aggregate_slot(target, vt)
1664
+ ot = T.resolve(self._type_expr(target.value))
1665
+ # The target of a field assignment can be a struct value or a pointer base (p->f = v)
1666
+ acc = T.struct_field_access(ot)
1667
+ if acc is None:
1668
+ self._error(target, "can only assign to struct fields")
1669
+ st, _levels = acc
1670
+ self._reject_extern_type_field(target, st, target.attr)
1671
+ if target.attr not in st.fields:
1672
+ self._error(target, f"struct {st.name} has no field {target.attr}")
1673
+ try:
1674
+ T.unify(st.fields[target.attr], vt)
1675
+ except T.TypesMismatch as exc:
1676
+ self._error(stmt, str(exc))
1677
+ return
1678
+ if isinstance(target, ast.Subscript):
1679
+ vt = self._type_expr(stmt.value)
1680
+ self._reject_aggregate_slot(target, vt)
1681
+ bt = T.resolve(self._type_expr(target.value))
1682
+ # Subscript assignment requires a fixed-length array.
1683
+ if isinstance(bt, T.Ptr):
1684
+ self._error(
1685
+ target,
1686
+ "pointers do not support subscripting; write a value with "
1687
+ "ptr.poke(p, v)",
1688
+ )
1689
+ return
1690
+ if not isinstance(bt, T.Array):
1691
+ self._error(target, "subscript-assignment target must be a fixed-length array")
1692
+ return
1693
+ self._type_expr(target.slice)
1694
+ try:
1695
+ T.unify(bt.element, vt)
1696
+ except T.TypesMismatch as exc:
1697
+ self._error(stmt, str(exc))
1698
+ return
1699
+ sym = self._target_symbol(target)
1700
+ if sym.static_object:
1701
+ self._error(
1702
+ stmt,
1703
+ f"{sym.name} is a static C object and cannot be reassigned; "
1704
+ "write the initializer in its declaration",
1705
+ code="unsupported",
1706
+ )
1707
+ sym.declared = True
1708
+ vt = self._type_expr(stmt.value)
1709
+ ch = self._char_from_str(sym.type, stmt.value)
1710
+ if ch is not None:
1711
+ vt = ch
1712
+ self._reject_aggregate_alias(target, stmt.value, vt)
1713
+ self._bind(sym, vt, stmt)
1714
+ return
1715
+ if isinstance(stmt, ast.AnnAssign):
1716
+ target = stmt.target
1717
+ assert isinstance(target, ast.Name)
1718
+ sym = self._target_symbol(target, check_const=False)
1719
+ section = self._annotation_section(stmt.annotation)
1720
+ if section or self._has_section_wrapper(stmt.annotation):
1721
+ if self.func is not None or sym.kind != "global":
1722
+ self._error(
1723
+ stmt,
1724
+ "section descriptor qualifier is only supported on module-level variables",
1725
+ code="unsupported",
1726
+ )
1727
+ sym.section = section
1728
+ if sym.kind == "global" and (section or stmt.value is None):
1729
+ sym.static_object = True
1730
+ ann, quals = self._resolve_annotated(stmt.annotation)
1731
+ current = T.resolve(sym.type)
1732
+ if sym.declared:
1733
+ # Repeated annotation = repeated declaration: each variable may be declared only once (use plain rebind without ': type')
1734
+ self._error(
1735
+ target,
1736
+ f"name '{target.id}' is redeclared; each variable may be declared only once "
1737
+ f"(use assignment without ': type' to rebind)",
1738
+ )
1739
+ sym.declared = True
1740
+ sym.quals = self._merge_quals(sym.quals, quals)
1741
+ if "const" in sym.quals:
1742
+ if stmt.value is None:
1743
+ self._error(stmt, "const variable requires an initializer")
1744
+ # A const variable's value is known at compile time and may participate in constant expressions
1745
+ self._record_const_value(sym, stmt.value)
1746
+ assert sym.type is not None
1747
+ if isinstance(current, T.TVar):
1748
+ sym.type = ann
1749
+ elif not T.same(current, ann):
1750
+ self._error(
1751
+ target,
1752
+ f"annotation of {target.id} is {T.describe(ann)}, "
1753
+ f"but it was previously inferred as {T.describe(current)}",
1754
+ )
1755
+ if stmt.value is None:
1756
+ # Pure declaration: type is determined; the output emits a static object in the file header and main assigns nothing
1757
+ return
1758
+ vt = self._type_annotated_value(stmt.value, ann)
1759
+ ch = self._char_from_str(ann, stmt.value)
1760
+ if ch is not None:
1761
+ vt = ch
1762
+ self._reject_aggregate_alias(target, stmt.value, vt)
1763
+ self._bind(sym, vt, stmt)
1764
+ return
1765
+ if isinstance(stmt, ast.AugAssign):
1766
+ target = stmt.target
1767
+ rt = self._type_expr(stmt.value)
1768
+ if isinstance(target, ast.Subscript):
1769
+ bt = T.resolve(self._type_expr(target.value))
1770
+ # Subscript augmented assignment requires a fixed-length array.
1771
+ if isinstance(bt, T.Ptr):
1772
+ self._error(
1773
+ target,
1774
+ "pointers do not support subscripting; write a value with "
1775
+ "ptr.poke(p, v)",
1776
+ )
1777
+ return
1778
+ if not isinstance(bt, T.Array):
1779
+ self._error(target, "subscript augmented-assignment target must be a fixed-length array")
1780
+ return
1781
+ self._type_expr(target.slice)
1782
+ try:
1783
+ T.unify(bt.element, rt)
1784
+ except T.TypesMismatch as exc:
1785
+ self._error(stmt, str(exc))
1786
+ return
1787
+ assert isinstance(target, ast.Name)
1788
+ sym = self._target_symbol(target)
1789
+ current = T.resolve(sym.type)
1790
+ if isinstance(current, T.Ptr):
1791
+ if not isinstance(stmt.op, (ast.Add, ast.Sub)):
1792
+ self._error(stmt, "pointers only support += and -=")
1793
+ if not T.is_int(rt):
1794
+ self._error(stmt, "pointer offset must be an integer")
1795
+ return
1796
+ if isinstance(current, (T.TVar, T.ConstInt, T.ConstFloat)):
1797
+ self._error(target, f"variable {target.id} has not been type-inferred before use")
1798
+ try:
1799
+ T.unify(current, rt)
1800
+ except T.TypesMismatch as exc:
1801
+ self._error(stmt, str(exc))
1802
+ return
1803
+ if isinstance(stmt, ast.Expr):
1804
+ if isinstance(stmt.value, ast.Call):
1805
+ if getattr(stmt, "_pp_block_decl", False):
1806
+ # A named declaration inside a conditional block is compile-time text: it does not enter the type system and is not registered into
1807
+ # the macro region: a same-named #define across different #if branches is legal in C.
1808
+ call = stmt.value
1809
+ _, err = pp.render_decl_directive(call)
1810
+ if err is not None:
1811
+ self._error(call, err)
1812
+ if pp.pp_decl_member_name(call) == "define":
1813
+ self._check_macro_name(call.args[0], call.args[0].value)
1814
+ stmt._pp_directive = True
1815
+ return
1816
+ if self._is_c_include_call(stmt.value):
1817
+ return # c.include is already handled in _collect_includes
1818
+ if pp.is_pp_directive_call(stmt.value):
1819
+ # A preprocessor directive is compile-time text and does not enter the type system; arguments are validated when rendering
1820
+ _, err = pp.render_directive(stmt.value)
1821
+ if err is not None:
1822
+ self._error(stmt.value, err)
1823
+ stmt._pp_directive = True
1824
+ return
1825
+ reg = self._c_registration_call_name(stmt.value)
1826
+ if reg is not None:
1827
+ # A registration call must be written on the right-hand side of an assignment; as a standalone statement it is meaningless
1828
+ self._error(
1829
+ stmt.value,
1830
+ f"c.{reg} must be assigned to a name "
1831
+ f"(e.g. X = c.{reg}(...)); it is a compile-time "
1832
+ f"registration and has no effect as a statement",
1833
+ )
1834
+ return
1835
+ # Statement-level builtin: no return value, standalone statement, emits one line of C (e.g. c.barrier())
1836
+ c_stmt = self._c_stmt_api_name(stmt.value)
1837
+ if c_stmt is not None:
1838
+ call = stmt.value
1839
+ if call.args or call.keywords:
1840
+ self._error(
1841
+ call,
1842
+ f"c.{c_stmt}() takes no arguments",
1843
+ )
1844
+ call._c_stmt = c_stmt
1845
+ return
1846
+ self._type_expr(stmt.value)
1847
+ return
1848
+ if isinstance(stmt, ast.Return):
1849
+ if self.func is None:
1850
+ self._error(stmt, "'return' is only allowed inside functions")
1851
+ assert self.func is not None
1852
+ if stmt.value is None:
1853
+ # Bare return (no value). This language has no None (rule 9):
1854
+ # - return type is void -> legal (C's return;, meaning "return nothing")
1855
+ # - return type is a value type -> error: cannot "return nothing at all";
1856
+ # either change the return type to void, or return a value
1857
+ if not T.is_void(self.func.ret):
1858
+ self._error(
1859
+ stmt,
1860
+ "a function with a return type must return a value; "
1861
+ "use 'void' as the return type to allow a bare 'return', "
1862
+ "or return an actual value",
1863
+ )
1864
+ return
1865
+ rt: T.Type = T.VOID
1866
+ else:
1867
+ rt = self._type_expr(stmt.value)
1868
+ ch = self._char_from_str(self.func.ret, stmt.value)
1869
+ if ch is not None:
1870
+ # A literal passed to a char-typed parameter: take that byte (_char_from_str has already tagged the node)
1871
+ rt = ch
1872
+ self.func.has_value_return = True
1873
+ try:
1874
+ T.unify(self.func.ret, rt)
1875
+ except T.TypesMismatch as exc:
1876
+ self._error(stmt, f"return type mismatch: {exc}")
1877
+ return
1878
+ if isinstance(stmt, ast.If):
1879
+ has_pp = any(
1880
+ isinstance(n, ast.Call)
1881
+ and pp.pp_member_name(n) in pp.PP_COND_FUNCS
1882
+ for n in ast.walk(stmt.test)
1883
+ )
1884
+ if has_pp:
1885
+ # Compile-time condition: translated to #if; the condition expression does not enter the runtime type system.
1886
+ # An elif is a nested If inside orelse in the AST and gets tagged the same way during recursion.
1887
+ err = pp.validate_cond(stmt.test)
1888
+ if err is not None:
1889
+ self._error(stmt.test, err)
1890
+ stmt._pp_if = True
1891
+ else:
1892
+ self._type_expr(stmt.test)
1893
+ for s in stmt.body:
1894
+ self._type_stmt(s)
1895
+ for s in stmt.orelse:
1896
+ self._type_stmt(s)
1897
+ return
1898
+ if isinstance(stmt, ast.While):
1899
+ self._type_expr(stmt.test)
1900
+ for s in stmt.body:
1901
+ self._type_stmt(s)
1902
+ return
1903
+ if isinstance(stmt, ast.For):
1904
+ it = stmt.iter
1905
+ if isinstance(it, ast.Call):
1906
+ is_range = isinstance(it.func, ast.Name) and it.func.id == "range"
1907
+ for index, a in enumerate(it.args):
1908
+ if not (is_range and self._fold_range_arg(a, index)):
1909
+ self._type_expr(a)
1910
+ sym = self._target_symbol(stmt.target)
1911
+ self._bind(sym, T.I64, stmt.target)
1912
+ for s in stmt.body:
1913
+ self._type_stmt(s)
1914
+ return
1915
+ # Fixed-length array iteration
1916
+ it_t = T.resolve(self._type_expr(it))
1917
+ if not isinstance(it_t, T.Array):
1918
+ self._error(it, "for loops only support range(...) or fixed-length array iteration")
1919
+ sym = self._target_symbol(stmt.target)
1920
+ self._bind(sym, it_t.element, stmt.target)
1921
+ for s in stmt.body:
1922
+ self._type_stmt(s)
1923
+ return
1924
+ if isinstance(stmt, (ast.Break, ast.Continue, ast.Pass)):
1925
+ return
1926
+ if isinstance(stmt, (ast.Import, ast.ImportFrom, ast.FunctionDef)):
1927
+ return
1928
+ self._error(stmt, f"statement {type(stmt).__name__} is not supported")
1929
+
1930
+ def _func_type_of(self, fi) -> T.Func:
1931
+ """Build the Func part of a function pointer type from a FuncInfo."""
1932
+ param_types = [fi.locals[p].type for p in fi.params]
1933
+ return T.Func(tuple(param_types), fi.ret)
1934
+
1935
+ def _type_expr(self, node: ast.AST) -> T.Type:
1936
+ if isinstance(node, ast.Constant):
1937
+ return self._infer_constant(node)
1938
+ if isinstance(node, ast.Name):
1939
+ if node.id in self._section_bindings:
1940
+ self._error(
1941
+ node,
1942
+ f"section descriptor {node.id} may only be used as a type "
1943
+ f"qualifier: {node.id}[T]",
1944
+ code="unsupported",
1945
+ )
1946
+ sym = self._lookup(node.id)
1947
+ if sym is None:
1948
+ self._error(node, undefined_name_message(node.id), code="name")
1949
+ assert sym is not None
1950
+ if sym.kind in ("type", "module", "builtin"):
1951
+ self._error(
1952
+ node, f"{node.id} cannot be used as a value (use it only as a type annotation)", code="name"
1953
+ )
1954
+ if sym.kind == "func":
1955
+ # A function name decays to a function pointer in expression position (consistent with C)
1956
+ fi = self.functions.get(node.id)
1957
+ if fi is None:
1958
+ self._error(node, f"function {node.id} is not defined", code="name")
1959
+ node._etype = T.TVar()
1960
+ return node._etype
1961
+ ft = self._func_type_of(fi)
1962
+ node._symbol = sym
1963
+ node._etype = T.Ptr(ft)
1964
+ return node._etype
1965
+ if sym.kind == "ptr_type":
1966
+ # Ptr itself is a "pointer type constructor": Ptr[T] evaluates to a type value
1967
+ node._etype = T.PtrTypeValue(T.TVar())
1968
+ node._ptr_ctor = True
1969
+ return node._etype
1970
+ if sym.kind == "array_type":
1971
+ # Array may only appear in type-annotation position (Array[T]); it cannot be used as an ordinary value
1972
+ self._error(
1973
+ node,
1974
+ f"{node.id} can only be used in type annotations (e.g. x: Array[int32])",
1975
+ code="name",
1976
+ )
1977
+ node._etype = T.TVar()
1978
+ return node._etype
1979
+ if sym.kind == "ptr_alias":
1980
+ # A type alias lives at the type level and cannot be used as an ordinary value
1981
+ self._error(
1982
+ node,
1983
+ f"{node.id} is a type alias and cannot be used as a value (only valid in type annotations)",
1984
+ code="name",
1985
+ )
1986
+ node._etype = T.TVar()
1987
+ return node._etype
1988
+ if sym.kind == "mem_module":
1989
+ node._etype = T.VOID
1990
+ node._mem_module = True
1991
+ return node._etype
1992
+ if sym.kind == "io_module":
1993
+ node._etype = T.VOID
1994
+ node._io_module = True
1995
+ return node._etype
1996
+ if sym.kind == "strings_module":
1997
+ node._etype = T.VOID
1998
+ node._strings_module = True
1999
+ return node._etype
2000
+ if sym.kind == "bytes_module":
2001
+ node._etype = T.VOID
2002
+ node._bytes_module = True
2003
+ return node._etype
2004
+ assert sym.type is not None
2005
+ node._symbol = sym
2006
+ node._etype = sym.type
2007
+ return sym.type
2008
+ if isinstance(node, ast.BinOp):
2009
+ lt = self._type_expr(node.left)
2010
+ rt = self._type_expr(node.right)
2011
+ # Pointer arithmetic: Ptr + int, int + Ptr, Ptr - int, Ptr - Ptr
2012
+ lr = T.resolve(lt)
2013
+ rr = T.resolve(rt)
2014
+ lp = isinstance(lr, T.Ptr)
2015
+ rp = isinstance(rr, T.Ptr)
2016
+ if lp or rp:
2017
+ if isinstance(node.op, ast.Add):
2018
+ if lp and rp:
2019
+ self._error(node, "cannot add two pointers")
2020
+ int_t = rt if lp else lt
2021
+ if not T.is_int(int_t):
2022
+ self._error(node, "pointers can only be added to integers")
2023
+ node._etype = lr if lp else rr
2024
+ return node._etype
2025
+ if isinstance(node.op, ast.Sub):
2026
+ if lp and rp:
2027
+ if not T.same(lr.target, rr.target):
2028
+ self._error(node, "cannot subtract pointers of different types")
2029
+ node._etype = T.I64
2030
+ return T.I64
2031
+ if lp:
2032
+ if not T.is_int(rt):
2033
+ self._error(node, "pointers can only be subtracted by integers")
2034
+ node._etype = lr
2035
+ return lr
2036
+ self._error(node, "cannot subtract a pointer from an integer")
2037
+ self._error(node, f"pointers do not support operator {type(node.op).__name__}")
2038
+ try:
2039
+ unified = T.unify(lt, rt)
2040
+ except T.TypesMismatch as exc:
2041
+ self._error(node, str(exc))
2042
+ if isinstance(node.op, ast.Div):
2043
+ return T.F64
2044
+ r = T.resolve(unified)
2045
+ if (
2046
+ isinstance(r, T.Scalar)
2047
+ and r.category == "float"
2048
+ and isinstance(node.op, (ast.FloorDiv, ast.Mod, ast.Pow))
2049
+ ):
2050
+ return T.F64
2051
+ return self._norm(unified)
2052
+ if isinstance(node, ast.UnaryOp):
2053
+ t = self._type_expr(node.operand)
2054
+ if isinstance(node.op, ast.Not):
2055
+ return T.BOOL
2056
+ r = T.resolve(t)
2057
+ if isinstance(r, T.ConstInt):
2058
+ if isinstance(node.op, ast.USub):
2059
+ return T.ConstInt(-r.value)
2060
+ return r
2061
+ if isinstance(r, T.ConstFloat):
2062
+ if isinstance(node.op, ast.USub):
2063
+ return T.ConstFloat(-r.value)
2064
+ return r
2065
+ if isinstance(r, T.Scalar) and r.category == "bool":
2066
+ return T.I32
2067
+ return self._norm(t)
2068
+ if isinstance(node, ast.BoolOp):
2069
+ for v in node.values:
2070
+ self._type_expr(v)
2071
+ return T.BOOL
2072
+ if isinstance(node, ast.JoinedStr):
2073
+ # f-string: determine the type of each field first; the whole thing is Str
2074
+ for v in node.values:
2075
+ if isinstance(v, ast.FormattedValue):
2076
+ self._type_expr(v.value)
2077
+ return T.STR
2078
+ if isinstance(node, ast.Compare):
2079
+ ct = self._type_expr(node.left)
2080
+ for comp in node.comparators:
2081
+ ot = self._type_expr(comp)
2082
+ try:
2083
+ ct = T.unify(ct, ot)
2084
+ except T.TypesMismatch as exc:
2085
+ self._error(node, str(exc))
2086
+ return T.BOOL
2087
+ if isinstance(node, ast.Call):
2088
+ return self._type_call(node)
2089
+ if isinstance(node, ast.IfExp):
2090
+ self._type_expr(node.test)
2091
+ a = self._type_expr(node.body)
2092
+ b = self._type_expr(node.orelse)
2093
+ try:
2094
+ return T.unify(a, b)
2095
+ except T.TypesMismatch as exc:
2096
+ self._error(node, str(exc))
2097
+ if isinstance(node, ast.Attribute):
2098
+ target = self._member_type(node)
2099
+ if target is not None:
2100
+ self._error(node, "type names can only be used in annotations or casts")
2101
+ # Enum member: Mode.RUN
2102
+ enum_member = self._enum_member_type(node)
2103
+ if enum_member is not None:
2104
+ node._etype = enum_member
2105
+ node._enum_member = True
2106
+ return enum_member
2107
+ vt = self._type_expr(node.value)
2108
+ # Struct field: struct value s.f, pointer base p->f / (*p)->f
2109
+ acc = T.struct_field_access(vt)
2110
+ if acc is not None:
2111
+ st, levels = acc
2112
+ self._reject_extern_type_field(node, st, node.attr)
2113
+ if node.attr not in st.fields:
2114
+ self._error(node, f"struct {st.name} has no field {node.attr}")
2115
+ node._etype = st.fields[node.attr]
2116
+ node._field_struct = st
2117
+ node._field_name = node.attr
2118
+ node._field_ptr_levels = levels
2119
+ return node._etype
2120
+ r = T.resolve(vt)
2121
+ if isinstance(r, T.Ptr):
2122
+ self._error(
2123
+ node,
2124
+ f"cannot access field {node.attr!r} through a pointer to "
2125
+ f"{T.describe(r.target)}",
2126
+ )
2127
+ self._error(node, "unsupported attribute access")
2128
+ if isinstance(node, ast.Subscript):
2129
+ # Function-pointer type constructor: Func[[...], R] is itself a function pointer, stored internally as
2130
+ # Ptr(Func(...)) (consistent with _resolve_annotation). Handled before _type_expr(node.value)
2131
+ # to avoid Func failing an assertion for having no value type as a type constructor.
2132
+ if isinstance(node.value, ast.Name):
2133
+ base_sym = self.scope.get(node.value.id)
2134
+ if base_sym is not None and base_sym.kind == "func_type":
2135
+ node._etype = T.Ptr(self._resolve_func_annotation(node))
2136
+ return node._etype
2137
+ vt = self._type_expr(node.value)
2138
+ r = T.resolve(vt)
2139
+ if isinstance(r, T.PtrTypeValue):
2140
+ # Ptr[int32] appears in expression position: this is a "pointer type value",
2141
+ # used for a type alias like int32_ptr = Ptr[int32]
2142
+ inner = self._resolve_annotation(node.slice)
2143
+ node._etype = T.PtrTypeValue(inner)
2144
+ node._ptr_type_value = True
2145
+ return node._etype
2146
+ if isinstance(r, T.Array):
2147
+ idx_t = self._type_expr(node.slice)
2148
+ if not (T.is_int(idx_t) or T.is_bool(idx_t)):
2149
+ self._error(node.slice, "array subscript must be an integer")
2150
+ node._etype = r.element
2151
+ node._array_base = node.value
2152
+ node._array_index = node.slice
2153
+ node._array_target = r.element
2154
+ return r.element
2155
+ if T.is_bytes(r):
2156
+ # A bytes subscript yields a uchar: the result keeps the byte form and does not participate in arithmetic.
2157
+ idx_t = self._type_expr(node.slice)
2158
+ if not (T.is_int(idx_t) or T.is_bool(idx_t)):
2159
+ self._error(node.slice, "bytes subscript must be an integer")
2160
+ node._etype = T.UCHAR
2161
+ node._bytes_base = node.value
2162
+ node._bytes_index = node.slice
2163
+ return T.UCHAR
2164
+ if T.is_str(r):
2165
+ # Text subscript yields one character (char): indexed by UTF-8 code point.
2166
+ idx_t = self._type_expr(node.slice)
2167
+ if not (T.is_int(idx_t) or T.is_bool(idx_t)):
2168
+ self._error(node.slice, "string subscript must be an integer")
2169
+ node._etype = T.CHAR
2170
+ node._str_base = node.value
2171
+ node._str_index = node.slice
2172
+ return T.CHAR
2173
+ if isinstance(r, T.Ptr):
2174
+ # Pointers do not support subscripting: read with ptr.peek(p), move with ptr.skip(p, n).
2175
+ self._error(
2176
+ node,
2177
+ "pointers do not support subscripting; read a value with "
2178
+ "ptr.peek(p) and move with ptr.skip(p, n)",
2179
+ )
2180
+ return r.target
2181
+ self._error(
2182
+ node,
2183
+ "subscripting is only allowed on fixed-length arrays, bytes, "
2184
+ "or strings",
2185
+ )
2186
+ return T.I32
2187
+ if isinstance(node, ast.List):
2188
+ return self._array_literal_type(node, self._type_expr)
2189
+ self._error(node, f"expression {type(node).__name__} is not supported")
2190
+
2191
+ def _type_annotated_value(self, value: ast.AST, ann: T.Type) -> T.Type:
2192
+ """Annotated assignment: the annotation decides the element type first (e.g. x: int32 = 10)."""
2193
+ if isinstance(ann, T.Array) and isinstance(value, ast.List):
2194
+ return self._array_literal_type(value, self._type_expr, ann)
2195
+ return self._type_expr(value)
2196
+
2197
+ def _type_arg_against(self, arg: ast.AST, pt: T.Type) -> T.Type:
2198
+ """First pass: when a parameter is declared as array[T], the element type of a literal argument follows the parameter."""
2199
+ pr = T.resolve(pt)
2200
+ if isinstance(pr, T.Array) and isinstance(arg, ast.List):
2201
+ return self._array_literal_type(arg, self._type_expr, pr)
2202
+ return self._type_expr(arg)
2203
+
2204
+ def _array_literal_type(
2205
+ self, node: ast.List, typer, expected: Optional[T.Type] = None
2206
+ ) -> T.Type:
2207
+ """Infer the element type and length of a list literal, producing T.Array.
2208
+
2209
+ When expected is given (from an array[T] annotation), the element type follows the annotation,
2210
+ consistent with the scalar annotation `x: int32 = 10`; nested cases propagate down one level at a time.
2211
+ """
2212
+ if not node.elts:
2213
+ self._error(node, "cannot infer length and element type of an empty array; use make_array(T, N)")
2214
+ exp_elem: Optional[T.Type] = None
2215
+ if expected is not None and isinstance(T.resolve(expected), T.Array):
2216
+ exp_elem = T.resolve(expected).element
2217
+ elem: T.Type = T.TVar()
2218
+ for e in node.elts:
2219
+ if isinstance(e, ast.List):
2220
+ sub_exp = (
2221
+ exp_elem if exp_elem is not None and isinstance(T.resolve(exp_elem), T.Array) else None
2222
+ )
2223
+ et = self._array_literal_type(e, typer, sub_exp)
2224
+ else:
2225
+ et = typer(e)
2226
+ if exp_elem is not None and isinstance(e, ast.Constant) and (
2227
+ isinstance(e.value, str) or isinstance(e.value, bytes)
2228
+ ):
2229
+ # Char-family arrays (Array[char] / Array[uchar] / Array[schar]):
2230
+ # elements written as char literals take that byte per the target type; do not treat them as Str/Bytes.
2231
+ ch = self._char_from_str(exp_elem, e)
2232
+ if ch is not None:
2233
+ et = ch
2234
+ if exp_elem is not None:
2235
+ try:
2236
+ et = T.unify(exp_elem, et)
2237
+ except T.TypesMismatch as exc:
2238
+ self._error(e, f"array element types are inconsistent: {exc}")
2239
+ try:
2240
+ elem = T.unify(elem, et)
2241
+ except T.TypesMismatch as exc:
2242
+ self._error(node, f"array element types are inconsistent: {exc}")
2243
+ node._etype = T.Array(elem, len(node.elts))
2244
+ return node._etype
2245
+
2246
+ def _type_call(self, node: ast.Call) -> T.Type:
2247
+ f = node.func
2248
+ if isinstance(f, ast.Name):
2249
+ sym = self._lookup(f.id)
2250
+ if sym is None:
2251
+ if f.id == "make_array":
2252
+ self._error(
2253
+ f,
2254
+ "make_array must be imported: use 'from embeddedpy.arrays import make_array'",
2255
+ code="name",
2256
+ )
2257
+ self._error(f, undefined_name_message(f.id), code="name")
2258
+ assert sym is not None
2259
+ # Function-pointer call: a variable (local/global/param) whose type is Ptr[Func[...]].
2260
+ # The extern function-pointer type ExternFuncPtr is also carried as Ptr[ExternFuncPtr],
2261
+ # and since ExternFuncPtr is a subclass of Func, the same check branch covers it.
2262
+ if sym.kind in ("local", "global", "param"):
2263
+ st = T.resolve(sym.type)
2264
+ if isinstance(st, T.Ptr) and isinstance(T.resolve(st.target), T.Func):
2265
+ ft = T.resolve(st.target)
2266
+ node.func._symbol = sym
2267
+ for arg, expected in zip(node.args, ft.args):
2268
+ at = self._type_expr(arg)
2269
+ try:
2270
+ T.unify(expected, at)
2271
+ except T.TypesMismatch as exc:
2272
+ self._error(arg, f"argument type mismatch: {exc}")
2273
+ node._funcptr_call = True
2274
+ node._funcptr_type = ft
2275
+ node._etype = ft.ret
2276
+ return ft.ret
2277
+ if sym.kind == "make_array_func":
2278
+ return self._type_make_array(node)
2279
+ if sym.kind == "auto_func":
2280
+ self._error(
2281
+ node,
2282
+ "auto() can only be used as an enum member value",
2283
+ code="unsupported",
2284
+ )
2285
+ if sym.kind == "type":
2286
+ if isinstance(T.resolve(sym.type), T.Struct):
2287
+ st = T.resolve(sym.type)
2288
+ self._type_struct_ctor(node, st)
2289
+ node._struct_ctor = st
2290
+ node._etype = st
2291
+ return st
2292
+ for a in node.args:
2293
+ self._type_expr(a)
2294
+ assert sym.type is not None
2295
+ return sym.type
2296
+ if sym.kind == "ptr_func":
2297
+ if len(node.args) != 1:
2298
+ self._error(node, "ptr requires one argument")
2299
+ arg = node.args[0]
2300
+ at = self._type_expr(arg)
2301
+ node._etype = T.Ptr(at)
2302
+ return node._etype
2303
+ if sym.kind == "func":
2304
+ fi = self.functions[f.id]
2305
+ for arg, pname in zip(node.args, fi.params):
2306
+ pt = fi.locals[pname].type
2307
+ assert pt is not None
2308
+ pr = T.resolve(pt)
2309
+ ch = self._char_from_str(pr, arg)
2310
+ if ch is not None:
2311
+ # A string literal passed to a char parameter: take the first character (_char_from_str has already tagged the node)
2312
+ at = ch
2313
+ else:
2314
+ at = self._type_arg_against(arg, pt)
2315
+ try:
2316
+ T.unify(pt, at)
2317
+ except T.TypesMismatch as exc:
2318
+ self._error(arg, f"argument {pname} of call to {fi.name}: {exc}")
2319
+ for arg in node.args[len(fi.params):]:
2320
+ self._type_expr(arg)
2321
+ return fi.ret
2322
+ if sym.kind == "builtin":
2323
+ return self._type_builtin(node, f.id)
2324
+ if sym.kind == "sizeof_func":
2325
+ return self._type_builtin(node, "sizeof")
2326
+ if sym.kind == "copy_aggregate_func":
2327
+ return self._type_copy_aggregate(node)
2328
+ self._error(f, f"{f.id} is not callable", code="name")
2329
+ if isinstance(f, ast.Attribute):
2330
+ api = self._ptr_api_name(f)
2331
+ if api is not None:
2332
+ return self._type_ptr_api_call(node, api)
2333
+ mem_api = self._mem_api_name(f)
2334
+ if mem_api is not None:
2335
+ return self._type_mem_api_call(node, mem_api)
2336
+ io_api = self._io_api_name(f)
2337
+ if io_api is not None:
2338
+ return self._type_io_api_call(node, io_api)
2339
+ strings_api = self._strings_api_name(f)
2340
+ if strings_api is not None:
2341
+ return self._type_strings_api_call(node, strings_api)
2342
+ bytes_api = self._bytes_api_name(f)
2343
+ if bytes_api is not None:
2344
+ return self._type_bytes_api_call(node, bytes_api)
2345
+ # c.clz / c.ctz / c.popcount: expression-level builtins,
2346
+ # going through the same three-pass dispatch as ptr/mem (first pass only determines type).
2347
+ c_api = self._c_expr_api_name(f)
2348
+ if c_api is not None:
2349
+ return self._type_c_expr_api_call(node, c_api)
2350
+ # c.xxx(...): a member call into the C interop entry point. Registration-class members may only be written on the right-hand side of an assignment,
2351
+ # and any other member name does not exist - all of these must yield a clear error rather than falling through to generic attribute inference and crashing.
2352
+ c_member = self._c_member_name(f)
2353
+ if c_member is not None:
2354
+ pp_name = pp.pp_member_name(node)
2355
+ if pp_name in pp.PP_COND_FUNCS:
2356
+ # The legitimate path is the whole condition in an If branch being recognized as a compile-time condition,
2357
+ # which does not go through _type_call; reaching here means it was used as an ordinary value.
2358
+ self._error(
2359
+ node,
2360
+ f"c.{pp_name}(...) is only allowed in a preprocessor "
2361
+ f"condition (if / elif with c.defined / c.macro)",
2362
+ )
2363
+ return T.TVar()
2364
+ if pp_name in pp.PP_DIRECTIVES:
2365
+ # Directive functions may only be standalone statements; the bare-call branch already let them through earlier.
2366
+ self._error(
2367
+ node,
2368
+ f"c.{pp_name}(...) must be a standalone statement, "
2369
+ f"not used as a value",
2370
+ )
2371
+ return T.TVar()
2372
+ decl_name = pp.pp_decl_member_name(node)
2373
+ if decl_name is not None:
2374
+ # A named declaration was used as a value: inside a conditional block only standalone statements are accepted.
2375
+ self._error(
2376
+ node,
2377
+ f"c.{decl_name}(...) must be a standalone statement, "
2378
+ f"not used as a value",
2379
+ )
2380
+ return T.TVar()
2381
+ reg = self._c_registration_call_name(node)
2382
+ if reg is not None:
2383
+ self._error(
2384
+ node,
2385
+ f"c.{reg} must be assigned to a name "
2386
+ f"(e.g. X = c.{reg}(...)); it is a compile-time "
2387
+ f"registration and cannot be used as a value",
2388
+ )
2389
+ else:
2390
+ self._error(
2391
+ node,
2392
+ f"unknown member 'c.{c_member}' in C interop; "
2393
+ f"available members are: include, extern_type, "
2394
+ f"extern_const, extern_var, typedef, define, "
2395
+ f"extern_function, defined, macro, emit, pragma, "
2396
+ f"error, warning, undef; expression builtins: "
2397
+ f"clz, ctz, popcount; statement "
2398
+ f"builtin: barrier; decorators: packed, word, "
2399
+ f"inline, section, aligned, weak, visibility, export",
2400
+ )
2401
+ return T.TVar()
2402
+ self._require_attr_base(f)
2403
+ target = self._member_type(f)
2404
+ if target is not None:
2405
+ for a in node.args:
2406
+ self._type_expr(a)
2407
+ return target
2408
+ # A struct field holds a function pointer: c.cb(5) (in C it is also c.cb(5))
2409
+ ft = self._field_funcptr_type(f)
2410
+ if ft is not None:
2411
+ for arg, expected in zip(node.args, ft.args):
2412
+ at = self._type_arg_against(arg, expected)
2413
+ try:
2414
+ T.unify(expected, at)
2415
+ except T.TypesMismatch as exc:
2416
+ self._error(arg, f"argument type mismatch: {exc}")
2417
+ for arg in node.args[len(ft.args):]:
2418
+ self._type_expr(arg)
2419
+ node._funcptr_call = True
2420
+ node._funcptr_type = ft
2421
+ node._etype = ft.ret
2422
+ return ft.ret
2423
+ path = self._member_path(f)
2424
+ if path is not None and path.startswith("embeddedpy"):
2425
+ self._error(node, f"wrapper {path} is not supported", code="import")
2426
+ # Disallowed methods on fixed-length arrays: give a friendly error
2427
+ if f.attr in FORBIDDEN_ARRAY_METHODS:
2428
+ try:
2429
+ base_t = T.resolve(self._type_expr(f.value))
2430
+ except CompileError:
2431
+ base_t = None
2432
+ if isinstance(base_t, T.Array):
2433
+ self._error(
2434
+ node,
2435
+ f"fixed-length arrays do not support {f.attr}; use subscript assignment x[i] = v for in-place writes",
2436
+ )
2437
+ self._error(f, "unsupported attribute call")
2438
+ self._error(f, "only calls to function names are supported")
2439
+
2440
+ def _type_make_array(self, node: ast.Call) -> T.Type:
2441
+ if len(node.args) != 2:
2442
+ self._error(node, "make_array takes two arguments: make_array(element_type, length)")
2443
+ elem = self._resolve_annotation(node.args[0])
2444
+ # The length must be a compile-time constant: a literal, or the constant value of a const variable
2445
+ length = self._const_length(node.args[1])
2446
+ if length is None:
2447
+ n_t = self._type_expr(node.args[1])
2448
+ r = T.resolve(n_t)
2449
+ if not isinstance(r, T.ConstInt):
2450
+ self._error(node.args[1], "make_array length must be a compile-time integer literal")
2451
+ length = r.value
2452
+ if length <= 0:
2453
+ self._error(node.args[1], "make_array length must be a positive integer")
2454
+ node._etype = T.Array(elem, length)
2455
+ return node._etype
2456
+
2457
+ def _type_builtin(self, node: ast.Call, name: str) -> T.Type:
2458
+ if name == "range":
2459
+ self._error(node, "range can only be used in for loops")
2460
+ if name == "sizeof":
2461
+ # sizeof evaluates only a type: the argument is a type name, not an expression.
2462
+ # Both passes compute a constant size, avoiding the first pass binding the variable to int64.
2463
+ return self._check_sizeof(node)
2464
+ arg_types = [self._type_expr(a) for a in node.args]
2465
+ if name == "print":
2466
+ return T.VOID
2467
+ if name == "input":
2468
+ if len(arg_types) > 1:
2469
+ self._error(node, "input takes at most one argument")
2470
+ if arg_types and not T.is_str(arg_types[0]):
2471
+ self._error(node.args[0], "input prompt must be a string")
2472
+ return T.STR
2473
+ if name in ("min", "max"):
2474
+ if len(arg_types) == 2:
2475
+ try:
2476
+ return T.unify(arg_types[0], arg_types[1])
2477
+ except T.TypesMismatch as exc:
2478
+ self._error(node, str(exc))
2479
+ return T.I64
2480
+ if name == "len":
2481
+ # A fixed-length array's length is already known in the first pass (type is unified), represented as a constant integer,
2482
+ # so len(a) is not bound prematurely to int64.
2483
+ if arg_types:
2484
+ r = T.resolve(arg_types[0])
2485
+ if isinstance(r, T.Array) and r.length >= 0:
2486
+ return T.ConstInt(r.length)
2487
+ return T.I64
2488
+ if name == "abs":
2489
+ if arg_types:
2490
+ at = arg_types[0]
2491
+ r = T.resolve(at)
2492
+ if isinstance(r, T.Scalar) and r.category == "bool":
2493
+ return T.I32
2494
+ return self._norm(at)
2495
+ return T.I64
2496
+ if name == "int":
2497
+ return T.I64
2498
+ if name == "float":
2499
+ return T.F64
2500
+ if name == "str":
2501
+ return T.STR
2502
+ if name == "sizeof":
2503
+ # sizeof evaluates only a type; the concrete type is determined in the second pass
2504
+ return T.I64
2505
+ self._error(node, f"builtin function {name} is not supported")
2506
+
2507
+ def _norm(self, t: T.Type) -> T.Type:
2508
+ """Normalize a constant type to the default scalar type; return inferred variables unchanged."""
2509
+ r = T.resolve(t)
2510
+ if isinstance(r, (T.ConstInt, T.ConstFloat)):
2511
+ return T.base(r)
2512
+ return r
2513
+
2514
+ def _try_type_alias(self, stmt: ast.Assign, target: ast.Name) -> Optional[Symbol]:
2515
+ """Recognize a type alias: int32_ptr = c.typedef(Ptr[int32]).
2516
+
2517
+ Equivalent to C's ``typedef int32_t *int32_ptr;``. It is declared explicitly with ``c.typedef(...)``
2518
+ (rather than a bare assignment ``X = Ptr[int32]``), which both distinguishes it at a glance from a value
2519
+ assignment ``x = 5`` and is symmetric with ``c.extern_type("DEV")`` (which consumes an external type and
2520
+ emits nothing) - here we alias a type defined for this module (the defining side). The Func form
2521
+ ``c.typedef(Func[[int32], void])`` is the main benefit, letting a verbose function-pointer signature
2522
+ take a short name.
2523
+
2524
+ Returns the bound symbol; returns None if this is not a type alias.
2525
+ """
2526
+ value = stmt.value
2527
+ # A bare assignment ``X = Ptr[int32]`` / ``X = Func[[...], R]`` is rejected at compile time:
2528
+ # a type alias may only be declared explicitly via c.typedef(...), to avoid confusion with value assignment.
2529
+ if isinstance(value, ast.Subscript) and isinstance(value.value, ast.Name):
2530
+ base = self.scope.get(value.value.id)
2531
+ if base is not None and base.kind in ("ptr_type", "func_type"):
2532
+ self._error(
2533
+ value,
2534
+ "a type expression cannot be assigned as a value; "
2535
+ "use X = c.typedef(Ptr[T]) or X = c.typedef(Func[[...], R]) "
2536
+ "to define a type alias",
2537
+ )
2538
+ if not isinstance(value, ast.Call):
2539
+ return None
2540
+ f = value.func
2541
+ if not (isinstance(f, ast.Attribute)
2542
+ and f.attr == "typedef"
2543
+ and isinstance(f.value, ast.Name)
2544
+ and f.value.id == "c"):
2545
+ return None
2546
+ if value.keywords or len(value.args) != 1:
2547
+ self._error(
2548
+ value,
2549
+ "c.typedef requires exactly one type argument (Ptr[T] or Func[[...], R])",
2550
+ )
2551
+ return None
2552
+ type_node = value.args[0]
2553
+
2554
+ # Evaluate the right-hand type expression:
2555
+ # Ptr[T] -> PtrTypeValue(T) (pointer type value, must be carried as an alias)
2556
+ # Func[[...],R] -> Ptr(Func(...)) (function-pointer alias, written by value as *name)
2557
+ vt = self._type_expr(type_node) if self._second_pass else self._infer_expr(type_node)
2558
+ resolved = T.resolve(vt)
2559
+ if isinstance(resolved, T.PtrTypeValue):
2560
+ alias_type = resolved
2561
+ elif isinstance(resolved, T.Ptr) and isinstance(T.resolve(resolved.target), T.Func):
2562
+ alias_type = resolved
2563
+ else:
2564
+ self._error(
2565
+ type_node, "c.typedef only accepts Ptr[T] or Func[[...], R]"
2566
+ )
2567
+ return None
2568
+
2569
+ # Conflict with a same-named c.extern_type / c.extern_const / c.extern_var / c.define:
2570
+ # all four bind some declaration to a name, so reuse their respective seen sets for cross-reporting.
2571
+ seen_sets = (
2572
+ getattr(self, "_extern_type_seen", set()),
2573
+ getattr(self, "_extern_const_seen", set()),
2574
+ getattr(self, "_extern_var_seen", set()),
2575
+ getattr(self, "_macro_seen", set()),
2576
+ )
2577
+ if any(target.id in s for s in seen_sets):
2578
+ self._error(
2579
+ target,
2580
+ f"{target.id} is already declared as an external type, constant, "
2581
+ f"variable, or macro",
2582
+ )
2583
+ return None
2584
+
2585
+ target_sym = self._target_symbol(target)
2586
+ alias_seen = getattr(self, "_alias_seen", None)
2587
+ if alias_seen is None:
2588
+ alias_seen = set()
2589
+ self._alias_seen = alias_seen
2590
+
2591
+ if target_sym.kind == "ptr_alias":
2592
+ # Second pass: already bound in the first pass; only need to verify type consistency
2593
+ existing = T.resolve(target_sym.type)
2594
+ if isinstance(existing, T.PtrTypeValue) and isinstance(alias_type, T.PtrTypeValue):
2595
+ if not T.same(existing, alias_type):
2596
+ self._error(
2597
+ target,
2598
+ f"{target.id} is already bound to {T.describe(existing)}, "
2599
+ f"and cannot be rebound to {T.describe(alias_type)}",
2600
+ )
2601
+ elif isinstance(existing, T.Ptr) and isinstance(alias_type, T.Ptr) \
2602
+ and not T.same(existing, alias_type):
2603
+ self._error(
2604
+ target,
2605
+ f"{target.id} is already bound to {T.describe(existing)}, "
2606
+ f"and cannot be rebound to {T.describe(alias_type)}",
2607
+ )
2608
+ stmt._type_alias = True
2609
+ stmt._alias_sym = target_sym
2610
+ return target_sym
2611
+ if target_sym.type is not None and not isinstance(
2612
+ T.resolve(target_sym.type), T.TVar
2613
+ ):
2614
+ self._error(target, f"{target.id} has already been assigned")
2615
+ return target_sym
2616
+ # A typedef name is a C-level type name, not a top-level variable: it gets neither the g_ prefix nor the module
2617
+ # prefix, otherwise external C cannot access the user-written alias (a submodule would become g_<mod>__X).
2618
+ c_name = getattr(stmt, "_embeddedpy_orig_name", target.id)
2619
+ if c_name in runtime_lib.RESERVED_IDENTIFIERS:
2620
+ self._error(
2621
+ target,
2622
+ f"c.typedef alias name {c_name!r} collides with an identifier "
2623
+ f"used by the generated C runtime",
2624
+ )
2625
+ target_sym.c_name = c_name
2626
+ target_sym.kind = "ptr_alias"
2627
+ target_sym.type = alias_type
2628
+ alias_seen.add(target.id)
2629
+ stmt._type_alias = True
2630
+ stmt._alias_sym = target_sym
2631
+ return target_sym
2632
+
2633
+ def _record_const_value(self, sym: Symbol, value: ast.AST) -> None:
2634
+ """Record the constant value of a const variable (used in constant expressions such as make_array length)."""
2635
+ if isinstance(value, ast.Constant) and isinstance(value.value, int) \
2636
+ and not isinstance(value.value, bool):
2637
+ sym.const_value = value.value
2638
+
2639
+ def _const_length(self, node: ast.AST) -> Optional[int]:
2640
+ """Get an array length known at compile time: a literal, or the constant value of a const variable."""
2641
+ if isinstance(node, ast.Constant) and isinstance(node.value, int) \
2642
+ and not isinstance(node.value, bool):
2643
+ return node.value
2644
+ if isinstance(node, ast.Name):
2645
+ sym = self.scope.get(node.id)
2646
+ if sym is not None and sym.const_value is not None:
2647
+ return sym.const_value
2648
+ return None
2649
+
2650
+ def _is_const_expr(self, node: ast.AST) -> bool:
2651
+ """Determine whether an expression is a compile-time constant (usable for static initialization)."""
2652
+ if isinstance(node, ast.Constant):
2653
+ return isinstance(node.value, (int, float, bool, str, bytes))
2654
+ if isinstance(node, ast.Attribute):
2655
+ # An enum member is a compile-time constant
2656
+ return getattr(node, "_enum_member", False)
2657
+ if isinstance(node, ast.UnaryOp):
2658
+ return isinstance(node.op, (ast.USub, ast.UAdd)) and self._is_const_expr(
2659
+ node.operand
2660
+ )
2661
+ if isinstance(node, ast.BinOp):
2662
+ return self._is_const_expr(node.left) and self._is_const_expr(node.right)
2663
+ if isinstance(node, ast.List):
2664
+ # An array may be statically initialized with an initializer list
2665
+ return all(self._is_const_expr(e) for e in node.elts)
2666
+ if isinstance(node, ast.Call):
2667
+ # sizeof(T) is a compile-time constant
2668
+ return getattr(node, "_builtin", None) == "sizeof"
2669
+ return False
2670
+
2671
+ def _ann_compatible(self, current: T.Type, ann: T.Type) -> bool:
2672
+ """Whether an annotation is compatible with the already-inferred type (unknown array length is treated as compatible)."""
2673
+ if T.same(current, ann):
2674
+ return True
2675
+ rc = T.resolve(current)
2676
+ ra = T.resolve(ann)
2677
+ if isinstance(rc, T.Array) and isinstance(ra, T.Array):
2678
+ if ra.length < 0:
2679
+ return T.same(rc.element, ra.element)
2680
+ if rc.length < 0:
2681
+ return T.same(rc.element, ra.element)
2682
+ return False
2683
+
2684
+ def _require_cond(self, node: ast.AST) -> T.Type:
2685
+ t = self._infer_expr(node)
2686
+ if not (T.is_bool(t) or T.is_int(t) or T.is_ptr(t) or T.is_file(t)):
2687
+ self._error(
2688
+ node, f"condition must be bool, integer, pointer, or File; got {T.describe(t)}"
2689
+ )
2690
+ if T.is_file(t) or T.is_ptr(t):
2691
+ node._cond_type = t
2692
+ else:
2693
+ node._cond_type = T.base(t)
2694
+ return t
2695
+
2696
+ def _ptr_api_name(self, f: ast.Attribute) -> Optional[str]:
2697
+ """Recognize a ptr.xxx pointer-API call and return the API name."""
2698
+ if f.attr not in PTR_API_NAMES:
2699
+ return None
2700
+ base = f.value
2701
+ if not isinstance(base, ast.Name):
2702
+ return None
2703
+ sym = self._lookup(base.id)
2704
+ if sym is None or sym.kind != "ptr_func":
2705
+ return None
2706
+ return f.attr
2707
+
2708
+ def _mem_api_name(self, f: ast.Attribute) -> Optional[str]:
2709
+ """Recognize a mem.xxx heap-memory-management call and return the API name."""
2710
+ if f.attr not in MEM_API_NAMES:
2711
+ return None
2712
+ base = f.value
2713
+ if not isinstance(base, ast.Name):
2714
+ return None
2715
+ sym = self._lookup(base.id)
2716
+ if sym is None or sym.kind != "mem_module":
2717
+ return None
2718
+ return f.attr
2719
+
2720
+ def _c_expr_api_name(self, f: ast.Attribute) -> Optional[str]:
2721
+ """Recognize a c.xxx bit-operation builtin and return the API name."""
2722
+ if f.attr not in C_EXPR_API_NAMES:
2723
+ return None
2724
+ base = f.value
2725
+ if not isinstance(base, ast.Name):
2726
+ return None
2727
+ sym = self._lookup(base.id)
2728
+ if sym is None or sym.kind != "c_module":
2729
+ return None
2730
+ return f.attr
2731
+
2732
+ def _c_stmt_api_name(self, node: ast.AST) -> Optional[str]:
2733
+ """Recognize a c.xxx() statement-level builtin (no return value, standalone statement, emits one line of C) and return the API name."""
2734
+ if not isinstance(node, ast.Call):
2735
+ return None
2736
+ f = node.func
2737
+ if not isinstance(f, ast.Attribute):
2738
+ return None
2739
+ if f.attr not in C_STMT_API_NAMES:
2740
+ return None
2741
+ base = f.value
2742
+ if not isinstance(base, ast.Name):
2743
+ return None
2744
+ sym = self._lookup(base.id)
2745
+ if sym is None or sym.kind != "c_module":
2746
+ return None
2747
+ return f.attr
2748
+
2749
+ def _io_api_name(self, f: ast.Attribute) -> Optional[str]:
2750
+ """Recognize an io.xxx file-I/O call and return the API name."""
2751
+ if f.attr not in IO_API_NAMES:
2752
+ return None
2753
+ base = f.value
2754
+ if not isinstance(base, ast.Name):
2755
+ return None
2756
+ sym = self._lookup(base.id)
2757
+ if sym is None or sym.kind != "io_module":
2758
+ return None
2759
+ return f.attr
2760
+
2761
+ def _type_io_api_call(self, node: ast.Call, api: str) -> T.Type:
2762
+ """First pass: types for io.open / io.read / io.write / io.close."""
2763
+ node._io_api = api
2764
+ if node.keywords:
2765
+ self._error(node, f"io.{api} does not support keyword arguments")
2766
+ args = node.args
2767
+ if api == "open":
2768
+ if len(args) != 2:
2769
+ self._error(node, "io.open requires two arguments: io.open(path, mode)")
2770
+ return T.FILE
2771
+ path_t = self._type_expr(args[0])
2772
+ if not T.is_str(path_t):
2773
+ self._error(args[0], "io.open path must be a string")
2774
+ mode_t = self._type_expr(args[1])
2775
+ if not T.is_str(mode_t):
2776
+ self._error(args[1], "io.open mode must be a string")
2777
+ node._etype = T.FILE
2778
+ return T.FILE
2779
+ if api == "read":
2780
+ if len(args) != 2:
2781
+ self._error(node, "io.read requires two arguments: io.read(file, capacity)")
2782
+ return T.BYTES
2783
+ ft = self._type_expr(args[0])
2784
+ if not T.is_file(ft):
2785
+ self._error(args[0], "io.read first argument must be a File")
2786
+ cap_t = self._type_expr(args[1])
2787
+ if not (T.is_int(cap_t) or T.is_bool(cap_t)):
2788
+ self._error(args[1], "io.read capacity must be an integer")
2789
+ node._etype = T.BYTES
2790
+ return T.BYTES
2791
+ if api == "write":
2792
+ if len(args) != 2:
2793
+ self._error(node, "io.write requires two arguments: io.write(file, data)")
2794
+ return T.I64
2795
+ ft = self._type_expr(args[0])
2796
+ if not T.is_file(ft):
2797
+ self._error(args[0], "io.write first argument must be a File")
2798
+ dt = self._type_expr(args[1])
2799
+ if not T.is_bytes(dt):
2800
+ self._error(args[1], "io.write second argument must be a bytes value")
2801
+ node._etype = T.I64
2802
+ return T.I64
2803
+ # close
2804
+ if len(args) != 1:
2805
+ self._error(node, "io.close requires one argument: io.close(file)")
2806
+ return T.VOID
2807
+ ft = self._type_expr(args[0])
2808
+ if not T.is_file(ft):
2809
+ self._error(args[0], "io.close argument must be a File")
2810
+ node._etype = T.VOID
2811
+ return T.VOID
2812
+
2813
+ def _strings_api_name(self, f: ast.Attribute) -> Optional[str]:
2814
+ """Recognize a strings.xxx text-buffer call and return the API name."""
2815
+ base = f.value
2816
+ if not isinstance(base, ast.Name):
2817
+ return None
2818
+ sym = self._lookup(base.id)
2819
+ if sym is None or sym.kind != "strings_module":
2820
+ return None
2821
+ if f.attr not in STRINGS_API_NAMES:
2822
+ return None
2823
+ return f.attr
2824
+
2825
+ def _type_strings_api_call(self, node: ast.Call, api: str) -> T.Type:
2826
+ """First pass: types for strings.data / byte_len / from_ptr."""
2827
+ node._strings_api = api
2828
+ if node.keywords:
2829
+ self._error(node, f"strings.{api} does not support keyword arguments")
2830
+ args = node.args
2831
+ if api == "from_ptr":
2832
+ if len(args) != 2:
2833
+ self._error(
2834
+ node,
2835
+ "strings.from_ptr requires two arguments: strings.from_ptr(p, n)",
2836
+ )
2837
+ return T.STR
2838
+ pt = self._type_expr(args[0])
2839
+ nt = self._type_expr(args[1])
2840
+ if not T.is_ptr(pt):
2841
+ self._error(args[0], "strings.from_ptr first argument must be a pointer")
2842
+ if not (T.is_int(nt) or T.is_bool(nt)):
2843
+ self._error(args[1], "strings.from_ptr length must be an integer")
2844
+ node._etype = T.STR
2845
+ return T.STR
2846
+ if api == "data":
2847
+ if len(args) != 1:
2848
+ self._error(node, "strings.data requires one argument: strings.data(s)")
2849
+ return T.Ptr(T.CHAR)
2850
+ st = self._type_expr(args[0])
2851
+ if not T.is_str(st):
2852
+ self._error(args[0], "strings.data argument must be a Str")
2853
+ node._etype = T.Ptr(T.CHAR)
2854
+ return T.Ptr(T.CHAR)
2855
+ # byte_len
2856
+ if len(args) != 1:
2857
+ self._error(node, "strings.byte_len requires one argument: strings.byte_len(s)")
2858
+ return T.I64
2859
+ st = self._type_expr(args[0])
2860
+ if not T.is_str(st):
2861
+ self._error(args[0], "strings.byte_len argument must be a Str")
2862
+ node._etype = T.I64
2863
+ return T.I64
2864
+
2865
+ def _bytes_api_name(self, f: ast.Attribute) -> Optional[str]:
2866
+ """Recognize a bytes.xxx byte-buffer call and return the API name."""
2867
+ base = f.value
2868
+ if not isinstance(base, ast.Name):
2869
+ return None
2870
+ sym = self._lookup(base.id)
2871
+ if sym is None or sym.kind != "bytes_module":
2872
+ return None
2873
+ if f.attr not in BYTES_API_NAMES:
2874
+ return None
2875
+ return f.attr
2876
+
2877
+ def _type_bytes_api_call(self, node: ast.Call, api: str) -> T.Type:
2878
+ """First pass: types for bytes.data / byte_len / from_ptr."""
2879
+ node._bytes_api = api
2880
+ if node.keywords:
2881
+ self._error(node, f"bytes.{api} does not support keyword arguments")
2882
+ args = node.args
2883
+ if api == "from_ptr":
2884
+ if len(args) != 2:
2885
+ self._error(
2886
+ node,
2887
+ "bytes.from_ptr requires two arguments: bytes.from_ptr(p, n)",
2888
+ )
2889
+ return T.BYTES
2890
+ pt = self._type_expr(args[0])
2891
+ nt = self._type_expr(args[1])
2892
+ if not T.is_ptr(pt):
2893
+ self._error(args[0], "bytes.from_ptr first argument must be a pointer")
2894
+ if not (T.is_int(nt) or T.is_bool(nt)):
2895
+ self._error(args[1], "bytes.from_ptr length must be an integer")
2896
+ node._etype = T.BYTES
2897
+ return T.BYTES
2898
+ if api == "data":
2899
+ if len(args) != 1:
2900
+ self._error(node, "bytes.data requires one argument: bytes.data(b)")
2901
+ return T.Ptr(T.UCHAR)
2902
+ st = self._type_expr(args[0])
2903
+ if not T.is_bytes(st):
2904
+ self._error(args[0], "bytes.data argument must be a Bytes")
2905
+ node._etype = T.Ptr(T.UCHAR)
2906
+ return T.Ptr(T.UCHAR)
2907
+ # byte_len
2908
+ if len(args) != 1:
2909
+ self._error(node, "bytes.byte_len requires one argument: bytes.byte_len(b)")
2910
+ return T.I64
2911
+ st = self._type_expr(args[0])
2912
+ if not T.is_bytes(st):
2913
+ self._error(args[0], "bytes.byte_len argument must be a Bytes")
2914
+ node._etype = T.I64
2915
+ return T.I64
2916
+
2917
+
2918
+ def _field_funcptr_type(self, f: ast.Attribute) -> Optional[T.Func]:
2919
+ """When a struct field holds a function pointer, return that function's type; otherwise None.
2920
+
2921
+ ``c.cb(5)`` - in C, ``cb`` is an ``int (*)(int)`` field and can be called directly,
2922
+ embeddedpy likewise does not require writing ``(*c.cb)(5)``.
2923
+
2924
+ On the first call it also computes the field type and tags it with ``_field_*``
2925
+ (needed by codegen to emit ``s.f`` / ``p->f``); the second pass reuses it directly.
2926
+ """
2927
+ ft = getattr(f, "_etype", None)
2928
+ if ft is None:
2929
+ vt = self._type_expr(f.value)
2930
+ acc = T.struct_field_access(vt)
2931
+ if acc is None:
2932
+ return None
2933
+ st, levels = acc
2934
+ self._reject_extern_type_field(f, st, f.attr)
2935
+ if f.attr not in st.fields:
2936
+ return None
2937
+ ft = st.fields[f.attr]
2938
+ f._etype = ft
2939
+ f._field_struct = st
2940
+ f._field_name = f.attr
2941
+ f._field_ptr_levels = levels
2942
+ r = T.resolve(ft)
2943
+ if isinstance(r, T.Ptr) and isinstance(T.resolve(r.target), T.Func):
2944
+ return T.resolve(r.target)
2945
+ return None
2946
+
2947
+ def _require_attr_base(self, f: ast.Attribute) -> None:
2948
+ """The base name of an attribute access must already be defined, otherwise report "undefined name"."""
2949
+ base = f.value
2950
+ if isinstance(base, ast.Name) and self._lookup(base.id) is None:
2951
+ self._error(base, undefined_name_message(base.id), code="name")
2952
+
2953
+ def _resolve_type_arg(self, node: ast.AST) -> Optional[T.Type]:
2954
+ """Resolve the type argument of ptr.from_int / ptr.cast (a type name such as int32)."""
2955
+ if isinstance(node, ast.Name):
2956
+ sym = self._lookup(node.id)
2957
+ if sym is not None and sym.kind == "type" and sym.type is not None:
2958
+ return sym.type
2959
+ return None
2960
+ if isinstance(node, ast.Attribute):
2961
+ return self._member_type(node)
2962
+ return None
2963
+
2964
+ def _ptr_target(self, t: T.Type) -> Optional[T.Type]:
2965
+ """Get the pointed-to type of a pointer; return None if it is not a pointer."""
2966
+ r = T.resolve(t)
2967
+ if isinstance(r, T.Ptr):
2968
+ return r.target
2969
+ return None
2970
+
2971
+ def _array_scalar_elem(self, t: T.Type) -> T.Type:
2972
+ """Element type when an array decays to a pointer to its first element (innermost for multi-dimensional)."""
2973
+ r = T.resolve(t)
2974
+ while isinstance(r, T.Array):
2975
+ r = T.resolve(r.element)
2976
+ return r
2977
+
2978
+ def _type_ptr_api_call(self, node: ast.Call, api: str) -> T.Type:
2979
+ """First pass: roughly compute the type of ptr.xxx (must be precise enough for global variable typing)."""
2980
+ node._ptr_api = api
2981
+ args = node.args
2982
+ if api == "ref":
2983
+ if len(args) != 1:
2984
+ self._error(node, "ptr.ref requires one argument")
2985
+ return T.Ptr(T.TVar())
2986
+ at = self._type_expr(args[0])
2987
+ r = T.resolve(at)
2988
+ if isinstance(r, T.Array):
2989
+ at = self._array_scalar_elem(at)
2990
+ node._etype = T.Ptr(at)
2991
+ return node._etype
2992
+ if api == "null":
2993
+ # ptr.null(): a null pointer. The element type is determined by context (annotation / assignment target)
2994
+ if len(args) != 0:
2995
+ self._error(node, "ptr.null takes no arguments")
2996
+ node._etype = T.Ptr(T.TVar())
2997
+ return node._etype
2998
+ if api == "peek":
2999
+ if len(args) != 1:
3000
+ self._error(node, "ptr.peek requires one argument")
3001
+ return T.TVar()
3002
+ target = self._ptr_target(self._type_expr(args[0]))
3003
+ node._etype = target if target is not None else T.TVar()
3004
+ return node._etype
3005
+ if api == "poke":
3006
+ if len(args) != 2:
3007
+ self._error(node, "ptr.poke requires two arguments: ptr.poke(p, v)")
3008
+ else:
3009
+ self._type_expr(args[0])
3010
+ self._type_expr(args[1])
3011
+ node._etype = T.VOID
3012
+ return T.VOID
3013
+ if api == "skip":
3014
+ if len(args) != 2:
3015
+ self._error(node, "ptr.skip requires two arguments: ptr.skip(p, n)")
3016
+ else:
3017
+ self._type_expr(args[0])
3018
+ self._type_expr(args[1])
3019
+ target = self._ptr_target(self._type_expr(args[0]))
3020
+ node._etype = T.Ptr(target if target is not None else T.TVar())
3021
+ return node._etype
3022
+ if api == "field":
3023
+ if len(args) != 2:
3024
+ self._error(node, 'ptr.field requires two arguments: ptr.field(s, "field_name")')
3025
+ node._etype = T.Ptr(T.TVar())
3026
+ return node._etype
3027
+ st = T.resolve(self._type_expr(args[0]))
3028
+ name_arg = args[1]
3029
+ # The first argument can be a struct value or a pointer to a struct
3030
+ acc = T.struct_field_access(st)
3031
+ if acc is None:
3032
+ if not isinstance(st, T.TVar):
3033
+ self._error(
3034
+ node,
3035
+ "ptr.field first argument must be a struct or a pointer to a struct",
3036
+ )
3037
+ node._etype = T.Ptr(T.TVar())
3038
+ return node._etype
3039
+ stc, levels = acc
3040
+ if (
3041
+ isinstance(name_arg, ast.Constant)
3042
+ and isinstance(name_arg.value, str)
3043
+ and name_arg.value in stc.fields
3044
+ ):
3045
+ node._etype = T.Ptr(stc.fields[name_arg.value])
3046
+ node._ptrapi_ptr_levels = levels
3047
+ return node._etype
3048
+ node._etype = T.Ptr(T.TVar())
3049
+ return node._etype
3050
+ # from_int / cast
3051
+ if len(args) != 2:
3052
+ self._error(node, f"ptr.{api} requires two arguments")
3053
+ node._etype = T.Ptr(T.TVar())
3054
+ return node._etype
3055
+ self._type_expr(args[0])
3056
+ elem = self._resolve_type_arg(args[1])
3057
+ if elem is None:
3058
+ self._error(
3059
+ args[1],
3060
+ f"ptr.{api} second argument must be a type name (e.g. int32)",
3061
+ )
3062
+ node._etype = T.Ptr(elem if elem is not None else T.TVar())
3063
+ return node._etype
3064
+
3065
+
3066
+ def _type_struct_ctor(self, node: ast.Call, st: T.Struct) -> None:
3067
+ """First pass: argument inference and basic validation for a struct constructor call."""
3068
+ if node.args and node.keywords:
3069
+ self._error(node, "struct constructor cannot mix positional and keyword arguments")
3070
+ return
3071
+ if any(k.arg is None for k in node.keywords):
3072
+ self._error(node, "struct constructor does not support ** unpacking")
3073
+ return
3074
+ fields = list(st.fields.keys())
3075
+ if node.args:
3076
+ if len(node.args) != len(fields):
3077
+ self._error(
3078
+ node,
3079
+ f"struct {st.name} expects {len(fields)} positional arguments, got {len(node.args)}",
3080
+ )
3081
+ return
3082
+ for arg in node.args:
3083
+ self._type_expr(arg)
3084
+ elif node.keywords:
3085
+ seen = set()
3086
+ for kw in node.keywords:
3087
+ if kw.arg not in st.fields:
3088
+ self._error(kw, f"struct {st.name} has no field named {kw.arg!r}")
3089
+ elif kw.arg in seen:
3090
+ self._error(kw, f"struct {st.name} field {kw.arg!r} specified more than once")
3091
+ else:
3092
+ seen.add(kw.arg)
3093
+ self._type_expr(kw.value)
3094
+ if len(seen) != len(fields):
3095
+ missing = [f for f in fields if f not in seen]
3096
+ self._error(node, f"struct {st.name} constructor must initialize all fields; missing: {', '.join(missing)}")
3097
+ else:
3098
+ # No-argument construction: zero initialization is valid (compiled on the C side as (T){0})
3099
+ return
3100
+
3101
+ def _type_copy_aggregate(self, node: ast.Call) -> T.Type:
3102
+ """Pass 1: roughly compute the type of copy_aggregate (must be exact, for typing global variables)."""
3103
+ if node.keywords:
3104
+ self._error(node, "copy_aggregate does not support keyword arguments")
3105
+ if len(node.args) != 1:
3106
+ self._error(node, "copy_aggregate takes one argument: copy_aggregate(value)")
3107
+ return T.TVar()
3108
+ at = self._type_expr(node.args[0])
3109
+ r = T.resolve(at)
3110
+ if not isinstance(r, (T.Struct, T.Array)):
3111
+ self._error(node.args[0], "copy_aggregate argument must be an aggregate")
3112
+ node._is_copy_aggregate = True
3113
+ node._etype = r
3114
+ return node._etype
3115
+
3116
+ def _type_mem_api_call(self, node: ast.Call, api: str) -> T.Type:
3117
+ """Pass 1: roughly compute the type of mem.xxx (must be exact, for typing global variables)."""
3118
+ node._mem_api = api
3119
+ if node.keywords:
3120
+ self._error(node, f"mem.{api} does not support keyword arguments")
3121
+ args = node.args
3122
+ if api == "arena_reset":
3123
+ if args:
3124
+ self._error(node, "mem.arena_reset takes no arguments")
3125
+ node._etype = T.VOID
3126
+ return T.VOID
3127
+ if api == "alloc":
3128
+ # mem.alloc(T, n): allocate space for n T values, return T*
3129
+ if len(args) != 2:
3130
+ self._error(node, "mem.alloc requires two arguments: mem.alloc(element_type, count)")
3131
+ return T.Ptr(T.TVar())
3132
+ elem = self._resolve_type_arg(args[0])
3133
+ if elem is None:
3134
+ self._error(args[0], "mem.alloc first argument must be a type name (e.g. int32)")
3135
+ elem = T.TVar()
3136
+ r = T.resolve(elem)
3137
+ if isinstance(r, (T.Struct, T.Array, T.Enum)) or r is T.STR or r is T.BYTES or r is T.VOID:
3138
+ self._error(
3139
+ args[0],
3140
+ "mem.alloc only supports fixed-width numeric types "
3141
+ "(use an array of structs on the stack instead)",
3142
+ )
3143
+ n_t = self._type_expr(args[1])
3144
+ if not (T.is_int(n_t) or T.is_bool(n_t)):
3145
+ self._error(args[1], "mem.alloc count must be an integer")
3146
+ node._memapi_elem = elem
3147
+ node._memapi_count = args[1]
3148
+ node._etype = T.Ptr(elem)
3149
+ return node._etype
3150
+ if api == "free":
3151
+ # mem.free(p): release and set the pointer to NULL
3152
+ if len(args) != 1:
3153
+ self._error(node, "mem.free requires one argument: mem.free(pointer)")
3154
+ return T.VOID
3155
+ pt = self._type_expr(args[0])
3156
+ if self._ptr_target(pt) is None:
3157
+ self._error(args[0], "mem.free argument must be a pointer")
3158
+ node._memapi_arg = args[0]
3159
+ node._etype = T.VOID
3160
+ return T.VOID
3161
+ # realloc
3162
+ if len(args) != 2:
3163
+ self._error(node, "mem.realloc requires two arguments: mem.realloc(pointer, count)")
3164
+ return T.Ptr(T.TVar())
3165
+ pt = self._type_expr(args[0])
3166
+ target = self._ptr_target(pt)
3167
+ if target is None:
3168
+ self._error(args[0], "mem.realloc first argument must be a pointer")
3169
+ target = T.TVar()
3170
+ n_t = self._type_expr(args[1])
3171
+ if not (T.is_int(n_t) or T.is_bool(n_t)):
3172
+ self._error(args[1], "mem.realloc count must be an integer")
3173
+ node._memapi_arg = args[0]
3174
+ node._memapi_count = args[1]
3175
+ node._memapi_elem = target
3176
+ node._etype = T.Ptr(target)
3177
+ return node._etype
3178
+
3179
+ def _type_c_expr_api_call(self, node: ast.Call, api: str) -> T.Type:
3180
+ """Pass 1: types of c.clz/ctz/popcount (exact, for typing global variables)."""
3181
+ node._c_expr_api = api
3182
+ if node.keywords:
3183
+ self._error(node, f"c.{api} does not support keyword arguments")
3184
+ args = node.args
3185
+ if len(args) != 1:
3186
+ self._error(node, f"c.{api} requires one integer argument: c.{api}(x)")
3187
+ node._etype = T.I32
3188
+ return T.I32
3189
+ at = self._type_expr(args[0])
3190
+ if not (T.is_int(at) or T.is_bool(at)):
3191
+ self._error(args[0], f"c.{api} argument must be an integer")
3192
+ # 64-bit operands use the __builtin_*ll variants on the C side; codegen chooses accordingly
3193
+ r = T.resolve(at)
3194
+ node._c_expr_ll = r in (T.I64, T.U64)
3195
+ node._etype = T.I32
3196
+ return T.I32
3197
+
3198
+ def _verify(self) -> None:
3199
+ for name, sym in self.globals.items():
3200
+ self._assert_resolved(sym.type, self.tree, f"global variable {name}")
3201
+ for fi in self.functions.values():
3202
+ for pname in fi.params:
3203
+ self._assert_resolved(
3204
+ fi.locals[pname].type,
3205
+ fi.node,
3206
+ f"parameter {pname} of function {fi.name}",
3207
+ )
3208
+ if self._header_mode:
3209
+ # header emits only prototypes: local variables in function bodies have zero emit and do not need typing;
3210
+ # parameter types belong to the signature and still need full resolution.
3211
+ continue
3212
+ for name, sym in fi.locals.items():
3213
+ self._assert_resolved(
3214
+ sym.type,
3215
+ fi.node,
3216
+ f"local variable {name} of function {fi.name}",
3217
+ )
3218
+
3219
+ def _assert_resolved(
3220
+ self, t: Optional[T.Type], node: ast.AST, what: str
3221
+ ) -> None:
3222
+ assert t is not None
3223
+ r = T.resolve(t)
3224
+ if isinstance(r, T.TVar):
3225
+ self._error(node, f"type of {what} cannot be inferred; add a type annotation")
3226
+ if isinstance(r, T.Ptr):
3227
+ self._assert_resolved(r.target, node, f"{what} pointer target")
3228
+ if isinstance(r, T.Array):
3229
+ self._assert_resolved(r.element, node, f"{what} array element")