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,2407 @@
1
+ """Typed C code generation.
2
+
3
+ The input is an AST that has already passed inference and validation (nodes carry symbols and type annotations),
4
+ The output is portable C99 source code: only the runtime functions and public types actually used by this program are inlined,
5
+ The output is self-contained.
6
+ """
7
+
8
+ import ast
9
+ import re
10
+ import sys
11
+ from typing import List, Optional, Set
12
+
13
+ from . import irtypes as T
14
+ from .checker import FuncInfo, ModuleInfo, Symbol
15
+ from . import runtime_lib
16
+ from . import preprocessor as pp
17
+ from .config import CompileConfig
18
+ from .errors import CompileError, Diagnostic
19
+ from .cgen_helpers import (
20
+ _make_static, _scalar, c_type, array_dims, _quals_prefix,
21
+ decl_str, c_abstract_decl, _cdecl_parts, zero_value,
22
+ c_string, byte_len, c_byte_array, i64_literal,
23
+ _char_ctype, _c_char_literal,
24
+ _COMPARE_OPS,
25
+ _ARENA_MANUAL_MARKER, _ARENA_MANUAL_END_MARKER,
26
+ _ARENA_FRAME_MARK, _ARENA_FRAME_RELEASE, _ARENA_FRAME_FLOOR,
27
+ _ARENA_LINE_PREFIX,
28
+ )
29
+
30
+ # First reserve a placeholder for the public-type section in the file header: only after the body,
31
+ # runtime closures, and literal arrays are all generated can the actual type names present in the output decide which definitions to emit.
32
+ _RUNTIME_TYPES_MARKER = "__EP_RUNTIME_TYPES__"
33
+ _RUNTIME_TYPE_NAME_RE = re.compile(r"\b(py_str|py_bytes|py_file)\b")
34
+ _C_STRING_LITERAL_RE = re.compile(r'"(?:[^"\\]|\\.)*"')
35
+
36
+
37
+ class CodeGen:
38
+ """Compile the checked AST and module info into C99 text; the output role is decided by configuration."""
39
+ def __init__(
40
+ self,
41
+ tree: ast.Module,
42
+ info: ModuleInfo,
43
+ filename: str,
44
+ config: "Optional[CompileConfig]" = None,
45
+ emit_line: bool = False,
46
+ ) -> None:
47
+ self.tree = tree
48
+ self.info = info
49
+ self.filename = filename
50
+ self.config = config or CompileConfig()
51
+ self.emit_line = emit_line
52
+ self.lines: List[str] = []
53
+ self.indent = 0
54
+ self.temp = 0
55
+ self._last_line = 0
56
+ # String literal registry: (text, C literal, byte count, code point count)
57
+ self.str_literals: List = []
58
+ self._lit_index: dict = {}
59
+ # Byte-string literal registry: (name, C initializer list, byte count)
60
+ self.bytes_literals: List = []
61
+ self._bytes_lit_index: dict = {}
62
+ # Whether the bytes type has been used (define py_bytes only when used)
63
+ self._uses_bytes = False
64
+ # The actual #include names emitted by this output (decided by user configuration; the compiler does not automatically add headers)
65
+ self._include_names: set = set()
66
+
67
+ # ---------------------------------------------------------------- output
68
+
69
+ def out(self, text: str = "") -> None:
70
+ self.lines.append((" " * self.indent + text) if text else "")
71
+
72
+ def mark(self, node: ast.AST) -> None:
73
+ if not self.emit_line:
74
+ return
75
+ lineno = getattr(node, "lineno", 0)
76
+ if lineno == self._last_line:
77
+ return
78
+ self._last_line = lineno
79
+ name = self.filename.replace("\\", "/").replace('"', '\\"')
80
+ self.out(f'#line {lineno} "{name}"')
81
+
82
+ def _emit_runtime_types(self) -> None:
83
+ """Reserve a placeholder for the public-type section in the file header; the definition content is back-filled by _finish_runtime_types."""
84
+ self.out(_RUNTIME_TYPES_MARKER)
85
+
86
+ def _finish_runtime_types(self) -> None:
87
+ """Back-fill definitions according to the public type names actually present in the final output.
88
+
89
+ The scan target is the complete body after runtime fragments and literal arrays have been inserted, so fragment
90
+ signatures' Str / Bytes / File are also counted. Each type carries its own guard,
91
+ when the types used by the .c and its paired .h differ, the side included later can still complete the missing definitions.
92
+ """
93
+ used: Set[str] = set()
94
+ for line in self.lines:
95
+ if line.strip() == _RUNTIME_TYPES_MARKER:
96
+ continue
97
+ clean = _C_STRING_LITERAL_RE.sub('""', line)
98
+ used.update(_RUNTIME_TYPE_NAME_RE.findall(clean))
99
+ rendered = runtime_lib.render_types(used)
100
+ for i, line in enumerate(self.lines):
101
+ if line.strip() != _RUNTIME_TYPES_MARKER:
102
+ continue
103
+ if rendered:
104
+ self.lines[i:i + 1] = rendered.split("\n")
105
+ else:
106
+ # When the type section is empty, collapse the consecutive blank lines before/after the placeholder into one, leaving no gap in the output
107
+ start = i
108
+ while start > 0 and not self.lines[start - 1].strip():
109
+ start -= 1
110
+ end = i + 1
111
+ while end < len(self.lines) and not self.lines[end].strip():
112
+ end += 1
113
+ self.lines[start:end] = [""]
114
+ break
115
+
116
+ def generate(self) -> str:
117
+ # Header mode: only emit a declaration set (types/constants/prototypes/guards); no main and no runtime.
118
+ if self.config.output_type == "header":
119
+ return self._generate_header()
120
+ # System headers: the includes from configuration are output after exclude subtractions and deduplication;
121
+ # the headers declared via c.include in the source code (user headers with "" and system headers with <>) are appended after.
122
+ base_inc = self.config.include
123
+ headers: List = [(h, True) for h in base_inc]
124
+ for header, system in self.info.includes:
125
+ headers.append((header, system))
126
+ if self.config.exclude:
127
+ headers = [(h, s) for h, s in headers if h not in self.config.exclude]
128
+ seen: set = set()
129
+ for header, system in headers:
130
+ if header in seen:
131
+ continue
132
+ seen.add(header)
133
+ self._include_names.add(header)
134
+ if system:
135
+ self.out(f"#include <{header}>")
136
+ else:
137
+ self.out(f'#include "{header}"')
138
+ self.out()
139
+
140
+ # Preprocessor directives and conditional blocks written by the user: emitted verbatim in source order, no additions or reordering
141
+ self._emit_pp_decls()
142
+
143
+ # Macro definitions (c.define): plain text substitution, no type; both H and C sides emit #define
144
+ self._emit_macros()
145
+ self.out()
146
+
147
+ # The public-type section (string / byte-string / file handle) is reserved first and back-filled at the end according to usage.
148
+ # Types come from runtime_lib -- the single source of truth for the runtime; the generated output carries no comments.
149
+ self._emit_runtime_types()
150
+ self.out()
151
+
152
+ # Aggregate type definitions (typedef struct / typedef union)
153
+ # External types (c.extern_type) have their definition authority in the header file; zero emit here.
154
+ self._emit_type_defs()
155
+
156
+ # Enum definitions (compiled to C typedef enum)
157
+ enums = [
158
+ sym for sym in self.info.scope.values()
159
+ if sym.kind == "type" and isinstance(T.resolve(sym.type), T.Enum)
160
+ ]
161
+ if enums:
162
+ for sym in enums:
163
+ en = T.resolve(sym.type)
164
+ assert isinstance(en, T.Enum)
165
+ self.out("typedef enum {")
166
+ self.indent += 1
167
+ for mname, mvalue in en.members.items():
168
+ self.out(f"{en.c_name}_{mname} = {mvalue},")
169
+ self.indent -= 1
170
+ self.out(f"}} {en.c_name};")
171
+ self.out()
172
+
173
+ # Type aliases typedef (c.typedef(Ptr[T]) / c.typedef(Func[[...], R])):
174
+ # Like struct/enum they are type declarations and must appear before the variables/functions that reference them.
175
+ aliases = [s for s in self.info.scope.values() if s.kind == "ptr_alias"]
176
+ if aliases:
177
+ for s in aliases:
178
+ self.out(self._alias_typedef(s))
179
+ self.out()
180
+
181
+ # Function prototypes must precede global definitions: a static object's initializer list may contain function names
182
+ # (interrupt vector table), and C requires those names to be declared beforehand.
183
+ if self.info.functions:
184
+ normal = [fi for fi in self.info.functions.values() if not fi.is_extern]
185
+ externs = [fi for fi in self.info.functions.values() if fi.is_extern]
186
+ if normal:
187
+ for fi in normal:
188
+ self.out(self._prototype(fi) + ";")
189
+ self.out()
190
+ if externs:
191
+ for fi in externs:
192
+ self.out(self._extern_prototype(fi) + ";")
193
+ self.out()
194
+
195
+ # Static array definition for string literals: literals are registered only when expressions are generated,
196
+ # so here we can only reserve a placeholder and back-fill after all function bodies and main are generated (otherwise the definition would be lost).
197
+ literal_insert_at = len(self.lines)
198
+
199
+ real_globals = [
200
+ sym
201
+ for sym in self.info.globals.values()
202
+ if sym.kind != "ptr_alias" # Type aliases are pure type-level products and occupy no storage
203
+ ]
204
+ if real_globals:
205
+ for sym in real_globals:
206
+ assert sym.type is not None
207
+ if sym.static_object:
208
+ # Real static C objects (valueless globals / segment-named globals): emitted directly in the file header
209
+ # definition; they do not go through the arena pointer and are not assigned in main.
210
+ decl = decl_str(sym.type, sym.c_name, sym.quals)
211
+ attr = (
212
+ f' __attribute__((section({c_string(sym.section)}), used))'
213
+ if sym.section else ""
214
+ )
215
+ init_node = self._global_init_node(sym)
216
+ if init_node is None:
217
+ self.out(f"static {decl}{attr};")
218
+ else:
219
+ self.out(
220
+ f"static {decl}{attr} = "
221
+ f"{self._const_init_value(sym, init_node)};"
222
+ )
223
+ continue
224
+ if "const" in sym.quals and sym.init_node is not None:
225
+ # const global variables must be statically initialized at the point of declaration
226
+ init = self._const_init_value(sym, sym.init_node)
227
+ self.out(
228
+ f"static {decl_str(sym.type, sym.c_name, sym.quals)} = {init};"
229
+ )
230
+ continue
231
+ if self._is_ref_type(sym.type):
232
+ # Aggregate type: a block of compile-time fixed-size static object + a pointer to it.
233
+ # The length is derived from literals / make_array(T, N) in the source code, computed by the compiler;
234
+ # it does not enter the arena, does not call malloc, and its address is valid for the entire program lifetime.
235
+ obj = self._storage_name(sym.c_name)
236
+ self.out(f"static {decl_str(sym.type, obj, sym.quals)};")
237
+ init = f"&{obj}" if isinstance(T.resolve(sym.type), T.Struct) else obj
238
+ self.out(
239
+ f"static {self._ref_decl(sym.type, sym.c_name, sym.quals)} = {init};"
240
+ )
241
+ continue
242
+ self.out(
243
+ f"static {decl_str(sym.type, sym.c_name, sym.quals)} = "
244
+ f"{zero_value(sym.type)};"
245
+ )
246
+ self.out()
247
+
248
+ # Runtime functions must be defined before user functions and main to avoid implicit declarations.
249
+ # Record the insertion point first, then insert it back after user functions and main are generated and the closure is computed.
250
+ runtime_insert_at = len(self.lines)
251
+
252
+ for fi in self.info.functions.values():
253
+ if fi.is_extern:
254
+ continue # External functions are only declared, no function body is generated
255
+ self._current_func = fi
256
+ self._emit_function(fi)
257
+
258
+ if self.config.output_type == "library":
259
+ # A library output has no entry point, so top-level executable statements have nowhere to go: reject at compile-time rather than silently dropping code
260
+ body = self._main_body_stmts()
261
+ if body:
262
+ first = body[0]
263
+ raise CompileError([Diagnostic(
264
+ message=("library output cannot contain top-level statements; "
265
+ "move them into a function"),
266
+ line=getattr(first, "lineno", 0),
267
+ filename=self.filename,
268
+ code="config",
269
+ )])
270
+ else:
271
+ self._emit_main()
272
+
273
+ # Scan the runtime functions actually used in the generated body, compute the transitive dependency closure, and inline as needed
274
+ used = self._collect_used_runtime()
275
+ closure = runtime_lib.collect(used)
276
+ needs_arena = "__arena__" in closure
277
+
278
+ # Decide the switching of the two pools and each function's frame-based watermark rollback based on whether the arena is needed.
279
+ # Placeholders are replaced uniformly here; when the arena is not needed, the entire line is removed, leaving no trace in the output.
280
+ # The automatic pool watermark py_arena_lo is rolled back only by function frames; the manual pool py_arena_hi is only
281
+ # zeroed by mem.arena_reset() explicitly written in the user source code; the two do not interfere with each other. The compiler does not automatically
282
+ # reset, nor does it treat main as a scope -- pool ownership is determined solely by the position in the user source code.
283
+ new_lines = []
284
+ for line in self.lines:
285
+ stripped = line.strip()
286
+ if stripped.startswith(_ARENA_LINE_PREFIX):
287
+ if needs_arena:
288
+ indent = line[: len(line) - len(line.lstrip())]
289
+ new_lines.append(
290
+ indent + "py_arena_line = "
291
+ + stripped[len(_ARENA_LINE_PREFIX):] + ";"
292
+ )
293
+ continue
294
+ if stripped in (
295
+ _ARENA_MANUAL_MARKER, _ARENA_MANUAL_END_MARKER,
296
+ _ARENA_FRAME_MARK, _ARENA_FRAME_RELEASE, _ARENA_FRAME_FLOOR,
297
+ ):
298
+ if needs_arena:
299
+ indent = line[: len(line) - len(line.lstrip())]
300
+ if stripped == _ARENA_MANUAL_MARKER:
301
+ new_lines.append(indent + "py_arena_manual = 1;")
302
+ elif stripped == _ARENA_MANUAL_END_MARKER:
303
+ new_lines.append(indent + "py_arena_manual = 0;")
304
+ elif stripped == _ARENA_FRAME_MARK:
305
+ new_lines.append(
306
+ indent + "int __ep_frame_manual = py_arena_manual;"
307
+ )
308
+ new_lines.append(indent + "py_arena_manual = 0;")
309
+ new_lines.append(
310
+ indent + "size_t __ep_frame_mark = py_arena_lo;"
311
+ )
312
+ new_lines.append(
313
+ indent + "size_t __ep_frame_floor = __ep_frame_mark;"
314
+ )
315
+ elif stripped == _ARENA_FRAME_FLOOR:
316
+ new_lines.append(
317
+ indent + "__ep_frame_floor = py_arena_lo;"
318
+ )
319
+ else:
320
+ new_lines.append(
321
+ indent + "py_arena_lo = __ep_frame_floor;"
322
+ )
323
+ new_lines.append(
324
+ indent + "py_arena_manual = __ep_frame_manual;"
325
+ )
326
+ continue
327
+ new_lines.append(line)
328
+ self.lines = new_lines
329
+
330
+ # Build the runtime section and insert it after "function declarations" and before user function definitions.
331
+ # Runtime fragments carry no #include of their own: all headers in the output come only from the user's
332
+ # include layer (top of the file); the compiler does not automatically add headers.
333
+ runtime_block: List[str] = []
334
+ if closure:
335
+ for name in closure:
336
+ code = _make_static(runtime_lib.render_snippet(
337
+ name, self.config.manual_cap, self.config.auto_cap
338
+ ))
339
+ runtime_block.extend(code.split("\n"))
340
+ runtime_block.append("")
341
+ self.lines = (
342
+ self.lines[:runtime_insert_at]
343
+ + runtime_block
344
+ + self.lines[runtime_insert_at:]
345
+ )
346
+
347
+ # Back-fill the static array definition for string literals (literals are all registered by now)
348
+ if self.str_literals:
349
+ literal_block: List[str] = []
350
+ for name, clit, blen, clen in self.str_literals:
351
+ literal_block.append(f"static const char {name}[] = {clit};")
352
+ literal_block.append("")
353
+ self.lines = (
354
+ self.lines[:literal_insert_at]
355
+ + literal_block
356
+ + self.lines[literal_insert_at:]
357
+ )
358
+
359
+ # Back-fill the static array definition for byte-string literals
360
+ if self.bytes_literals:
361
+ bytes_block: List[str] = []
362
+ for name, carr, blen in self.bytes_literals:
363
+ bytes_block.append(
364
+ f"static const uint8_t {name}[{max(blen, 1)}] = {carr};"
365
+ )
366
+ bytes_block.append("")
367
+ self.lines = (
368
+ self.lines[:literal_insert_at]
369
+ + bytes_block
370
+ + self.lines[literal_insert_at:]
371
+ )
372
+
373
+ # After public types are back-filled according to the final body, check again against the same body whether system headers are complete.
374
+ self._finish_runtime_types()
375
+
376
+ # If a system header actually used by the output is not in the user configuration, only warn and continue generating.
377
+ # Do not add #include, do not block, do not change the exit code; the .h mode has no runtime function body, so this path is not taken.
378
+ self._warn_missing_headers(closure, used)
379
+
380
+ return "\n".join(self.lines) + "\n"
381
+
382
+ def _warn_missing_headers(self, closure: List[str], used: Set[str]) -> None:
383
+ """If a system header used in the output body is excluded/omitted by the user, only give a hint and continue generating.
384
+
385
+ The compiler does not add #include, does not error, does not change the exit code; the hint is written to stderr,
386
+ and does not pollute the main output. Header mode has no runtime body, so this method is not called.
387
+ """
388
+ required = runtime_lib.required_headers(self.lines)
389
+ missing = sorted(h for h in required if h not in self._include_names)
390
+ if not missing:
391
+ return
392
+ public_used = sorted(n for n in used if n.startswith("py_"))
393
+ if public_used:
394
+ fallback = public_used[0]
395
+ elif used:
396
+ fallback = sorted(used)[0]
397
+ else:
398
+ fallback = "runtime"
399
+ for header in missing:
400
+ snippet = None
401
+ symbols: List[str] = []
402
+ # Take only one representative fragment: the one that hits the most symbols of that header, for maximum information;
403
+ # In case of ties, take the earlier one in the closure (dependency order is stable).
404
+ for name in closure:
405
+ hits = runtime_lib.SNIPPET_HEADERS.get(name, {}).get(header)
406
+ if hits and len(hits) > len(symbols):
407
+ snippet = runtime_lib.snippet_display(name)
408
+ symbols = hits
409
+ if snippet is None:
410
+ snippet = fallback
411
+ if not symbols:
412
+ symbols = required[header]
413
+ print(
414
+ f"warning: generated code requires <{header}> "
415
+ f"(runtime snippet {snippet} uses {'/'.join(symbols)}),"
416
+ f"but it is not in the include set (excluded or omitted),"
417
+ f"add it to [tool.embeddedpy] include, or remove it from exclude.",
418
+ file=sys.stderr,
419
+ )
420
+
421
+ # ------------------------------------------------ aggregate type definitions (shared by .c / .h)
422
+ def _emit_type_defs(self) -> None:
423
+ """Emit struct / union typedefs; the two outputs share the same assembly logic.
424
+
425
+ The bit-field's backing integer type, packed attribute, and trailing anonymous padding are all determined here by @c.word(W)
426
+ The user only writes the bit width of Bits[N] and a single total width, and does not write the storage type or padding fields.
427
+ """
428
+ structs = [
429
+ sym for sym in self.info.scope.values()
430
+ if sym.kind == "type"
431
+ and isinstance(T.resolve(sym.type), T.Struct)
432
+ and not isinstance(T.resolve(sym.type), T.ExternType)
433
+ ]
434
+ for sym in structs:
435
+ st = T.resolve(sym.type)
436
+ assert isinstance(st, T.Struct)
437
+ keyword = "union" if st.is_union else "struct"
438
+ sattrs: List[str] = []
439
+ if st.packed:
440
+ sattrs.append("packed")
441
+ if st.align:
442
+ sattrs.append(f"aligned({st.align})")
443
+ attr = (" __attribute__((" + ", ".join(sattrs) + "))") if sattrs else ""
444
+ self.out(f"typedef {keyword}{attr} {{")
445
+ self.indent += 1
446
+ used = 0
447
+ for fname, ftype in st.fields.items():
448
+ r = T.resolve(ftype)
449
+ is_bits = isinstance(r, T.Bits)
450
+ if is_bits:
451
+ # union members share storage; the bit count takes the widest member; struct accumulates bit by bit.
452
+ used = max(used, r.width) if st.is_union else used + r.width
453
+ self.out(f"{decl_str(ftype, fname, bitfield=is_bits)};")
454
+ if st.word_bits and st.word_bits > used:
455
+ self.out(f"uint{st.word_bits}_t : {st.word_bits - used};")
456
+ self.indent -= 1
457
+ self.out(f"}} {st.c_name};")
458
+
459
+ # ---------------------------------------------------------- header mode
460
+ # The same source code, when output_type="header" is configured, is compiled into a header file: it contains only a declaration set, no main,
461
+ # no runtime function body. Struct/enum/alias typedefs, constant #defines, function prototypes,
462
+ # include guards are all present; reference types (struct/array) global variables are declared extern.
463
+ def _generate_header(self) -> str:
464
+ self.lines = []
465
+ self.indent = 0
466
+
467
+ # System headers + user headers (consistent with .c mode)
468
+ base_inc = self.config.include
469
+ headers: List = [(h, True) for h in base_inc]
470
+ for header, system in self.info.includes:
471
+ headers.append((header, system))
472
+ if self.config.exclude:
473
+ headers = [(h, s) for h, s in headers if h not in self.config.exclude]
474
+ seen: set = set()
475
+ for header, system in headers:
476
+ if header in seen:
477
+ continue
478
+ seen.add(header)
479
+ self._include_names.add(header)
480
+ if system:
481
+ self.out(f"#include <{header}>")
482
+ else:
483
+ self.out(f'#include "{header}"')
484
+ self.out()
485
+
486
+ guard = self._header_guard()
487
+ self.out(f"#ifndef {guard}")
488
+ self.out(f"#define {guard}")
489
+ self.out()
490
+
491
+ # Preprocessor directives and conditional declaration blocks written by the user are emitted verbatim in source order
492
+ self._emit_pp_decls()
493
+
494
+ # The public-type section is reserved first; after the declaration set is collected, it is back-filled with actually used types to keep the header self-contained
495
+ self._emit_runtime_types()
496
+ self.out()
497
+
498
+ # Aggregate type typedef (external types c.extern_type have their definition authority externally, zero emit)
499
+ self._emit_type_defs()
500
+ self.out()
501
+
502
+ # Enum typedef
503
+ enums = [
504
+ s for s in self.info.scope.values()
505
+ if s.kind == "type" and isinstance(T.resolve(s.type), T.Enum)
506
+ ]
507
+ for s in enums:
508
+ en = T.resolve(s.type)
509
+ assert isinstance(en, T.Enum)
510
+ self.out("typedef enum {")
511
+ self.indent += 1
512
+ for mname, mvalue in en.members.items():
513
+ self.out(f"{en.c_name}_{mname} = {mvalue},")
514
+ self.indent -= 1
515
+ self.out(f"}} {en.c_name};")
516
+ self.out()
517
+
518
+ # Type alias typedef (Ptr[T] / Func[[...], R])
519
+ aliases = [s for s in self.info.scope.values() if s.kind == "ptr_alias"]
520
+ for s in aliases:
521
+ self.out(self._alias_typedef(s))
522
+ if aliases:
523
+ self.out()
524
+
525
+ # Macro definitions (c.define): both H and C sides emit #define
526
+ self._emit_header_macros()
527
+
528
+ # External constant declarations (c.extern_const): only emit extern const, without value
529
+ self._emit_header_extern_consts()
530
+
531
+ # External variable declarations (c.extern_var): only emit extern, without value
532
+ self._emit_header_extern_vars()
533
+
534
+ # Local constant definitions (TIMEOUT: const[int32] = 100): static const with value
535
+ self._emit_header_local_consts()
536
+
537
+ # Function prototypes (without static; extern functions keep their extern declaration)
538
+ if self.info.functions:
539
+ externs = [fi for fi in self.info.functions.values() if fi.is_extern]
540
+ normal = [fi for fi in self.info.functions.values() if not fi.is_extern]
541
+ if normal:
542
+ for fi in normal:
543
+ self.out(self._prototype(fi, static=False) + ";")
544
+ self.out()
545
+ if externs:
546
+ for fi in externs:
547
+ self.out(self._extern_prototype(fi) + ";")
548
+ self.out()
549
+
550
+ self._finish_runtime_types()
551
+ self.out("#endif")
552
+ return "\n".join(self.lines) + "\n"
553
+
554
+ def _header_guard(self) -> str:
555
+ """The guard macro name is derived from the output name; the algorithm is centralized in CompileConfig."""
556
+ return self.config.header_guard(self.filename)
557
+
558
+ def _alias_typedef(self, sym: "Symbol") -> str:
559
+ """Restore a type alias symbol to C typedef text.
560
+
561
+ PtrTypeValue(T) -> Ptr[T]; the rest (Ptr[Func], Ptr[ExternFuncPtr]) are kept as-is.
562
+ """
563
+ t = T.resolve(sym.type)
564
+ if isinstance(t, T.PtrTypeValue):
565
+ real = T.Ptr(t.target)
566
+ elif isinstance(t, T.Ptr):
567
+ real = t
568
+ else:
569
+ real = t
570
+ return f"typedef {decl_str(real, sym.c_name)};"
571
+
572
+ @staticmethod
573
+ def _const_macro_value(value: object) -> str:
574
+ if isinstance(value, bool):
575
+ return "1" if value else "0"
576
+ if isinstance(value, int):
577
+ return str(value)
578
+ if isinstance(value, float):
579
+ return repr(value)
580
+ if isinstance(value, str):
581
+ return c_string(value)
582
+ return str(value)
583
+
584
+ def _all_decls(self) -> "List[Symbol]":
585
+ """Register named declarations in scope + bare calls (no LHS)."""
586
+ return list(self.info.scope.values()) + list(self.info.decls)
587
+
588
+ def _emit_macros(self) -> None:
589
+ """Write the c.define macro as ``#define NAME value`` (shared by H and C sides)."""
590
+ for s in self._all_decls():
591
+ if s.kind == "macro":
592
+ self.out(f"#define {s.c_name} {self._const_macro_value(s.macro_value)}")
593
+
594
+ def _emit_header_macros(self) -> None:
595
+ """In h mode, write the c.define macro into the header file: ``#define NAME value``.
596
+
597
+ Macros and const are independent -- macros are plain text substitution with no type, and both H and C sides emit them.
598
+ """
599
+ macros = [s for s in self._all_decls() if s.kind == "macro"]
600
+ if not macros:
601
+ return
602
+ self._emit_macros()
603
+ self.out()
604
+
605
+ def _emit_header_extern_consts(self) -> None:
606
+ """In h mode, emit ``extern const <T> NAME;`` for c.extern_const (without value).
607
+
608
+ C mode does not emit (the definition is provided by the external library); the name is taken verbatim from the C name in the header.
609
+ """
610
+ consts = [s for s in self._all_decls() if s.kind == "extern_const"]
611
+ if not consts:
612
+ return
613
+ for s in consts:
614
+ assert s.type is not None
615
+ # An external header may define a same-named constant as an object-like macro; wrap the declaration with #ifndef,
616
+ # so the header can be included under both definition styles without colliding into duplicate definitions.
617
+ self.out(f"#ifndef {s.c_name}")
618
+ self.out(f"extern {decl_str(s.type, s.c_name, s.quals)};")
619
+ self.out("#endif")
620
+ self.out()
621
+
622
+ def _emit_header_extern_vars(self) -> None:
623
+ """In h mode, emit ``extern <T> NAME;`` for c.extern_var (without value).
624
+
625
+ C mode does not emit (the definition is provided by an external translation unit); the name is taken verbatim from the external C variable name.
626
+ """
627
+ vars_ = [s for s in self._all_decls() if s.kind == "extern_var"]
628
+ if not vars_:
629
+ return
630
+ for s in vars_:
631
+ assert s.type is not None
632
+ self.out(f"extern {decl_str(s.type, s.c_name, s.quals)};")
633
+ self.out()
634
+
635
+ def _emit_header_local_consts(self) -> None:
636
+ """In h mode, emit ``static const <T> NAME = value;`` for ``NAME: const[T] = value``.
637
+
638
+ This is exactly consistent with the c mode output (dual-track semantics unified); the value comes from the literal assignment in the source code.
639
+ Ordinary global variables (not annotated const) are module-private and do not enter the header.
640
+ """
641
+ consts = [
642
+ s for s in self.info.scope.values()
643
+ if s.kind == "global" and "const" in s.quals
644
+ ]
645
+ if not consts:
646
+ return
647
+ for s in consts:
648
+ assert s.type is not None
649
+ value = self._const_init_literal(s.name)
650
+ if value is None:
651
+ # The c mode already validated that const must have a compile-time literal initializer; skip here
652
+ continue
653
+ self.out(
654
+ f"static {decl_str(s.type, s.c_name, s.quals)} = {value};"
655
+ )
656
+ self.out()
657
+
658
+ def _global_init_node(self, sym: "Symbol") -> "Optional[ast.AST]":
659
+ """Find the initializer expression written for this global in the top-level declarations (None if absent)."""
660
+ for stmt in self.tree.body:
661
+ if isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 \
662
+ and isinstance(stmt.targets[0], ast.Name) \
663
+ and stmt.targets[0].id == sym.name:
664
+ return stmt.value
665
+ if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name) \
666
+ and stmt.target.id == sym.name:
667
+ return stmt.value
668
+ return None
669
+
670
+ def _const_init_literal(self, name: str) -> "Optional[str]":
671
+ """Find the literal value of ``NAME = <literal>`` / ``NAME: T = <literal>`` from the top-level statements in the source code."""
672
+ for stmt in self.tree.body:
673
+ if isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 \
674
+ and isinstance(stmt.targets[0], ast.Name) \
675
+ and stmt.targets[0].id == name:
676
+ if isinstance(stmt.value, ast.Constant):
677
+ return self._const_macro_value(stmt.value.value)
678
+ elif isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name) \
679
+ and stmt.target.id == name and stmt.value is not None \
680
+ and isinstance(stmt.value, ast.Constant):
681
+ return self._const_macro_value(stmt.value.value)
682
+ return None
683
+
684
+ _PY_NAME_RE = re.compile(r"\b(py_[a-z0-9_]+|count_codepoints|str_from_buffer|format_double|block_data)\b")
685
+
686
+ def _collect_used_runtime(self) -> Set[str]:
687
+ used: Set[str] = set()
688
+ for line in self.lines:
689
+ for m in self._PY_NAME_RE.finditer(line):
690
+ used.add(m.group(1))
691
+ return used
692
+
693
+ def _prototype(self, fi: FuncInfo, static: bool = True, definition: bool = False) -> str:
694
+ rt = self._ref_c_type(fi.ret)
695
+ params: List[str] = []
696
+ for name in fi.params:
697
+ t = self._param_type(fi, name)
698
+ r = T.resolve(t)
699
+ cname = fi.locals[name].c_name
700
+ quals = fi.locals[name].quals
701
+ if isinstance(r, T.Array):
702
+ # Fixed-width array parameters decay to pointers by C convention, and a length parameter is implicitly appended
703
+ params.append(f"{_quals_prefix(quals)}{c_type(r.element)} *{cname}")
704
+ params.append(f"int64_t {cname}_len")
705
+ else:
706
+ # Function pointer parameters must go through decl_str: c_type gives a "type expression"
707
+ # (int32_t (*)(int32_t, int32_t)), but a declaration requires parentheses hugging the variable name
708
+ # (int32_t (*v_f)(int32_t, int32_t)), otherwise C would read it as a function.
709
+ # Struct/array are compiled to pointers by reference semantics (T *name).
710
+ params.append(self._ref_decl(t, cname, quals))
711
+ if not params:
712
+ params = ["void"]
713
+ parts: List[str] = []
714
+ if static and not fi.is_weak and not fi.export_c_name:
715
+ # Both weak symbols and @c.export symbols must have external linkage
716
+ # (C: "weak declaration cannot have internal linkage")
717
+ parts.append("static")
718
+ if fi.is_inline:
719
+ parts.append("inline")
720
+ attrs: List[str] = []
721
+ if fi.section:
722
+ attrs.append(f"section({c_string(fi.section)})")
723
+ if fi.is_weak:
724
+ attrs.append("weak")
725
+ if fi.align:
726
+ attrs.append(f"aligned({fi.align})")
727
+ if fi.visibility:
728
+ attrs.append(f'visibility("{fi.visibility}")')
729
+ if fi.export_c_name and definition:
730
+ # An exported entry point is often not referenced by this translation unit; "used" prevents the linker from discarding it
731
+ attrs.append("used")
732
+ if attrs:
733
+ parts.append("__attribute__((" + ", ".join(attrs) + "))")
734
+ prefix = " ".join(parts) + " " if parts else ""
735
+ cname = fi.export_c_name or f"f_{fi.name}"
736
+ return f"{prefix}{rt} {cname}({', '.join(params)})"
737
+
738
+ def _extern_prototype(self, fi: FuncInfo) -> str:
739
+ """Declaration of an external C function: extern <ret> <C name>(<params>);"""
740
+ rt = self._ref_c_type(fi.ret)
741
+ params: List[str] = []
742
+ for name in fi.params:
743
+ t = self._param_type(fi, name)
744
+ r = T.resolve(t)
745
+ cname = fi.locals[name].c_name
746
+ if isinstance(r, T.Array):
747
+ # Fixed-width array parameters decay to pointers by C convention, and a length parameter is implicitly appended
748
+ params.append(f"{c_type(r.element)} *{cname}")
749
+ params.append(f"int64_t {cname}_len")
750
+ else:
751
+ # Function pointer parameters must go through decl_str (same reason as _prototype).
752
+ # Struct/array are compiled to pointers by reference semantics (T *name).
753
+ params.append(self._ref_decl(t, cname))
754
+ if not params:
755
+ params = ["void"]
756
+ attrs: List[str] = []
757
+ if fi.section:
758
+ attrs.append(f"section({c_string(fi.section)})")
759
+ if fi.is_weak:
760
+ attrs.append("weak")
761
+ if fi.align:
762
+ attrs.append(f"aligned({fi.align})")
763
+ if fi.visibility:
764
+ attrs.append(f'visibility("{fi.visibility}")')
765
+ attr = f"__attribute__((" + ", ".join(attrs) + ")) " if attrs else ""
766
+ return f"extern {attr}{rt} {fi.extern_c_name}({', '.join(params)})"
767
+
768
+ def _param_type(self, fi: FuncInfo, name: str) -> T.Type:
769
+ t = fi.locals[name].type
770
+ assert t is not None
771
+ return t
772
+
773
+ # ---------------------------------------------------------------- reference representation
774
+ # Struct / array are uniformly "pointer-backed" on the C side: the variable is a pointer to a block of compile-time fixed
775
+ # size static/automatic object. The pointer is only used to unify the syntax of field access, indexing, and function argument passing;
776
+ # whole aggregate assignment (b = a) is rejected by the two-pass checker; independent copies go through copy_aggregate.
777
+ @staticmethod
778
+ def _is_ref_type(t: T.Type) -> bool:
779
+ r = T.resolve(t)
780
+ return isinstance(r, (T.Struct, T.Array))
781
+
782
+ @staticmethod
783
+ def _storage_name(c_name: str) -> str:
784
+ """The name of the compile-time fixed-storage object behind a reference-type variable."""
785
+ return f"{c_name}_obj"
786
+
787
+ def _ref_c_type(self, t: T.Type) -> str:
788
+ """Return type as a C type name; struct/array decay to pointers.
789
+
790
+ Multi-dimensional arrays must preserve the inner dimension (T (*)[N]), otherwise grid[i][j] would decay to one dimension
791
+ indexing; in C, applying two [] to int32_t* is illegal or yields a wrong value.
792
+ """
793
+ r = T.resolve(t)
794
+ if isinstance(r, T.Struct):
795
+ return f"{r.c_name} *"
796
+ if isinstance(r, T.Array):
797
+ # A one-dimensional array decays to "pointer to element"; multi-dimensional arrays preserve the inner dimension;
798
+ # assembled with a generic declarator, so even a function-pointer element yields void (**)(void).
799
+ return c_abstract_decl(T.Ptr(T.resolve(r.element)))
800
+ return c_type(t)
801
+
802
+ def _ref_decl(self, t: T.Type, name: str, quals: Optional[List[str]] = None) -> str:
803
+ """Declaration; struct/array compiled to pointers (T *name / T (*name)[N])."""
804
+ r = T.resolve(t)
805
+ if isinstance(r, T.Struct):
806
+ return decl_str(T.Ptr(r), name, quals)
807
+ if isinstance(r, T.Array):
808
+ return decl_str(T.Ptr(T.resolve(r.element)), name, quals)
809
+ return decl_str(t, name, quals)
810
+
811
+ def _new_temp(self, prefix: str) -> str:
812
+ self.temp += 1
813
+ return f"__{prefix}{self.temp}"
814
+
815
+ def _ref_field_levels(self, base_node: ast.AST, levels: int) -> int:
816
+ """Add the implicit layer of pointer of a "reference variable" during field access.
817
+
818
+ A struct/array variable is a pointer on the C side, so s.f must generate s->f. Only recognize Name:
819
+ for nested field s.inner.x, the outer base is an Attribute (the result is a struct-value field),
820
+ and must not add it. A base that is originally Ptr[Struct] gets its level count from the checker; its symbol
821
+ type is Ptr rather than a reference type, so it is not mistakenly added either.
822
+ """
823
+ if isinstance(base_node, ast.Name):
824
+ sym = getattr(base_node, "_symbol", None)
825
+ if sym is not None and sym.type is not None and self._is_ref_type(sym.type):
826
+ return levels + 1
827
+ return levels
828
+
829
+ def _deref_if_ref(self, code: str, t: T.Type) -> str:
830
+ """Convert a reference-type value expression (pointer) into a value, used for positions such as struct fields / array elements."""
831
+ if self._is_ref_type(t):
832
+ return f"(*({code}))"
833
+ return code
834
+
835
+ @staticmethod
836
+ def _ref_rhs_addr(code: str, value: ast.AST) -> str:
837
+ """When aliasing on assignment, convert the "value-position" source into an address.
838
+
839
+ A struct field / array element is an inlined value on the C side (e.g., g_r->origin is a Point),
840
+ while a reference variable is a pointer (Point*). Taking & yields the address of that inlined memory;
841
+ the referenced object has static storage duration and does not dangle.
842
+ """
843
+ if isinstance(value, (ast.Attribute, ast.Subscript)):
844
+ return f"(&({code}))"
845
+ return code
846
+
847
+ @staticmethod
848
+ def _type_align(t: T.Type) -> int:
849
+ """The alignment byte count required by the type (must be satisfied when carving blocks from the arena).
850
+
851
+ For an aggregate type declared with ``@c.aligned(N)``, the arena must be aligned to N, otherwise accessing
852
+ that object would be an unaligned access (UB in C, crashes directly on Zig/ARM).
853
+ """
854
+ r = T.resolve(t)
855
+ if isinstance(r, T.Struct):
856
+ return max(8, r.align)
857
+ if isinstance(r, T.Array):
858
+ return CodeGen._type_align(r.element)
859
+ return 8
860
+
861
+ def _arena_alloc(self, size_expr: str, align: int, line: int = 0) -> str:
862
+ """Arena allocation expression: choose the aligned variant as needed.
863
+
864
+ size_expr is passed in the literal form at the call site; here we only decide
865
+ whether to use the ordinary 8-byte-aligned version or the stronger version per the type's alignment requirement.
866
+ """
867
+ if align > 8:
868
+ return f"py_arena_alloc_aligned({size_expr}, {align}u, {line})"
869
+ return f"py_arena_alloc({size_expr}, {line})"
870
+
871
+ @staticmethod
872
+ def _has_flexible_array(st: T.Struct) -> bool:
873
+ """Whether a struct contains a member array of unknown length (C99 flexible array member)."""
874
+ for ft in st.fields.values():
875
+ r = T.resolve(ft)
876
+ if isinstance(r, T.Array) and r.length < 0:
877
+ return True
878
+ return False
879
+
880
+ def _emit_struct_ctor(
881
+ self, target_ptr: str, st: T.Struct, node: ast.Call, declare: bool = False
882
+ ) -> None:
883
+ """Write a struct construction into the compile-time fixed-storage object pointed to by target_ptr.
884
+
885
+ declare=True is for temporary objects in expression context: declare the object and pointer first.
886
+ The target object is already allocated by a variable declaration; never call arena / malloc here.
887
+ """
888
+ if declare:
889
+ obj = self._storage_name(target_ptr)
890
+ self.out(f"static {st.c_name} {obj};")
891
+ self.out(f"{st.c_name} *{target_ptr} = &{obj};")
892
+ flexible = self._has_flexible_array(st)
893
+ field_names = list(st.fields.keys())
894
+ if node.args:
895
+ parts = []
896
+ for i, a in enumerate(node.args):
897
+ ft = st.fields[field_names[i]]
898
+ parts.append(
899
+ self._deref_if_ref(self._cast(self.expr(a), a._etype, ft), ft)
900
+ )
901
+ if flexible:
902
+ # When a flexible array member is present, C does not allow whole (S){...} initialization; the static object is already
903
+ # zero-initialized at the declaration site, so here we only write the non-flexible fields one by one.
904
+ for i, part in enumerate(parts):
905
+ name = field_names[i]
906
+ r = T.resolve(st.fields[name])
907
+ if isinstance(r, T.Array) and r.length < 0:
908
+ continue
909
+ self.out(f"{target_ptr}->{name} = {part};")
910
+ else:
911
+ self.out(f"*{target_ptr} = ({st.c_name}){{{', '.join(parts)}}};")
912
+ return
913
+ if not flexible:
914
+ self.out(f"*{target_ptr} = ({st.c_name}){{0}};")
915
+ if node.keywords:
916
+ for kw in node.keywords:
917
+ ft = st.fields[kw.arg]
918
+ r = T.resolve(ft)
919
+ if isinstance(r, T.Array) and r.length < 0:
920
+ continue
921
+ self.out(
922
+ f"{target_ptr}->{kw.arg} = "
923
+ f"{self._deref_if_ref(self._cast(self.expr(kw.value), kw.value._etype, ft), ft)};"
924
+ )
925
+
926
+ def _emit_ref_assign(self, sym: Symbol, rrt: T.Type, stmt: ast.stmt) -> None:
927
+ """Construction / copy of an aggregate type written into a compile-time fixed-storage object.
928
+
929
+ Whole aggregate assignment (b = a) is already rejected by the two-pass checker; here we only handle construction and
930
+ copy_aggregate, neither of which allocates runtime memory.
931
+ """
932
+ value = stmt.value
933
+ if isinstance(rrt, T.Struct):
934
+ if hasattr(value, "_struct_ctor"):
935
+ self._emit_struct_ctor(sym.c_name, T.resolve(value._struct_ctor), value)
936
+ return
937
+ if getattr(value, "_is_copy_aggregate", False):
938
+ # The source may be a struct inlined field (value); it must be addressed before being copied by C assignment.
939
+ src = self._ref_rhs_addr(self.expr(value.args[0]), value.args[0])
940
+ self.out(f"*{sym.c_name} = *{src};")
941
+ return
942
+ # Function returns an aggregate: copy the returned new value by value into this variable's own storage object.
943
+ src = self._new_temp("agg")
944
+ self.out(f"{self._ref_decl(rrt, src)} = {self.expr(value)};")
945
+ self.out(f"*{sym.c_name} = *{src};")
946
+ return
947
+ if isinstance(value, ast.List):
948
+ self._emit_array_literal_into(sym.c_name, value, self._array_dims(rrt), 0)
949
+ return
950
+ if getattr(value, "_is_make_array", False):
951
+ self._emit_array_zero(sym.c_name, self._array_dims(rrt), 0)
952
+ return
953
+ if getattr(value, "_is_copy_aggregate", False):
954
+ src = self.expr(value.args[0])
955
+ self._emit_array_copy(sym.c_name, src, self._array_dims(rrt), 0)
956
+ return
957
+ # Function returns an aggregate: C arrays cannot be assigned wholesale, so copy element by element into this variable's storage object.
958
+ src = self._new_temp("agg")
959
+ self.out(f"{self._ref_decl(rrt, src)} = {self.expr(value)};")
960
+ self._emit_array_copy(sym.c_name, src, self._array_dims(rrt), 0)
961
+ return
962
+
963
+ def _array_len_expr(self, node: ast.AST) -> str:
964
+ """Length expression of a fixed-width array: a compile-time constant or the parameter's length variable."""
965
+ t = T.resolve(getattr(node, "_etype", None))
966
+ if isinstance(t, T.Array):
967
+ if t.length >= 0:
968
+ return str(t.length)
969
+ if isinstance(node, ast.Name):
970
+ return f"{node._symbol.c_name}_len"
971
+ raise AssertionError("cannot determine fixed-length array length")
972
+
973
+ @staticmethod
974
+ def _array_dims(t: T.Type) -> List[T.Array]:
975
+ """Return the array types from outer to inner layers, e.g. array[array[int32]] -> [outer, inner]."""
976
+ dims: List[T.Array] = []
977
+ cur = T.resolve(t)
978
+ while isinstance(cur, T.Array):
979
+ dims.append(cur)
980
+ cur = T.resolve(cur.element)
981
+ return dims
982
+
983
+ @staticmethod
984
+ def _array_zero(elem: T.Type) -> str:
985
+ r = T.resolve(elem)
986
+ if isinstance(r, T.Struct):
987
+ return f"({r.c_name}){{0}}"
988
+ return "0"
989
+
990
+ def _emit_array_assign(self, dest: str, value: ast.AST, list_type: T.Array) -> None:
991
+ """Assign to a fixed-width array: literals are written element by element; variable copies are duplicated element by element."""
992
+ dims = self._array_dims(list_type)
993
+ if isinstance(value, ast.List):
994
+ self._emit_array_literal_into(dest, value, dims, 0)
995
+ return
996
+ if isinstance(value, ast.Call):
997
+ # make_array(T, N): zero out
998
+ self._emit_array_zero(dest, dims, 0)
999
+ return
1000
+ # Copy from another isomorphic array
1001
+ src = self.expr(value)
1002
+ self._emit_array_copy(dest, src, dims, 0)
1003
+
1004
+ def _emit_array_literal_into(
1005
+ self, dest: str, node: ast.List, dims: List[T.Array], level: int
1006
+ ) -> None:
1007
+ """Write a list literal into the target array element by element (C does not allow direct array assignment)."""
1008
+ elem = dims[level].element
1009
+ for i, e in enumerate(node.elts):
1010
+ if isinstance(e, ast.List):
1011
+ self._emit_array_literal_into(f"{dest}[{i}]", e, dims, level + 1)
1012
+ else:
1013
+ value = self._cast(self.expr(e), e._etype, elem)
1014
+ self.out(f"{dest}[{i}] = {self._deref_if_ref(value, elem)};")
1015
+
1016
+ def _emit_array_zero(
1017
+ self, dest: str, dims: List[T.Array], level: int
1018
+ ) -> None:
1019
+ """Zero out the target array element by element (the semantics of make_array)."""
1020
+ elem = dims[level].element
1021
+ inner = T.resolve(elem)
1022
+ for i in range(dims[level].length):
1023
+ if isinstance(inner, T.Array):
1024
+ self._emit_array_zero(f"{dest}[{i}]", dims, level + 1)
1025
+ else:
1026
+ self.out(f"{dest}[{i}] = {self._array_zero(elem)};")
1027
+
1028
+ def _emit_array_copy(
1029
+ self, dest: str, src: str, dims: List[T.Array], level: int
1030
+ ) -> None:
1031
+ """Copy element by element from one isomorphic array to another."""
1032
+ elem = dims[level].element
1033
+ inner = T.resolve(elem)
1034
+ for i in range(dims[level].length):
1035
+ if isinstance(inner, T.Array):
1036
+ self._emit_array_copy(f"{dest}[{i}]", f"{src}[{i}]", dims, level + 1)
1037
+ else:
1038
+ self.out(f"{dest}[{i}] = {src}[{i}];")
1039
+
1040
+ def _const_init_value(self, sym: Symbol, value: ast.AST) -> str:
1041
+ """Static initializer of a const variable.
1042
+
1043
+ Scalars go through ordinary conversion; arrays use C initializer lists (required for static initialization).
1044
+ """
1045
+ rrt = T.resolve(sym.type)
1046
+ if isinstance(rrt, T.Array) and isinstance(value, ast.List):
1047
+ dims = self._array_dims(rrt)
1048
+ return self._const_init_braces(value, dims, 0)
1049
+ return self._cast(self.expr(value), value._etype, sym.type)
1050
+
1051
+ def _const_init_braces(
1052
+ self, node: ast.List, dims: List[T.Array], level: int
1053
+ ) -> str:
1054
+ """Static initializer list: all elements are constants, no explicit conversion needed."""
1055
+ parts: List[str] = []
1056
+ for e in node.elts:
1057
+ if isinstance(e, ast.List):
1058
+ parts.append(self._const_init_braces(e, dims, level + 1))
1059
+ else:
1060
+ parts.append(self.expr(e))
1061
+ return "{" + ", ".join(parts) + "}"
1062
+
1063
+ def _list_compound_literal(self, node: ast.List) -> str:
1064
+ """List literal -> C99 compound literal, can be passed as a pointer argument."""
1065
+ t = T.resolve(node._etype)
1066
+ dims = self._array_dims(t)
1067
+ elem = T.resolve(dims[-1].element)
1068
+ if isinstance(elem, T.Ptr) and isinstance(T.resolve(elem.target), T.Func):
1069
+ # Function-pointer elements: the type name must be written as void (*[N])(void); you cannot
1070
+ # treat the function pointer as the base type and append [N]
1071
+ base, pat = _cdecl_parts(t)
1072
+ type_text = f"{base} {pat.replace('%s', '', 1)}"
1073
+ else:
1074
+ base = c_type(elem)
1075
+ suffix = "".join(f"[{d.length}]" for d in dims)
1076
+ type_text = f"{base}{suffix}"
1077
+ return f"({type_text}){self._list_init_braces(node, dims, 0)}"
1078
+
1079
+ def _list_init_braces(
1080
+ self, node: ast.List, dims: List[T.Array], level: int
1081
+ ) -> str:
1082
+ elem = dims[level].element
1083
+ parts: List[str] = []
1084
+ for e in node.elts:
1085
+ if isinstance(e, ast.List):
1086
+ parts.append(self._list_init_braces(e, dims, level + 1))
1087
+ else:
1088
+ parts.append(self._cast(self.expr(e), e._etype, elem))
1089
+ return "{" + ", ".join(parts) + "}"
1090
+
1091
+ @staticmethod
1092
+ def _frame_escape_returns(fi: FuncInfo) -> bool:
1093
+ """Whether the return value might carry out the pool memory allocated by this frame.
1094
+
1095
+ Functions returning Str / Bytes / a pointer, after the return expression is evaluated, record the current watermark as
1096
+ the reclamation floor: this frame's temporary objects are still rolled back, while the returned object is kept for the caller's frame and uniformly
1097
+ reclaimed at the caller's exit. This way every function participates in reclamation; there is no "whole-function gives up reclamation" tier.
1098
+ """
1099
+ r = T.resolve(fi.ret)
1100
+ return T.is_str(r) or T.is_bytes(r) or T.is_ptr(r)
1101
+
1102
+ def _emit_return(self, code: str) -> None:
1103
+ """The shared exit for all return paths, where frame-based reclamation restores the watermark."""
1104
+ if getattr(self, "_frame_reclaim", False):
1105
+ self.out(_ARENA_FRAME_RELEASE)
1106
+ self.out(code)
1107
+
1108
+ def _emit_function(self, fi: FuncInfo) -> None:
1109
+ self.out(self._prototype(fi, definition=True) + " {")
1110
+ self.indent += 1
1111
+ self._frame_reclaim = True
1112
+ self._frame_escapes = self._frame_escape_returns(fi)
1113
+ # The function entry forcibly switches to the automatic pool: this function's temporary objects are reclaimed by the exit watermark rollback,
1114
+ # while mem.arena_reset() written in user functions clears the manual pool and cannot touch this data.
1115
+ # The returned object is kept for the caller's frame by the floor; it is not specially skipped here.
1116
+ self.out(_ARENA_FRAME_MARK)
1117
+ for name, sym in fi.locals.items():
1118
+ if sym.kind == "param":
1119
+ continue
1120
+ assert sym.type is not None
1121
+ if "const" in sym.quals:
1122
+ # const local variables are generated at their declaration statement (including the initial value)
1123
+ continue
1124
+ r = T.resolve(sym.type)
1125
+ if self._is_ref_type(r):
1126
+ # Aggregate type: compile-time fixed-size static object + a pointer to it. Static storage duration
1127
+ # keeps the returned pointer from dangling, and occupies no arena and calls no malloc.
1128
+ obj = self._storage_name(sym.c_name)
1129
+ self.out(f"static {decl_str(sym.type, obj, sym.quals)};")
1130
+ init = f"&{obj}" if isinstance(r, T.Struct) else obj
1131
+ self.out(f"{self._ref_decl(sym.type, sym.c_name, sym.quals)} = {init};")
1132
+ else:
1133
+ self.out(
1134
+ f"{decl_str(sym.type, sym.c_name, sym.quals)} = "
1135
+ f"{zero_value(sym.type)};"
1136
+ )
1137
+ if any(sym.kind != "param" for sym in fi.locals.values()):
1138
+ self.out()
1139
+ for stmt in fi.node.body:
1140
+ if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant) \
1141
+ and isinstance(stmt.value.value, str):
1142
+ continue
1143
+ self._emit_stmt(stmt)
1144
+ if T.is_void(fi.ret):
1145
+ self._emit_return("return;")
1146
+ self.indent -= 1
1147
+ self.out("}")
1148
+ self.out()
1149
+
1150
+ def _main_body_stmts(self) -> List[ast.stmt]:
1151
+ """Return the top-level statements that will execute inside main (diagnostics and code generation share the same skip rules)."""
1152
+ body: List[ast.stmt] = []
1153
+ for stmt in self.tree.body:
1154
+ if isinstance(stmt, (ast.Import, ast.ImportFrom, ast.FunctionDef, ast.ClassDef)):
1155
+ continue
1156
+ if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant) \
1157
+ and isinstance(stmt.value.value, str):
1158
+ continue
1159
+ if isinstance(stmt, ast.Expr) and self._is_c_include_call(stmt.value):
1160
+ continue # c.include generates a file-header #include, not a statement
1161
+ if pp.is_pp_block_directive(stmt):
1162
+ continue # preprocessor directives are already emitted in the file-header region in source order
1163
+ if isinstance(stmt, ast.If) and getattr(stmt, "_pp_if", False) \
1164
+ and self._pp_pure_decl_block(stmt):
1165
+ continue # pure-declaration conditional blocks are already emitted in the file-header region
1166
+ if getattr(stmt, "_extern_type", False):
1167
+ continue # external type names are pure compile-time registrations and generate no code
1168
+ if getattr(stmt, "_extern_const", False):
1169
+ continue # external constant names are pure compile-time registrations and generate no definition/assignment
1170
+ if getattr(stmt, "_extern_var", False):
1171
+ continue # external variable names are pure compile-time registrations and generate no definition/assignment
1172
+ if getattr(stmt, "_macro", False):
1173
+ continue # macro names are pure compile-time registrations and generate no definition/assignment
1174
+ if getattr(stmt, "_section_binding", False):
1175
+ continue # segment descriptors are pure compile-time registrations and generate no definition/assignment
1176
+ if getattr(stmt, "_bare_decl", False):
1177
+ continue # bare calls without an LHS: declarations/macros are already emitted in the file header
1178
+ if self._is_static_object_decl(stmt):
1179
+ continue # real static C objects are already defined in the file header; main does not assign them
1180
+ body.append(stmt)
1181
+ return body
1182
+
1183
+ def _emit_main(self) -> None:
1184
+ self.out("int main(void) {")
1185
+ self.indent += 1
1186
+ self._frame_reclaim = False
1187
+ self._frame_escapes = False
1188
+ # main is only the execution host for module-level statements, not a scope in the user language: the user
1189
+ # cannot see it in the source code, and it does not exist in library / header outputs either. Pool ownership is determined per statement
1190
+ # by its position in the user source code: module-level statement values fall into the manual pool, values inside function bodies fall into the automatic pool.
1191
+ # The compiler does not auto-reset here; the manual pool is cleared only by mem.arena_reset() written by the user.
1192
+ body = self._main_body_stmts()
1193
+ if body:
1194
+ # All module-level statements draw from the same manual pool, with no reset between them:
1195
+ # the pool is switched once at each boundary of the whole block.
1196
+ self.out(_ARENA_MANUAL_MARKER)
1197
+ for stmt in body:
1198
+ self._emit_stmt(stmt)
1199
+ self.out(_ARENA_MANUAL_END_MARKER)
1200
+ self.out("return 0;")
1201
+ self.indent -= 1
1202
+ self.out("}")
1203
+
1204
+ @staticmethod
1205
+ def _is_static_object_decl(stmt: ast.stmt) -> bool:
1206
+ """Whether a top-level declaration corresponds to a real static C object (not re-assigned in main)."""
1207
+ if not isinstance(stmt, ast.AnnAssign):
1208
+ return False
1209
+ if stmt.value is None:
1210
+ return True
1211
+ sym = getattr(stmt, "_symbol", None)
1212
+ return bool(sym is not None and sym.static_object)
1213
+
1214
+ @staticmethod
1215
+ def _is_c_include_call(node: ast.AST) -> bool:
1216
+ if not isinstance(node, ast.Call):
1217
+ return False
1218
+ func = node.func
1219
+ return (
1220
+ isinstance(func, ast.Attribute)
1221
+ and func.attr == "include"
1222
+ and isinstance(func.value, ast.Name)
1223
+ and func.value.id == "c"
1224
+ )
1225
+
1226
+ # ---------------------------------------------------------------- preprocessing
1227
+
1228
+ def _pp_out(self, text: str) -> None:
1229
+ """Preprocessor directives are emitted at column 0, unaffected by the current function body's indentation."""
1230
+ saved = self.indent
1231
+ self.indent = 0
1232
+ self.out(text)
1233
+ self.indent = saved
1234
+
1235
+ def _emit_pp_directive(self, stmt: ast.Expr) -> None:
1236
+ if getattr(stmt, "_pp_block_decl", False):
1237
+ lines, err = pp.render_decl_directive(stmt.value)
1238
+ else:
1239
+ lines, err = pp.render_directive(stmt.value)
1240
+ assert err is None # validated by the two-pass checker
1241
+ for line in lines:
1242
+ self._pp_out(line)
1243
+
1244
+ @staticmethod
1245
+ def _pp_pure_decl_block(stmt: ast.If) -> bool:
1246
+ """Whether a top-level conditional block contains only declaration-class directives and can be placed in the file-header region.
1247
+
1248
+ Blocks containing executable statements are left to be emitted as ``#if`` inside main's body (C allows preprocessor directives inside function bodies).
1249
+ """
1250
+ def ok(s: ast.stmt) -> bool:
1251
+ if (isinstance(s, ast.Expr) and isinstance(s.value, ast.Constant)
1252
+ and isinstance(s.value.value, str)):
1253
+ return True
1254
+ if pp.is_pp_block_directive(s):
1255
+ return True
1256
+ if isinstance(s, ast.If) and getattr(s, "_pp_if", False):
1257
+ return all(ok(x) for x in s.body) and all(ok(x) for x in s.orelse)
1258
+ return False
1259
+ return all(ok(x) for x in stmt.body) and all(ok(x) for x in stmt.orelse)
1260
+
1261
+ def _emit_pp_chain(self, stmt: ast.If, emit_body) -> None:
1262
+ """Emit a complete #if / #elif / #else / #endif chain with exactly one #endif."""
1263
+ self._pp_out(f"#if {pp.render_cond(stmt.test)}")
1264
+ emit_body(stmt.body)
1265
+ cur = stmt
1266
+ while (len(cur.orelse) == 1 and isinstance(cur.orelse[0], ast.If)
1267
+ and getattr(cur.orelse[0], "_pp_if", False)):
1268
+ cur = cur.orelse[0]
1269
+ self._pp_out(f"#elif {pp.render_cond(cur.test)}")
1270
+ emit_body(cur.body)
1271
+ if cur.orelse:
1272
+ self._pp_out("#else")
1273
+ emit_body(cur.orelse)
1274
+ self._pp_out("#endif")
1275
+
1276
+ def _emit_pp_decl_body(self, body: list) -> None:
1277
+ for s in body:
1278
+ if pp.is_pp_block_directive(s):
1279
+ self._emit_pp_directive(s)
1280
+ elif isinstance(s, ast.If) and getattr(s, "_pp_if", False):
1281
+ self._emit_pp_chain(s, self._emit_pp_decl_body)
1282
+
1283
+ def _emit_pp_decls(self) -> None:
1284
+ """Emit module-level preprocessor directives and pure-declaration conditional blocks in source order."""
1285
+ emitted = False
1286
+ for stmt in self.tree.body:
1287
+ if pp.is_pp_block_directive(stmt):
1288
+ self._emit_pp_directive(stmt)
1289
+ emitted = True
1290
+ elif isinstance(stmt, ast.If) and getattr(stmt, "_pp_if", False) \
1291
+ and self._pp_pure_decl_block(stmt):
1292
+ self._emit_pp_chain(stmt, self._emit_pp_decl_body)
1293
+ emitted = True
1294
+ if emitted:
1295
+ self.out()
1296
+
1297
+ # ---------------------------------------------------------------- statements
1298
+
1299
+ def _emit_stmt(self, stmt: ast.stmt) -> None:
1300
+ self.mark(stmt)
1301
+ # The runtime's internal formatting buffer cannot access AST nodes; this global line number is used to fall back and report the real source line.
1302
+ self.out(f"{_ARENA_LINE_PREFIX}{getattr(stmt, 'lineno', 0)}")
1303
+ if isinstance(stmt, ast.Assign) and getattr(stmt, "_type_alias", False):
1304
+ # Type aliases (int32_ptr = Ptr[int32]) are pure type-level products and generate no code
1305
+ return
1306
+ if isinstance(stmt, ast.Assign) and getattr(stmt, "_target_kind", "") == "field":
1307
+ obj = self.expr(stmt._field_obj)
1308
+ value = self.expr(stmt.value)
1309
+ lhs = self._field_access(
1310
+ obj,
1311
+ stmt._field_name,
1312
+ self._ref_field_levels(
1313
+ stmt._field_obj, getattr(stmt, "_field_ptr_levels", 0)
1314
+ ),
1315
+ )
1316
+ self.out(f"{lhs} = {value};")
1317
+ return
1318
+ if isinstance(stmt, ast.Assign) and getattr(stmt, "_target_kind", "") == "subscript":
1319
+ obj = self.expr(stmt._subscript_obj)
1320
+ idx = self.expr(stmt._subscript_idx)
1321
+ target_type = stmt._subscript_target_type
1322
+ value = self._cast(
1323
+ self.expr(stmt.value), stmt.value._etype, target_type
1324
+ )
1325
+ self.out(f"({obj})[{idx}] = {self._deref_if_ref(value, target_type)};")
1326
+ return
1327
+ if isinstance(stmt, (ast.Assign, ast.AnnAssign)):
1328
+ sym: Symbol = stmt._symbol
1329
+ assert sym.type is not None
1330
+ rt = sym.type
1331
+ rrt = T.resolve(rt)
1332
+ if getattr(stmt, "_const_decl", False):
1333
+ # const local variables: initialize directly at the declaration (const cannot be assigned later in C)
1334
+ value = self._const_init_value(sym, stmt.value)
1335
+ self.out(
1336
+ f"{decl_str(rt, sym.c_name, sym.quals)} = {value};"
1337
+ )
1338
+ return
1339
+ if sym.kind == "global" and "const" in sym.quals:
1340
+ # const globals are statically initialized at the declaration; skip the assignment here
1341
+ return
1342
+ if self._is_ref_type(rrt):
1343
+ # Reference type: b = a is "pointer copy = alias"; construction/copy go through dedicated paths
1344
+ self._emit_ref_assign(sym, rrt, stmt)
1345
+ return
1346
+ value = self._cast(self.expr(stmt.value), stmt.value._etype, rt)
1347
+ self.out(f"{sym.c_name} = {value};")
1348
+ return
1349
+ if isinstance(stmt, ast.AugAssign):
1350
+ self._emit_aug(stmt)
1351
+ return
1352
+ if isinstance(stmt, ast.Expr):
1353
+ if pp.is_pp_block_directive(stmt):
1354
+ self._emit_pp_directive(stmt)
1355
+ return
1356
+ if self._is_print(stmt.value):
1357
+ self._emit_print(stmt.value)
1358
+ return
1359
+ c_stmt = getattr(stmt.value, "_c_stmt", None)
1360
+ if c_stmt == "barrier":
1361
+ # Compiler barrier: prevents cross-line read/write reordering (used for ordering of variables shared between ISR/main loop).
1362
+ self.out("__asm__ volatile(\"\" ::: \"memory\");")
1363
+ return
1364
+ if getattr(stmt.value, "_ptr_api", None) == "poke":
1365
+ # ptr.poke(p, v) is emitted as a single assignment statement
1366
+ self.out(f"{self.expr(stmt.value)};")
1367
+ return
1368
+ mem_api = getattr(stmt.value, "_mem_api", None)
1369
+ if mem_api == "arena_reset":
1370
+ self.out("py_arena_reset();")
1371
+ return
1372
+ if mem_api == "free":
1373
+ self._emit_mem_free(stmt.value)
1374
+ return
1375
+ if mem_api == "realloc":
1376
+ self._emit_mem_realloc(stmt.value)
1377
+ return
1378
+ code = self.expr(stmt.value)
1379
+ self.out(f"(void)({code});")
1380
+ return
1381
+ if isinstance(stmt, ast.Return):
1382
+ if stmt.value is None:
1383
+ fi = self._current_func
1384
+ if T.is_void(fi.ret):
1385
+ self._emit_return("return;")
1386
+ elif self._is_ref_type(fi.ret):
1387
+ # Reference-type return value: a valueless return uses a null pointer (the checker should have intercepted it in theory)
1388
+ self._emit_return("return NULL;")
1389
+ else:
1390
+ self._emit_return(f"return {zero_value(fi.ret)};")
1391
+ return
1392
+ fi = self._current_func
1393
+ if T.is_void(fi.ret):
1394
+ if self._is_print(stmt.value):
1395
+ self._emit_print(stmt.value)
1396
+ else:
1397
+ self.out(f"(void)({self.expr(stmt.value)});")
1398
+ self._emit_return("return;")
1399
+ return
1400
+ code = self._cast(self.expr(stmt.value), stmt.value._etype, fi.ret)
1401
+ if getattr(self, "_frame_escapes", False):
1402
+ # The expression is fully evaluated and the returned object sits at the pool tail; record it as the reclamation floor,
1403
+ # and the exit only rolls back this frame's temporary objects, handing the returned object to the caller's frame.
1404
+ self.out(_ARENA_FRAME_FLOOR)
1405
+ self._emit_return(f"return {code};")
1406
+ return
1407
+ if isinstance(stmt, ast.If):
1408
+ self._emit_if(stmt)
1409
+ return
1410
+ if isinstance(stmt, ast.While):
1411
+ self.out(f"while ({self._truthy(stmt.test, self.expr(stmt.test))}) {{")
1412
+ self.indent += 1
1413
+ for s in stmt.body:
1414
+ self._emit_stmt(s)
1415
+ self.indent -= 1
1416
+ self.out("}")
1417
+ return
1418
+ if isinstance(stmt, ast.For):
1419
+ self._emit_for(stmt)
1420
+ return
1421
+ if isinstance(stmt, ast.Break):
1422
+ self.out("break;")
1423
+ return
1424
+ if isinstance(stmt, ast.Continue):
1425
+ self.out("continue;")
1426
+ return
1427
+ if isinstance(stmt, ast.Pass):
1428
+ return
1429
+ raise AssertionError(f"unhandled statement: {type(stmt).__name__}")
1430
+
1431
+ def _emit_if(self, stmt: ast.If) -> None:
1432
+ if getattr(stmt, "_pp_if", False):
1433
+ # Compile-time condition: emit an #if chain; statements inside the block are generated as usual, and the macro is decided by the downstream C compiler
1434
+ self._emit_pp_chain(stmt, lambda body: [self._emit_stmt(s) for s in body])
1435
+ return
1436
+ self.out(f"if ({self._truthy(stmt.test, self.expr(stmt.test))}) {{")
1437
+ self.indent += 1
1438
+ for s in stmt.body:
1439
+ self._emit_stmt(s)
1440
+ self.indent -= 1
1441
+ if stmt.orelse:
1442
+ self.out("} else {")
1443
+ self.indent += 1
1444
+ for s in stmt.orelse:
1445
+ self._emit_stmt(s)
1446
+ self.indent -= 1
1447
+ self.out("}")
1448
+
1449
+ def _emit_for(self, stmt: ast.For) -> None:
1450
+ if getattr(stmt, "_for_array", None) is not None:
1451
+ self._emit_for_array(stmt)
1452
+ return
1453
+ it: ast.Call = stmt.iter # confirmed in the type-checking phase
1454
+ self.temp += 1
1455
+ n = self.temp
1456
+ args = []
1457
+ for a in it.args:
1458
+ folded = getattr(a, "_range_fold", None)
1459
+ if folded is None:
1460
+ args.append(self._cast(self.expr(a), a._etype, T.I64))
1461
+ else:
1462
+ args.append(i64_literal(folded))
1463
+ if len(args) == 1:
1464
+ start, stop, step = "((int64_t)0)", args[0], "((int64_t)1)"
1465
+ elif len(args) == 2:
1466
+ start, stop, step = args[0], args[1], "((int64_t)1)"
1467
+ else:
1468
+ start, stop, step = args[0], args[1], args[2]
1469
+ sym: Symbol = stmt._symbol
1470
+ self.out("{")
1471
+ self.indent += 1
1472
+ self.out(f"int64_t __stop{n} = {stop};")
1473
+ self.out(f"int64_t __step{n} = py_range_step({step}, {stmt.lineno});")
1474
+ self.out(f"{sym.c_name} = {start};")
1475
+ cond = (
1476
+ f"((__step{n} > 0) ? ({sym.c_name} < __stop{n}) : "
1477
+ f"({sym.c_name} > __stop{n}))"
1478
+ )
1479
+ self.out(
1480
+ f"for (; {cond}; {sym.c_name} = (int64_t)({sym.c_name} + __step{n})) {{"
1481
+ )
1482
+ self.indent += 1
1483
+ for s in stmt.body:
1484
+ self._emit_stmt(s)
1485
+ self.indent -= 1
1486
+ self.out("}")
1487
+ self.indent -= 1
1488
+ self.out("}")
1489
+
1490
+ def _emit_for_array(self, stmt: ast.For) -> None:
1491
+ """for v in arr: expand into an indexed loop."""
1492
+ it = stmt._for_array
1493
+ base = self.expr(it)
1494
+ length = self._array_len_expr(it)
1495
+ sym: Symbol = stmt._symbol
1496
+ self.temp += 1
1497
+ n = self.temp
1498
+ self.out("{")
1499
+ self.indent += 1
1500
+ self.out(f"int64_t __i{n} = 0;")
1501
+ self.out(f"for (; __i{n} < ({length}); __i{n} = (int64_t)(__i{n} + 1)) {{")
1502
+ self.indent += 1
1503
+ self.out(f"{sym.c_name} = ({base})[__i{n}];")
1504
+ for s in stmt.body:
1505
+ self._emit_stmt(s)
1506
+ self.indent -= 1
1507
+ self.out("}")
1508
+ self.indent -= 1
1509
+ self.out("}")
1510
+
1511
+ def _enum_of(self, node: ast.AST) -> Optional[T.Enum]:
1512
+ """Get the enum type that an enum member access belongs to."""
1513
+ base = getattr(node, "value", None)
1514
+ if not isinstance(base, ast.Name):
1515
+ return None
1516
+ sym = self.info.scope.get(base.id)
1517
+ if sym is None or sym.kind != "type" or sym.type is None:
1518
+ return None
1519
+ en = T.resolve(sym.type)
1520
+ return en if isinstance(en, T.Enum) else None
1521
+
1522
+ def _emit_aug(self, stmt: ast.AugAssign) -> None:
1523
+ # Fixed-length array subscript augmented assignment: a[i] += 1 -> a[i] = a[i] + 1
1524
+ if getattr(stmt, "_target_kind", "") == "subscript_aug":
1525
+ obj = self.expr(stmt._subscript_obj)
1526
+ idx = self.expr(stmt._subscript_idx)
1527
+ op_type = stmt._aug_op_type
1528
+ lhs = self._cast(f"({obj})[{idx}]", stmt._subscript_target_type, op_type)
1529
+ rhs = self._cast(self.expr(stmt.value), stmt._aug_rhs_type, op_type)
1530
+ raw = self._binary(stmt.op, lhs, rhs, op_type, stmt.lineno)
1531
+ self.out(f"({obj})[{idx}] = {raw};")
1532
+ return
1533
+ sym: Symbol = stmt._symbol
1534
+ rhs = self.expr(stmt.value)
1535
+ rt = sym.type
1536
+ assert rt is not None
1537
+ # Pointer offset: p += 1 -> p = p + 1
1538
+ if getattr(stmt, "_aug_kind", "") == "ptr_offset":
1539
+ r = self._cast(rhs, stmt._rhs_type, T.I64)
1540
+ op = "+" if isinstance(stmt.op, ast.Add) else "-"
1541
+ self.out(f"{sym.c_name} = {sym.c_name} {op} ({r});")
1542
+ return
1543
+ if getattr(stmt, "_aug_kind", "") == "str_concat":
1544
+ self.out(f"{sym.c_name} = py_str_concat({sym.c_name}, {rhs}, {stmt.lineno});")
1545
+ return
1546
+ op_type = stmt._op_type
1547
+ left = sym.c_name
1548
+ l = self._cast(left, rt, op_type)
1549
+ r = self._cast(rhs, stmt._rhs_type, op_type)
1550
+ raw = self._binary(stmt.op, l, r, op_type, stmt.lineno)
1551
+ self.out(f"{sym.c_name} = {self._cast(raw, T.base(op_type), rt)};")
1552
+
1553
+ # ---------------------------------------------------------------- condition/truthiness
1554
+
1555
+ def _truthy(self, node: ast.AST, code: str) -> str:
1556
+ cond_type = node._cond_type
1557
+ if T.is_bool(cond_type):
1558
+ return f"({code})"
1559
+ if T.is_ptr(cond_type):
1560
+ return f"(({code}) != NULL)"
1561
+ if T.is_file(cond_type):
1562
+ # A py_file with fp == NULL means open failed, consistent with the dev-track _NullFile falsy value
1563
+ return f"(({code}).fp != NULL)"
1564
+ return f"((({code}) != 0))"
1565
+
1566
+ # ---------------------------------------------------------------- expression
1567
+
1568
+ def expr(self, node: ast.AST) -> str:
1569
+ if isinstance(node, ast.Constant):
1570
+ return self._constant(node)
1571
+ if isinstance(node, ast.Name):
1572
+ sym: Symbol = node._symbol
1573
+ return sym.c_name
1574
+ if isinstance(node, ast.BinOp):
1575
+ return self._binop(node)
1576
+ if isinstance(node, ast.UnaryOp):
1577
+ return self._unary(node)
1578
+ if isinstance(node, ast.BoolOp):
1579
+ return self._boolop(node)
1580
+ if isinstance(node, ast.Compare):
1581
+ return self._compare(node)
1582
+ if isinstance(node, ast.JoinedStr):
1583
+ return self._fstring(node)
1584
+ if isinstance(node, ast.IfExp):
1585
+ return self._ifexp(node)
1586
+ if isinstance(node, ast.Attribute):
1587
+ if getattr(node, "_enum_member", False):
1588
+ # Enum member: Mode.RUN -> Mode_RUN
1589
+ enum = self._enum_of(node)
1590
+ assert enum is not None
1591
+ return f"{enum.c_name}_{node.attr}"
1592
+ if hasattr(node, "_field_struct"):
1593
+ return self._field_access(
1594
+ self.expr(node.value),
1595
+ node.attr,
1596
+ self._ref_field_levels(
1597
+ node.value, getattr(node, "_field_ptr_levels", 0)
1598
+ ),
1599
+ )
1600
+ raise AssertionError("unannotated attribute access")
1601
+ if isinstance(node, ast.Subscript):
1602
+ if hasattr(node, "_bytes_base"):
1603
+ # A bytes subscript reads data by byte position; the result type is uchar.
1604
+ base = self.expr(node._bytes_base)
1605
+ idx = self.expr(node._bytes_index)
1606
+ return f"((unsigned char)(({base}).data[{idx}]))"
1607
+ if hasattr(node, "_str_base"):
1608
+ # Text subscript: s[i] -> fetch the i-th character by UTF-8 code point; element type is char
1609
+ base = self.expr(node._str_base)
1610
+ idx = self.expr(node._str_index)
1611
+ return f"py_str_at({base}, {idx})"
1612
+ base = self.expr(node.value)
1613
+ idx = self.expr(node.slice)
1614
+ return f"({base})[{idx}]"
1615
+ if isinstance(node, ast.List):
1616
+ return self._list_compound_literal(node)
1617
+ if isinstance(node, ast.Call):
1618
+ return self._call(node)
1619
+ raise AssertionError(f"unhandled expression: {type(node).__name__}")
1620
+
1621
+ def _constant(self, node: ast.Constant) -> str:
1622
+ value = node.value
1623
+ if isinstance(value, bool):
1624
+ return "1" if value else "0"
1625
+ if isinstance(value, int):
1626
+ if value == -(1 << 63):
1627
+ return "(-INT64_C(9223372036854775807) - 1)"
1628
+ return str(value)
1629
+ if isinstance(value, float):
1630
+ return repr(value)
1631
+ if isinstance(value, str):
1632
+ # Assigning a string literal to a single-byte char type: take the first byte
1633
+ # (on the CPython track the value is a str, and printing the first character is consistent)
1634
+ cp = getattr(node, "_char_codepoint", None)
1635
+ if cp is not None:
1636
+ return _c_char_literal(cp, _char_ctype(node))
1637
+ return self._str_literal(value)
1638
+ if isinstance(value, bytes):
1639
+ # Assigning a byte-string literal to a single-byte char type: take the first byte
1640
+ cp = getattr(node, "_char_codepoint", None)
1641
+ if cp is not None:
1642
+ return _c_char_literal(cp, _char_ctype(node))
1643
+ return self._bytes_literal(value)
1644
+ raise AssertionError("unsupported constant")
1645
+
1646
+ def _bytes_literal(self, data: bytes) -> str:
1647
+ """Byte-string literals land in a static uint8_t array, zero allocation."""
1648
+ key = bytes(data)
1649
+ if key in self._bytes_lit_index:
1650
+ return self._bytes_lit_index[key]
1651
+ idx = len(self.bytes_literals)
1652
+ name = f"__bytes{idx}"
1653
+ carr = c_byte_array(key)
1654
+ self.bytes_literals.append((name, carr, len(key)))
1655
+ expr = f"(py_bytes){{{name}, {len(key)}}}"
1656
+ self._bytes_lit_index[key] = expr
1657
+ return expr
1658
+
1659
+ def _str_literal(self, text: str) -> str:
1660
+ """String literals land in a static array, without calling py_str_new, zero allocation."""
1661
+ if text in self._lit_index:
1662
+ return self._lit_index[text]
1663
+ idx = len(self.str_literals)
1664
+ name = f"__lit{idx}"
1665
+ clit = c_string(text)
1666
+ blen = byte_len(text)
1667
+ clen = len(text) # code point count (Python str's len counts by code point)
1668
+ self.str_literals.append((name, clit, blen, clen))
1669
+ expr = f"(py_str){{{name}, {clen}, {blen}}}"
1670
+ self._lit_index[text] = expr
1671
+ return expr
1672
+
1673
+ def _fstring(self, node: ast.JoinedStr) -> str:
1674
+ """f-string -> py_str expression: literal fragments and field fragments are concatenated with py_str_concat."""
1675
+ parts: List[str] = []
1676
+ for v in node.values:
1677
+ if isinstance(v, ast.FormattedValue):
1678
+ parts.append(self._fstring_field(v))
1679
+ elif isinstance(v, ast.Constant) and isinstance(v.value, str) and v.value:
1680
+ parts.append(self._str_literal(v.value))
1681
+ if not parts:
1682
+ return self._str_literal("")
1683
+ expr = parts[0]
1684
+ for p in parts[1:]:
1685
+ expr = f"py_str_concat({expr}, {p}, {node.lineno})"
1686
+ return expr
1687
+
1688
+ def _fstring_field(self, v: ast.FormattedValue) -> str:
1689
+ """One field of an f-string -> py_str expression."""
1690
+ code = self.expr(v.value)
1691
+ kind = getattr(v, "_fmt_kind", None)
1692
+ cfmt = getattr(v, "_fmt_cfmt", None)
1693
+ t = T.resolve(v.value._etype)
1694
+ if kind is None or cfmt is None:
1695
+ # No format spec: use the existing conversion function for the type
1696
+ if T.is_str(t):
1697
+ return code
1698
+ if T.is_bool(t):
1699
+ return f"py_str_from_bool({code})"
1700
+ s = T.base(t)
1701
+ if s.category == "float":
1702
+ return f"py_str_from_f64({self._cast(code, v.value._etype, T.F64)})"
1703
+ if s.signed:
1704
+ return f"py_str_from_i64({self._cast(code, v.value._etype, T.I64)})"
1705
+ return f"py_str_from_u64({self._cast(code, v.value._etype, T.U64)})"
1706
+ lit = c_string(cfmt)
1707
+ if kind == "i64":
1708
+ return f"py_str_format_i64({lit}, {self._cast(code, v.value._etype, T.I64)})"
1709
+ if kind == "u64":
1710
+ return f"py_str_format_u64({lit}, {self._cast(code, v.value._etype, T.U64)})"
1711
+ if kind == "f64":
1712
+ return f"py_str_format_f64({lit}, {self._cast(code, v.value._etype, T.F64)})"
1713
+ return f"py_str_format_str({lit}, {code})"
1714
+
1715
+ def _cast(self, code: str, src: T.Type, dst: T.Type) -> str:
1716
+ s = T.resolve(src)
1717
+ d = T.resolve(dst)
1718
+ if s is d:
1719
+ return code
1720
+ # External function pointer type: passed by value; the function name decays and is used directly as a C function pointer,
1721
+ # without any C cast (otherwise a non-existent .ctype would be applied).
1722
+ if isinstance(s, T.ExternFuncPtr) or isinstance(d, T.ExternFuncPtr):
1723
+ return code
1724
+ # Reference types (struct/array) are pointer expressions on the C side; both assignment and return copy the pointer,
1725
+ # and must not be wrapped in a C cast (otherwise the pointer would be converted to a value type, breaking aliasing semantics).
1726
+ if isinstance(s, (T.Struct, T.Array)) or isinstance(d, (T.Struct, T.Array)):
1727
+ return code
1728
+ if isinstance(s, T.Enum) or isinstance(d, T.Enum):
1729
+ # Enums are integers at the bottom; convert according to the target type
1730
+ return f"({c_type(d)})({code})"
1731
+ if isinstance(s, T.Ptr) or isinstance(d, T.Ptr):
1732
+ # Pointer types are compared structurally (Ptr is a dataclass, each construction is a new instance)
1733
+ if T.same(s, d):
1734
+ return code
1735
+ return f"({c_type(d)})({code})"
1736
+ if d is T.VOID or s is T.VOID:
1737
+ return code
1738
+ if s is T.STR or d is T.STR:
1739
+ return code
1740
+ return f"({d.ctype})({code})"
1741
+
1742
+ def _binop(self, node: ast.BinOp) -> str:
1743
+ # Pointer arithmetic
1744
+ if hasattr(node, "_ptr_arith"):
1745
+ kind = node._ptr_arith
1746
+ if kind == "add":
1747
+ if node._ptr_is_left:
1748
+ ptr_code = self.expr(node.left)
1749
+ int_code = self._cast(
1750
+ self.expr(node.right), node.right._etype, T.I64
1751
+ )
1752
+ else:
1753
+ ptr_code = self.expr(node.right)
1754
+ int_code = self._cast(
1755
+ self.expr(node.left), node.left._etype, T.I64
1756
+ )
1757
+ return f"({ptr_code} + {int_code})"
1758
+ if kind == "sub":
1759
+ ptr_code = self.expr(node.left)
1760
+ int_code = self._cast(self.expr(node.right), node.right._etype, T.I64)
1761
+ return f"({ptr_code} - {int_code})"
1762
+ if kind == "diff":
1763
+ left = self.expr(node.left)
1764
+ right = self.expr(node.right)
1765
+ return f"({left} - {right})"
1766
+ op_type = node._op_type
1767
+ if T.is_str(op_type):
1768
+ left = self.expr(node.left)
1769
+ right = self.expr(node.right)
1770
+ return f"py_str_concat({left}, {right}, {node.lineno})"
1771
+ left = self._cast(self.expr(node.left), node.left._etype, node._lcast)
1772
+ right = self._cast(self.expr(node.right), node.right._etype, node._rcast)
1773
+ raw = self._binary(node.op, left, right, op_type, node.lineno)
1774
+ return self._cast(raw, T.base(op_type), node._etype)
1775
+
1776
+ def _binary(
1777
+ self, op: ast.operator, left: str, right: str, op_type: T.Type, line: int
1778
+ ) -> str:
1779
+ t = _scalar(op_type)
1780
+ if isinstance(op, ast.Add):
1781
+ return f"({left} + {right})"
1782
+ if isinstance(op, ast.Sub):
1783
+ return f"({left} - {right})"
1784
+ if isinstance(op, ast.Mult):
1785
+ return f"({left} * {right})"
1786
+ if isinstance(op, ast.Div):
1787
+ return f"py_div_f64((double)({left}), (double)({right}), {line})"
1788
+ if isinstance(op, ast.FloorDiv):
1789
+ if t is T.F64:
1790
+ return f"py_fdiv_f64((double)({left}), (double)({right}), {line})"
1791
+ if t.signed:
1792
+ return f"(({t.ctype})py_fdiv_i64((int64_t)({left}), (int64_t)({right}), {line}))"
1793
+ return f"(({t.ctype})py_fdiv_u64((uint64_t)({left}), (uint64_t)({right}), {line}))"
1794
+ if isinstance(op, ast.Mod):
1795
+ if t is T.F64:
1796
+ return f"py_mod_f64((double)({left}), (double)({right}), {line})"
1797
+ if t.signed:
1798
+ return f"(({t.ctype})py_mod_i64((int64_t)({left}), (int64_t)({right}), {line}))"
1799
+ return f"(({t.ctype})py_mod_u64((uint64_t)({left}), (uint64_t)({right}), {line}))"
1800
+ if isinstance(op, ast.Pow):
1801
+ if t is T.F64:
1802
+ return f"py_pow_f64((double)({left}), (double)({right}), {line})"
1803
+ return f"(({t.ctype})py_pow_i64((int64_t)({left}), (int64_t)({right}), {line}))"
1804
+ if isinstance(op, ast.BitAnd):
1805
+ return f"({left} & {right})"
1806
+ if isinstance(op, ast.BitOr):
1807
+ return f"({left} | {right})"
1808
+ if isinstance(op, ast.BitXor):
1809
+ return f"({left} ^ {right})"
1810
+ if isinstance(op, ast.LShift):
1811
+ return f"(({t.ctype})(({left}) << ({right})))"
1812
+ if isinstance(op, ast.RShift):
1813
+ return f"(({t.ctype})(({left}) >> ({right})))"
1814
+ raise AssertionError(f"unhandled binary operation: {type(op).__name__}")
1815
+
1816
+ def _unary(self, node: ast.UnaryOp) -> str:
1817
+ operand = self.expr(node.operand)
1818
+ if isinstance(node.op, ast.Not):
1819
+ return f"(!{self._truthy(node.operand, operand)})"
1820
+ t = _scalar(node._etype)
1821
+ code = self._cast(operand, node._operand_type, node._operand_cast)
1822
+ if isinstance(node.op, ast.USub):
1823
+ return f"(({t.ctype})(-({code})))"
1824
+ if isinstance(node.op, ast.UAdd):
1825
+ return f"(({t.ctype})(+({code})))"
1826
+ if isinstance(node.op, ast.Invert):
1827
+ return f"(({t.ctype})(~({code})))"
1828
+ raise AssertionError(f"unhandled unary operation: {type(node.op).__name__}")
1829
+
1830
+ def _boolop(self, node: ast.BoolOp) -> str:
1831
+ sep = " && " if isinstance(node.op, ast.And) else " || "
1832
+ parts = [
1833
+ self._truthy(v, self.expr(v))
1834
+ for v in node.values
1835
+ ]
1836
+ return f"((bool)({sep.join(parts)}))"
1837
+
1838
+ def _compare(self, node: ast.Compare) -> str:
1839
+ ct = node._cmp_type
1840
+ codes = []
1841
+ for operand in [node.left] + list(node.comparators):
1842
+ code = self._cast(self.expr(operand), operand._etype, ct)
1843
+ codes.append(code)
1844
+ parts = []
1845
+ for i, op in enumerate(node.ops):
1846
+ a, b = codes[i], codes[i + 1]
1847
+ parts.append(self._compare_one(op, a, b, ct))
1848
+ return "(" + " && ".join(parts) + ")"
1849
+
1850
+ def _compare_one(self, op: ast.cmpop, a: str, b: str, ct: T.Type) -> str:
1851
+ if T.is_str(ct):
1852
+ if isinstance(op, ast.Eq):
1853
+ return f"py_str_eq({a}, {b})"
1854
+ if isinstance(op, ast.NotEq):
1855
+ return f"(!py_str_eq({a}, {b}))"
1856
+ cmp_code = f"py_str_cmp({a}, {b})"
1857
+ table = {
1858
+ ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">="
1859
+ }
1860
+ return f"({cmp_code} {table[type(op)]} 0)"
1861
+ return f"({a} {_COMPARE_OPS[type(op)]} {b})"
1862
+
1863
+ def _ifexp(self, node: ast.IfExp) -> str:
1864
+ cond = self._truthy(node.test, self.expr(node.test))
1865
+ bt = node._branch_type
1866
+ a = self._cast(self.expr(node.body), node.body._etype, bt)
1867
+ b = self._cast(self.expr(node.orelse), node.orelse._etype, bt)
1868
+ return f"({cond} ? ({a}) : ({b}))"
1869
+
1870
+ # ---------------------------------------------------------------- calls
1871
+
1872
+ def _call(self, node: ast.Call) -> str:
1873
+ if getattr(node, "_is_copy_aggregate", False):
1874
+ # Independent copies are only expanded by _emit_ref_assign on the assignment RHS; at expression positions fall back to the reference
1875
+ return self.expr(node.args[0])
1876
+ api = getattr(node, "_ptr_api", None)
1877
+ if api is not None:
1878
+ return self._call_ptr_api(node, api)
1879
+ mem_api = getattr(node, "_mem_api", None)
1880
+ if mem_api is not None:
1881
+ return self._call_mem_api(node, mem_api)
1882
+ io_api = getattr(node, "_io_api", None)
1883
+ if io_api is not None:
1884
+ return self._call_io_api(node, io_api)
1885
+ strings_api = getattr(node, "_strings_api", None)
1886
+ if strings_api is not None:
1887
+ return self._call_strings_api(node, strings_api)
1888
+ bytes_api = getattr(node, "_bytes_api", None)
1889
+ if bytes_api is not None:
1890
+ return self._call_bytes_api(node, bytes_api)
1891
+ c_api = getattr(node, "_c_expr_api", None)
1892
+ if c_api is not None:
1893
+ return self._call_c_expr_api(node, c_api)
1894
+ if hasattr(node, "_ptr_arg"):
1895
+ arg = self.expr(node._ptr_arg)
1896
+ return f"&({arg})"
1897
+ if hasattr(node, "_struct_ctor"):
1898
+ st = T.resolve(node._struct_ctor)
1899
+ assert isinstance(st, T.Struct)
1900
+ return self._struct_init(st, node)
1901
+ if getattr(node, "_array_len", None) is not None:
1902
+ # make_array(T, N): returns a zero-initialized fixed-width array
1903
+ elem = node._array_elem
1904
+ r = T.resolve(elem)
1905
+ if isinstance(r, T.Array):
1906
+ return f"({c_type(r.element)}){{0}}"
1907
+ return f"({c_type(r)}){{0}}"
1908
+ if getattr(node, "_funcptr_call", False):
1909
+ return self._call_funcptr(node)
1910
+ if hasattr(node, "_fi"):
1911
+ return self._call_func(node)
1912
+ if getattr(node, "_builtin", None) == "print":
1913
+ raise AssertionError("print can only be used as a statement")
1914
+ if getattr(node, "_builtin", None):
1915
+ return self._call_builtin(node)
1916
+ if hasattr(node, "_cast_type"):
1917
+ return self._call_cast(node)
1918
+ raise AssertionError("unannotated call")
1919
+
1920
+ def _call_func(self, node: ast.Call) -> str:
1921
+ fi: FuncInfo = node._fi
1922
+ args = []
1923
+ for arg, pname in zip(node.args, fi.params):
1924
+ pt = self._param_type(fi, pname)
1925
+ prt = T.resolve(pt)
1926
+ if isinstance(prt, T.Array):
1927
+ # Fixed-width array parameters are passed as pointer + length by C convention
1928
+ args.append(self.expr(arg))
1929
+ args.append(self._array_len_expr(arg))
1930
+ continue
1931
+ args.append(self._cast(self.expr(arg), arg._etype, pt))
1932
+ if fi.is_extern:
1933
+ return f"{fi.extern_c_name}({', '.join(args)})"
1934
+ if fi.export_c_name:
1935
+ return f"{fi.export_c_name}({', '.join(args)})"
1936
+ return f"f_{fi.name}({', '.join(args)})"
1937
+
1938
+ def _call_funcptr(self, node: ast.Call) -> str:
1939
+ ft = T.resolve(node._funcptr_type)
1940
+ callee = self.expr(node.func)
1941
+ args = []
1942
+ for arg, expected in zip(node.args, ft.args):
1943
+ args.append(self._cast(self.expr(arg), arg._etype, expected))
1944
+ return f"{callee}({', '.join(args)})"
1945
+
1946
+ def _call_cast(self, node: ast.Call) -> str:
1947
+ arg = node.args[0]
1948
+ target = _scalar(node._cast_type)
1949
+ at = T.base(T.resolve(node._arg_type))
1950
+ # A string literal is already folded into an integer constant at compile time, so the original string is not referenced; the constant is emitted directly and target-width wrapping is done by the C conversion.
1951
+ if T.is_str(at) and target.category == "int":
1952
+ const = getattr(node, "_cast_const", None)
1953
+ if const is not None:
1954
+ # INT64_MIN is written without a leading minus sign to avoid an unsigned-literal warning.
1955
+ lit = "(-INT64_C(9223372036854775807) - 1)" if const == -(1 << 63) else str(const)
1956
+ return f"({target.ctype})({lit})"
1957
+ code = self.expr(arg)
1958
+ if target.category == "str":
1959
+ # py_str is a struct, cannot use a C cast, and must go through the runtime conversion function.
1960
+ cat = at.category
1961
+ if cat == "bool":
1962
+ return f"py_str_from_bool({code})"
1963
+ if cat == "float":
1964
+ return f"py_str_from_f64((double)({code}))"
1965
+ if cat == "str":
1966
+ return code
1967
+ if cat == "char":
1968
+ # Char type to text: a one-byte text.
1969
+ return f"py_str_from_byte((unsigned char)({code}))"
1970
+ if cat == "int" and not at.signed:
1971
+ return f"py_str_from_u64((uint64_t)({code}))"
1972
+ return f"py_str_from_i64((int64_t)({code}))"
1973
+ if target.category == "bytes":
1974
+ if at.category == "char":
1975
+ # Char type to byte-string: a one-byte byte-string.
1976
+ return f"py_bytes_from_byte((unsigned char)({code}))"
1977
+ # Already a byte-string: move it as-is (byte-strings are immutable; sharing the underlying bytes is enough).
1978
+ return code
1979
+ if T.is_byte_char(at) and target.category == "int":
1980
+ # Char type to integer: take that byte's numeric value (0-255).
1981
+ # First convert to unsigned char; signed char will not be sign-extended either, so both tracks take the same value.
1982
+ return f"({target.ctype})((unsigned char)({code}))"
1983
+ return f"({target.ctype})({code})"
1984
+
1985
+ # ------------------------------------------------------- pure-functional pointer API: ptr.xxx
1986
+
1987
+ def _ptrapi_lvalue(self, arg: ast.AST) -> str:
1988
+ """The object whose address is taken: a variable, struct field, or pointer dereference."""
1989
+ if isinstance(arg, ast.Name):
1990
+ sym = getattr(arg, "_symbol", None)
1991
+ if sym is not None and sym.type is not None:
1992
+ r = T.resolve(sym.type)
1993
+ if isinstance(r, T.Array):
1994
+ # Array decay: &arr[0][0], taking the first element at each layer
1995
+ dims = array_dims(r)
1996
+ idx = "".join("[0]" for _ in dims)
1997
+ return f"{sym.c_name}{idx}"
1998
+ if isinstance(r, T.Struct):
1999
+ # A struct variable is already a pointer on the C side, so &(*s) yields Point* (not Point**)
2000
+ return f"(*{sym.c_name})"
2001
+ return self.expr(arg)
2002
+ if isinstance(arg, ast.Attribute):
2003
+ return self.expr(arg)
2004
+ if isinstance(arg, ast.Subscript):
2005
+ obj = self.expr(arg.value)
2006
+ ot = T.resolve(arg.value._etype)
2007
+ if isinstance(ot, T.Array):
2008
+ idx = self.expr(arg.slice)
2009
+ return f"{obj}[{idx}]"
2010
+ # Pointer dereference: &(*p)
2011
+ return f"(*({obj}))"
2012
+ raise AssertionError("cannot take address")
2013
+
2014
+ def _struct_init(self, st: T.Struct, node: ast.Call) -> str:
2015
+ """struct construction (expression context): allocate a temporary pointer and return it.
2016
+
2017
+ Under reference semantics a struct variable stores a pointer, so construction must be two statements "allocate + initialize,"
2018
+ which cannot be expressed with a single C initializer; hence it falls to a temporary variable, returning its name for the outer context to use.
2019
+ """
2020
+ tmp = self._new_temp("st")
2021
+ self._emit_struct_ctor(tmp, st, node, declare=True)
2022
+ return tmp
2023
+
2024
+ def _field_access(self, base: str, name: str, levels: int) -> str:
2025
+ """Generate C field access according to the pointer level.
2026
+
2027
+ - level 0 (struct value) -> ``s.f``
2028
+ - level 1 (``T *``) -> ``p->f``
2029
+ - level n>=2 -> ``(*(p))->f`` form with n-1 dereferences
2030
+
2031
+ C's ``->`` only dereferences one pointer level, so ``T **`` must first be manually dereferenced one level.
2032
+ """
2033
+ if levels <= 0:
2034
+ return f"{base}.{name}"
2035
+ if levels == 1:
2036
+ return f"{base}->{name}"
2037
+ deref = base
2038
+ for _ in range(levels - 1):
2039
+ deref = f"(*{deref})"
2040
+ return f"{deref}->{name}"
2041
+
2042
+ def _call_ptr_api(self, node: ast.Call, api: str) -> str:
2043
+ if api == "null":
2044
+ return "NULL"
2045
+ if api == "ref":
2046
+ return f"(&({self._ptrapi_lvalue(node._ptrapi_arg)}))"
2047
+ if api == "peek":
2048
+ p = self.expr(node.args[0])
2049
+ return f"(*({p}))"
2050
+ if api == "poke":
2051
+ p = self.expr(node.args[0])
2052
+ value = node.args[1]
2053
+ v = self._cast(self.expr(value), value._etype, node._ptrapi_elem)
2054
+ return f"(*({p})) = {v}"
2055
+ if api == "skip":
2056
+ p = self.expr(node.args[0])
2057
+ off = node.args[1]
2058
+ o = self._cast(self.expr(off), off._etype, T.I64)
2059
+ return f"(({p}) + {o})"
2060
+ if api == "field":
2061
+ obj = self.expr(node._ptrapi_obj)
2062
+ acc = self._field_access(
2063
+ obj,
2064
+ node._ptrapi_field,
2065
+ self._ref_field_levels(
2066
+ node._ptrapi_obj, getattr(node, "_ptrapi_ptr_levels", 0)
2067
+ ),
2068
+ )
2069
+ return f"(&({acc}))"
2070
+ if api == "from_int":
2071
+ addr = node.args[0]
2072
+ a = self._cast(self.expr(addr), addr._etype, T.I64)
2073
+ ctype = c_type(node._ptrapi_elem)
2074
+ return f"(({ctype}*)(intptr_t)({a}))"
2075
+ if api == "cast":
2076
+ p = self.expr(node.args[0])
2077
+ ctype = c_type(node._ptrapi_elem)
2078
+ return f"(({ctype}*)({p}))"
2079
+ raise AssertionError(f"unhandled ptr API: {api}")
2080
+
2081
+
2082
+ # -------------------------------------------- C memory management: mem.alloc/free/realloc
2083
+
2084
+ def _memapi_size(self, node: ast.Call) -> str:
2085
+ """Byte-count expression for mem.alloc/realloc: count * sizeof(T)."""
2086
+ count = node._memapi_count
2087
+ n = self._cast(self.expr(count), count._etype, T.I64)
2088
+ ctype = c_type(node._memapi_elem)
2089
+ return f"((size_t)({n}) * sizeof({ctype}))"
2090
+
2091
+ def _call_mem_api(self, node: ast.Call, api: str) -> str:
2092
+ if api == "arena_reset":
2093
+ # Normal usage is a standalone statement (emitted directly by _emit_stmt); at expression positions use
2094
+ # a comma expression to keep the C syntax valid and the value 0 in a void context.
2095
+ return "(py_arena_reset(), 0)"
2096
+ if api == "alloc":
2097
+ ctype = c_type(node._memapi_elem)
2098
+ size = self._memapi_size(node)
2099
+ # Use py_mem_alloc (calloc + side table) instead of bare malloc:
2100
+ # the CPython track's mem.alloc allocates a bytearray (zeroed), and the C track must match,
2101
+ # otherwise it would read uninitialized memory and the two tracks would produce different output.
2102
+ return f"({ctype}*)py_mem_alloc({size})"
2103
+ if api == "realloc":
2104
+ # When it appears at an expression position (e.g. buf = mem.realloc(buf, n)):
2105
+ # only return the new pointer; the assignment is done by the outer statement.
2106
+ arg = node._memapi_arg
2107
+ p = self.expr(arg)
2108
+ size = self._memapi_size(node)
2109
+ ctype = c_type(node._memapi_elem)
2110
+ # py_mem_realloc preserves min(old bytes, new bytes) of the old content and zeroes the newly
2111
+ # expanded region -- byte-for-byte consistent with the CPython track's bytearray semantics.
2112
+ return f"({ctype}*)py_mem_realloc((void*)({p}), {size})"
2113
+ raise AssertionError(f"unhandled mem API: {api}")
2114
+
2115
+ def _call_io_api(self, node: ast.Call, api: str) -> str:
2116
+ """C-side implementation of io.open / io.read / io.write / io.close."""
2117
+ if api == "open":
2118
+ path = self.expr(node.args[0])
2119
+ mode = self.expr(node.args[1])
2120
+ return f"py_open({path}, {mode})"
2121
+ if api == "read":
2122
+ f = self.expr(node.args[0])
2123
+ cap = self._cast(self.expr(node.args[1]), node.args[1]._etype, T.I64)
2124
+ return f"py_file_read({f}, {cap})"
2125
+ if api == "write":
2126
+ f = self.expr(node.args[0])
2127
+ data = self.expr(node.args[1])
2128
+ return f"py_file_write({f}, {data})"
2129
+ return f"py_file_close({self.expr(node.args[0])})"
2130
+
2131
+ def _call_strings_api(self, node: ast.Call, api: str) -> str:
2132
+ """C-side implementation of strings.data / byte_len / from_ptr."""
2133
+ if api == "from_ptr":
2134
+ # Build text from "pointer + byte length": py_str_new copies into the arena and counts code points.
2135
+ p = self.expr(node.args[0])
2136
+ n = self.expr(node.args[1])
2137
+ return f"py_str_new((const char *)({p}), (int64_t)({n}))"
2138
+ if api == "data":
2139
+ # Take a byte copy of the text: py_str_data allocates and memcpy's; modifying the copy does not affect the original text.
2140
+ s = self.expr(node.args[0])
2141
+ return f"py_str_data({s})"
2142
+ # byte_len: byte length (not code point count)
2143
+ return f"(({self.expr(node.args[0])}).blen)"
2144
+
2145
+ def _call_bytes_api(self, node: ast.Call, api: str) -> str:
2146
+ """C-side implementation of bytes.data / byte_len / from_ptr."""
2147
+ if api == "from_ptr":
2148
+ # Build a byte-string from "pointer + byte length": copy into the arena, detached from the source buffer.
2149
+ p = self.expr(node.args[0])
2150
+ n = self.expr(node.args[1])
2151
+ return f"py_bytes_from_ptr((const unsigned char *)({p}), (int64_t)({n}))"
2152
+ if api == "data":
2153
+ # Take a copy of the byte buffer: py_bytes_data allocates and memcpy's;
2154
+ # pass it to C functions together with byte_len (raw bytes may contain 0x00; there is no NUL convention).
2155
+ b = self.expr(node.args[0])
2156
+ return f"py_bytes_data({b})"
2157
+ # byte_len: byte length
2158
+ return f"(({self.expr(node.args[0])}).len)"
2159
+
2160
+ def _call_c_expr_api(self, node: ast.Call, api: str) -> str:
2161
+ """C-side implementation of c.clz/ctz/popcount (GCC/Clang builtins)."""
2162
+ suf = "ll" if node._c_expr_ll else ""
2163
+ return f"__builtin_{api}{suf}({self.expr(node.args[0])})"
2164
+
2165
+ def _emit_mem_free(self, node: ast.Call) -> None:
2166
+ """mem.free(p): free memory.
2167
+
2168
+ **Does not clear the pointer variable** -- same as C's free (free receives the value and cannot modify the caller's variable).
2169
+ To null the pointer, the user writes `p = ptr.null()` themselves.
2170
+ A double free is caught by py_fatal on the C track (the side table records deletions).
2171
+ """
2172
+ arg = node._memapi_arg
2173
+ p = self.expr(arg)
2174
+ # py_mem_free only releases blocks allocated by mem.alloc (verified via the side table),
2175
+ # corresponding to the CPython track's behavior of raising RuntimeError for non-heap pointers.
2176
+ self.out(f"py_mem_free({p});")
2177
+
2178
+ def _emit_mem_realloc(self, node: ast.Call) -> None:
2179
+ """mem.realloc(p, n): may move memory, so the pointer must be written back."""
2180
+ arg = node._memapi_arg
2181
+ p = self.expr(arg)
2182
+ size = self._memapi_size(node)
2183
+ ctype = c_type(node._memapi_elem)
2184
+ lvalue = self._memapi_lvalue(arg)
2185
+ if lvalue is None:
2186
+ # Cannot write back (e.g. p is an expression): use a temporary variable to hold it
2187
+ self.out(f"(void)py_mem_realloc((void*)({p}), {size});")
2188
+ return
2189
+ self.out(f"{lvalue} = ({ctype}*)py_mem_realloc((void*)({p}), {size});")
2190
+
2191
+ @staticmethod
2192
+ def _memapi_lvalue(arg: ast.AST) -> Optional[str]:
2193
+ """The pointer lvalue (variable name) for mem.free/realloc; returns None if it is not a variable."""
2194
+ if isinstance(arg, ast.Name):
2195
+ sym = getattr(arg, "_symbol", None)
2196
+ if sym is not None:
2197
+ return sym.c_name
2198
+ return None
2199
+
2200
+ @staticmethod
2201
+ def _is_print(node: ast.AST) -> bool:
2202
+ return isinstance(node, ast.Call) and getattr(node, "_builtin", None) == "print"
2203
+
2204
+ def _print_str_value(
2205
+ self, expr: str, fragments: List[str], args: List[str],
2206
+ prelude: List[str],
2207
+ ) -> None:
2208
+ """Print a py_str value as a string: first land it in a temporary variable, then output with %.*s.
2209
+
2210
+ py_str is a struct and cannot be safely evaluated twice inside printf, so it is uniformly stored first.
2211
+ """
2212
+ self.temp += 1
2213
+ name = f"__s{self.temp}"
2214
+ prelude.append(f"py_str {name} = {expr};")
2215
+ fragments.append('"%.*s"')
2216
+ args.append(f"(int){name}.blen")
2217
+ args.append(f"{name}.data")
2218
+
2219
+ def _emit_print(self, node: ast.Call) -> None:
2220
+ """print is emitted directly as a single printf call, with string constants folded into the format string."""
2221
+ fragments: List[str] = []
2222
+ args: List[str] = []
2223
+ prelude: List[str] = []
2224
+ postlude: List[str] = []
2225
+ sep = node._sep
2226
+ end = node._end
2227
+ for i, arg in enumerate(node.args):
2228
+ if i > 0:
2229
+ self._fmt_literal(fragments, " " if sep is None else sep)
2230
+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
2231
+ self._fmt_literal(fragments, arg.value)
2232
+ continue
2233
+ code = self.expr(arg)
2234
+ arg_t = T.resolve(node._arg_types[i])
2235
+ if isinstance(arg_t, T.Enum):
2236
+ # Enums are printed as integers (consistent with CPython's IntEnum)
2237
+ fragments.append('"%lld"')
2238
+ args.append(f"(long long)({code})")
2239
+ continue
2240
+ t = _scalar(node._arg_types[i])
2241
+ if t is T.STR:
2242
+ self._print_str_value(code, fragments, args, prelude)
2243
+ elif t is T.BYTES:
2244
+ # Byte-strings also need to be stored in a temporary variable first (to avoid repeated evaluation)
2245
+ # The output form is consistent with Python's repr(bytes): b'...', with non-printable bytes escaped
2246
+ self.temp += 1
2247
+ name = f"__b{self.temp}"
2248
+ cap = f"__c{self.temp}"
2249
+ rname = f"__r{self.temp}"
2250
+ prelude.append(f"py_bytes {name} = {code};")
2251
+ # Each byte outputs at most 4 characters (\xNN), plus b'' and the trailing NUL
2252
+ prelude.append(f"int64_t {cap} = {name}.len * 4 + 4;")
2253
+ prelude.append(
2254
+ f"char *{rname} = (char *)py_arena_alloc((size_t){cap}, {node.lineno});"
2255
+ )
2256
+ prelude.append(
2257
+ f"py_bytes_repr({name}.data, {name}.len, {rname}, {cap});"
2258
+ )
2259
+ fragments.append('"%s"')
2260
+ args.append(rname)
2261
+ elif t is T.BOOL:
2262
+ fragments.append('"%s"')
2263
+ args.append(f'({code} ? "True" : "False")')
2264
+ elif t.category == "char":
2265
+ # Both tracks go through the same shape: first land this single byte as the corresponding value,
2266
+ # then output it in that value's print form, without printing the character via %c as an integer code.
2267
+ self.temp += 1
2268
+ name = f"__u{self.temp}"
2269
+ prelude.append(
2270
+ f"unsigned char {name} = (unsigned char)({code});"
2271
+ )
2272
+ if t.text:
2273
+ # Text type (char): make it a length-1 text and print as a string,
2274
+ # consistent with the dev-track str.
2275
+ self._print_str_value(
2276
+ f"py_str_from_byte({name})", fragments, args, prelude
2277
+ )
2278
+ else:
2279
+ # Byte type (schar / uchar): print in byte-string form b'x',
2280
+ # consistent with the dev-track bytes (repr form: non-printable bytes escaped).
2281
+ buf = f"__ub{self.temp}"
2282
+ # A one-byte repr is at most "b'\\xNN'" + NUL, exactly 8 bytes.
2283
+ prelude.append(f"char {buf}[8];")
2284
+ prelude.append(f"py_bytes_repr(&{name}, 1, {buf}, 8);")
2285
+ fragments.append('"%s"')
2286
+ args.append(buf)
2287
+ elif t.category == "float":
2288
+ # Python's print(float) uses repr: -7.0 prints as "-7.0" rather than "-7",
2289
+ # and 1/3 prints with 16 significant digits rather than 15. Here we uniformly go through the runtime's
2290
+ # py_str_from_f64 (Python-repr-compatible shortest round-trip representation).
2291
+ self._print_str_value(
2292
+ f"py_str_from_f64((double)({code}))",
2293
+ fragments, args, prelude,
2294
+ )
2295
+ elif t.signed:
2296
+ fragments.append('"%lld"')
2297
+ args.append(f"(long long)({code})")
2298
+ else:
2299
+ fragments.append('"%llu"')
2300
+ args.append(f"(unsigned long long)({code})")
2301
+ self._fmt_literal(fragments, "\n" if end is None else end)
2302
+
2303
+ call = "printf(" + " ".join(fragments)
2304
+ if args:
2305
+ call += ", " + ", ".join(args)
2306
+ call += ");"
2307
+ if prelude or postlude:
2308
+ self.out("{")
2309
+ self.indent += 1
2310
+ for line in prelude:
2311
+ self.out(line)
2312
+ self.out(call)
2313
+ for line in postlude:
2314
+ self.out(line)
2315
+ self.indent -= 1
2316
+ self.out("}")
2317
+ else:
2318
+ self.out(call)
2319
+
2320
+ @staticmethod
2321
+ def _fmt_literal(fragments: List[str], text: str) -> None:
2322
+ if text:
2323
+ # The % in user text must be escaped to avoid being treated as a format spec by printf
2324
+ fragments.append(c_string(text.replace("%", "%%")))
2325
+
2326
+ def _call_builtin(self, node: ast.Call) -> str:
2327
+ name = node._builtin
2328
+ args = node.args
2329
+ arg_types = node._arg_types
2330
+ if name == "sizeof":
2331
+ # sizeof(T): let the target platform's C compiler compute it
2332
+ return f"sizeof({node._sizeof_c})"
2333
+ if name == "len":
2334
+ at = T.resolve(arg_types[0])
2335
+ if isinstance(at, T.Array):
2336
+ # Fixed-width array length: a compile-time constant or the parameter's length variable
2337
+ return self._array_len_expr(args[0])
2338
+ if T.is_bytes(at):
2339
+ # Byte-string length: the len field carried by the py_bytes struct
2340
+ return f"(({self.expr(args[0])}).len)"
2341
+ return f"py_str_len({self.expr(args[0])})"
2342
+ if name == "input":
2343
+ # Read one line from standard input; if a prompt is given, write it to stdout first
2344
+ if node.args:
2345
+ return f"py_input_prompt({self.expr(node.args[0])})"
2346
+ return "py_input()"
2347
+ if name == "abs":
2348
+ code = self.expr(args[0])
2349
+ s = _scalar(arg_types[0])
2350
+ if s is T.BOOL:
2351
+ return f"((int32_t)({code}))"
2352
+ if s.category == "float":
2353
+ return f"(({s.ctype})py_fabsd((double)({code})))"
2354
+ if not s.signed:
2355
+ return code
2356
+ return f"(({s.ctype})py_iabs((int64_t)({code})))"
2357
+ if name in ("min", "max"):
2358
+ return self._minmax(node, name)
2359
+ if name == "int":
2360
+ return f"((int64_t)({self.expr(args[0])}))"
2361
+ if name == "float":
2362
+ return f"((double)({self.expr(args[0])}))"
2363
+ if name == "str":
2364
+ code = self.expr(args[0])
2365
+ s = _scalar(arg_types[0])
2366
+ if s is T.STR:
2367
+ return code
2368
+ if s is T.BOOL:
2369
+ return f"py_str_from_bool({code})"
2370
+ if s.category == "float":
2371
+ return f"py_str_from_f64((double)({code}))"
2372
+ if s.signed:
2373
+ return f"py_str_from_i64((int64_t)({code}))"
2374
+ return f"py_str_from_u64((uint64_t)({code}))"
2375
+ raise AssertionError(f"unhandled builtin function {name}")
2376
+
2377
+ def _minmax(self, node: ast.Call, name: str) -> str:
2378
+ a_node, b_node = node.args
2379
+ a_type, b_type = node._arg_types
2380
+ rt = _scalar(node._etype)
2381
+ a = self._cast(self.expr(a_node), a_type, node._etype)
2382
+ b = self._cast(self.expr(b_node), b_type, node._etype)
2383
+ fn = "min" if name == "min" else "max"
2384
+ if rt is T.STR:
2385
+ return f"py_{fn}_str({a}, {b})"
2386
+ if rt.category == "float":
2387
+ return (
2388
+ f"(({rt.ctype})py_{fn}_f64((double)({a}), (double)({b})))"
2389
+ )
2390
+ if rt.signed:
2391
+ return f"(({rt.ctype})py_{fn}_i64((int64_t)({a}), (int64_t)({b})))"
2392
+ return f"(({rt.ctype})py_{fn}_u64((uint64_t)({a}), (uint64_t)({b})))"
2393
+
2394
+
2395
+ def generate(
2396
+ tree: ast.Module,
2397
+ info: ModuleInfo,
2398
+ filename: str,
2399
+ config: "Optional[CompileConfig]" = None,
2400
+ emit_line: "Optional[bool]" = None,
2401
+ ) -> str:
2402
+ """Module-level generation entry point: construct CodeGen and return the complete C source file text."""
2403
+ if emit_line is None:
2404
+ emit_line = ((config or CompileConfig()).line_output == "line")
2405
+ gen = CodeGen(tree, info, filename, config, emit_line=emit_line)
2406
+ gen._current_func = None
2407
+ return gen.generate()