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,663 @@
1
+ """Internal type representation and unification algorithm of the compiler.
2
+
3
+ Types fall into four categories:
4
+ - Scalar: fixed-width integer, fixed-width float, bool, str, void
5
+ - ConstInt / ConstFloat: literal types, can be "absorbed" by the target type
6
+ - TVar: inference variable, bound by the unification algorithm
7
+ """
8
+
9
+ from dataclasses import dataclass, field
10
+ from typing import Dict, Optional, Tuple, Union
11
+
12
+ # The language library is the single source of truth for type names and bit widths; the compiler derives its compile-time type objects from it.
13
+ import embeddedpy.types as _lang_types
14
+
15
+
16
+ class Type:
17
+ """Base class of all types."""
18
+
19
+
20
+ class TVar(Type):
21
+ """Inference variable."""
22
+
23
+ _counter = 0
24
+
25
+ def __init__(self) -> None:
26
+ TVar._counter += 1
27
+ self.id = TVar._counter
28
+ self.bound: Optional[Type] = None
29
+
30
+ def __repr__(self) -> str:
31
+ return f"?{self.id}"
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Scalar(Type):
36
+ """Concrete scalar type."""
37
+
38
+ name: str
39
+ ctype: str
40
+ bits: int
41
+ signed: bool
42
+ category: str # int / float / bool / char / str / bytes / file / void
43
+ # Within the char family, distinguish two print forms: char prints as string, schar / uchar print as bytestring.
44
+ text: bool = True
45
+
46
+
47
+ @dataclass
48
+ class Struct(Type):
49
+ """Aggregate type: a named set of fields, compiled to a C struct / union (value type, passed by value).
50
+
51
+ ``is_union`` decides whether to emit ``typedef struct`` or ``typedef union``;
52
+ ``packed`` decides whether to emit ``__attribute__((packed))``;
53
+ ``word_bits`` is the total register width declared by ``@c.word(W)`` (0 means not written).
54
+ All three fields have defaults, so the existing ``Struct(name, c_name=...)`` constructor is unaffected.
55
+ """
56
+
57
+ name: str
58
+ fields: Dict[str, "Type"] = field(default_factory=dict)
59
+ c_name: str = ""
60
+ is_union: bool = False
61
+ packed: bool = False
62
+ word_bits: int = 0
63
+ align: int = 0
64
+
65
+
66
+ @dataclass
67
+ class ExternType(Struct):
68
+ """External C type: only the name is registered; the definition lives in an external header.
69
+
70
+ Registered via ``c.extern_type("Cfg")``. The compiler does **not emit a typedef**; the C side directly
71
+ writes the c_name (the definition is provided by the header brought in via ``c.include``). fields is always empty--
72
+ embeddedpy does not hold the field table, so field access must error at compile time to avoid dual-track divergence.
73
+ It inherits Struct to reuse the existing semantics of annotations, construction, arena, and pointers.
74
+ """
75
+
76
+ external: bool = True
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class Bits(Scalar):
81
+ """Bit-field field type: ``Bits[N]`` compiles to C's ``uintW_t name : N;``.
82
+
83
+ Inheriting ``Scalar`` is deliberate: a bit field in an expression is just an unsigned integer,
84
+ so ``is_int`` / ``base`` / ``unify`` / ``describe`` all follow the scalar path,
85
+ without needing separate branches for arithmetic, comparison, and printing. ``ctype`` / ``bits`` are the **carrier
86
+ integer type** (determined by ``@c.word(W)``), and ``width`` is the bit width the user wrote.
87
+
88
+ It may only appear at the field-annotation position of an aggregate type: C's bit field is not a complete object type,
89
+ and cannot be a local variable, function parameter, or array element.
90
+ """
91
+
92
+ width: int = 0
93
+ storage_bits: int = 0
94
+
95
+
96
+ @dataclass
97
+ class Ptr(Type):
98
+ """Pointer type: a pointer to T, compiled to C's T*."""
99
+
100
+ target: "Type"
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class PtrTypeValue(Type):
105
+ """Type value: Ptr[T] itself (rather than a pointer to T).
106
+
107
+ Used for type aliases--`int32_ptr = Ptr[int32]` gives a name to the type
108
+ "pointer to int32", equivalent to C's `typedef int32_t *int32_ptr;`.
109
+ It can only appear at a type-annotation position, not as an ordinary value.
110
+ """
111
+
112
+ target: "Type"
113
+
114
+
115
+ @dataclass
116
+ class Array(Type):
117
+ """Fixed-length, homogeneous array: compiled to C's T name[N].
118
+
119
+ length is a compile-time constant length; -1 means not yet determined (e.g. a function parameter,
120
+ whose actual length is obtained by unification at the call site).
121
+ """
122
+
123
+ element: "Type"
124
+ length: int = -1
125
+
126
+
127
+ @dataclass(frozen=True)
128
+ class Func(Type):
129
+ """Function signature type: only used as the target type of a Ptr (function pointer).
130
+
131
+ For example ``Ptr[Func[[int32, int32], int32]]`` means "a function pointer that takes two int32
132
+ and returns int32". The compiler generates it into C's
133
+ ``int32_t (*)(int32_t, int32_t)``. A function name in expression position decays to
134
+ this pointer type (consistent with C's "function name decays to pointer").
135
+ """
136
+
137
+ args: Tuple["Type", ...] = ()
138
+ ret: "Type" = field(default_factory=lambda: VOID)
139
+
140
+
141
+ @dataclass(frozen=True)
142
+ class ExternFuncPtr(Func):
143
+ """External C function-pointer type: only the name and signature are registered; the definition lives in an external header.
144
+
145
+ Registered via ``c.extern_type("cb", Func[[int32], void])``. name/c_name are
146
+ the type names in the header (e.g. ``cb``); args/ret are the function signature (parsed from the second argument).
147
+
148
+ Relationship with ``T.Func``: it **is** a function-pointer type (passed by value, callable),
149
+ so it reuses all of Func's validation and call logic; the only difference is that the C side emits it as c_name
150
+ (``cb h;``) instead of ``void (*h)(...)``--which is exactly the point of an external type name.
151
+ A hard requirement for the C track to emit correct C: without it, the compiler would not know it is a function pointer and would emit
152
+ ``cb *`` by the struct convention, conflicting with the header's ``typedef ... (*cb)(...)``.
153
+ """
154
+
155
+ name: str = ""
156
+ c_name: str = ""
157
+
158
+
159
+ @dataclass
160
+ class Enum(Type):
161
+ """Enum type: compiled to C's enum.
162
+
163
+ members maps member name -> integer value; values are determined at compile time,
164
+ and members are generated on the C side as constants named `<enum>_<member>`.
165
+ """
166
+
167
+ name: str
168
+ members: Dict[str, int] = field(default_factory=dict)
169
+ c_name: str = ""
170
+
171
+
172
+ @dataclass(frozen=True)
173
+ class ConstInt(Type):
174
+ """Integer constant type."""
175
+
176
+ value: int
177
+
178
+
179
+ @dataclass(frozen=True)
180
+ class ConstFloat(Type):
181
+ """Float constant type."""
182
+
183
+ value: float
184
+
185
+
186
+ def _scalar_from_library(name: str, obj: object) -> Scalar:
187
+ """Derive a compile-time scalar type from the language library's type object.
188
+
189
+ The language library (``embeddedpy.types``) decides "which types exist and how many bits each has";
190
+ the compiler only supplements the C-side mapping (intN -> intN_t, float32 -> float …).
191
+ """
192
+ kind = getattr(obj, "kind", None)
193
+ if kind == "int":
194
+ return Scalar(name, f"{name}_t", obj.bits, obj.signed, "int")
195
+ if kind == "char":
196
+ # Char types: the C-side spelling is given by the language library (char / signed char / unsigned char),
197
+ # and whether it is text or byte semantics is also decided by the library (text attribute).
198
+ ctype = getattr(obj, "ctype", None) or name
199
+ return Scalar(
200
+ name, ctype, obj.bits, obj.signed, "char",
201
+ text=bool(getattr(obj, "text", True)),
202
+ )
203
+ if kind == "float":
204
+ return Scalar(name, "float" if obj.bits == 32 else "double", obj.bits, True, "float")
205
+ raise ValueError(f"unsupported scalar type kind: {name} ({kind!r})")
206
+
207
+
208
+ BOOL = Scalar("bool", "_Bool", 1, False, "bool")
209
+ STR = Scalar("Str", "py_str", -1, False, "str")
210
+ BYTES = Scalar("Bytes", "py_bytes", -1, False, "bytes")
211
+ FILE = Scalar("File", "py_file", -1, False, "file")
212
+ VOID = Scalar("void", "void", -1, False, "void")
213
+
214
+ # Types reusing builtin objects: embeddedpy.types directly reuses builtins' objects,
215
+ # and the compiler supplements the C-side mapping (Bool -> _Bool, Str -> py_str, Bytes -> py_bytes).
216
+ # The key is the **user-visible type name**, which is not the same as Scalar's internal category.
217
+ REEXPORTED_TYPES: Dict[str, Scalar] = {
218
+ "Bool": BOOL,
219
+ "Str": STR,
220
+ "Bytes": BYTES,
221
+ }
222
+
223
+ # void does not reuse a builtin object (Python has no void--its None is "empty value" rather than "no value"),
224
+ # but it also does not take the scalar-derivation path: it is "no value", not a kind of value.
225
+ VOID_TYPES: Dict[str, Scalar] = {"void": VOID}
226
+
227
+ # These names are not derived into scalar types by the compiler in embeddedpy.types.
228
+ REEXPORTED_TYPE_NAMES = frozenset(REEXPORTED_TYPES) | frozenset(VOID_TYPES)
229
+
230
+ INT_TYPES: Dict[str, Scalar] = {}
231
+ FLOAT_TYPES: Dict[str, Scalar] = {}
232
+ CHAR_TYPES: Dict[str, Scalar] = {}
233
+ for _name in _lang_types.__all__:
234
+ if _name in REEXPORTED_TYPE_NAMES:
235
+ # Types reusing builtin objects (Bool / Str / Bytes) have no kind attribute,
236
+ # so they cannot take the _scalar_from_library derivation path.
237
+ continue
238
+ _obj = getattr(_lang_types, _name)
239
+ if getattr(_obj, "kind", None) not in ("int", "float", "char"):
240
+ # Non-scalar types (Array / Ptr / Func / Struct / Enum / modifiers, etc.)
241
+ # are registered by name via lang_api; they do not take the scalar-derivation path.
242
+ continue
243
+ _scalar = _scalar_from_library(_name, _obj)
244
+ if _obj.kind == "int":
245
+ INT_TYPES[_name] = _scalar
246
+ elif _obj.kind == "char":
247
+ CHAR_TYPES[_name] = _scalar
248
+ else:
249
+ FLOAT_TYPES[_name] = _scalar
250
+
251
+ I8 = INT_TYPES["int8"]
252
+ I16 = INT_TYPES["int16"]
253
+ I32 = INT_TYPES["int32"]
254
+ I64 = INT_TYPES["int64"]
255
+
256
+ U8 = INT_TYPES["uint8"]
257
+ U16 = INT_TYPES["uint16"]
258
+ U32 = INT_TYPES["uint32"]
259
+ U64 = INT_TYPES["uint64"]
260
+
261
+ # Single-byte char family: char / schar / uchar, spelled on the C side as
262
+ # char / signed char / unsigned char; print forms split into text and bytestring.
263
+ CHAR = CHAR_TYPES["char"]
264
+ SCHAR = CHAR_TYPES["schar"]
265
+ UCHAR = CHAR_TYPES["uchar"]
266
+
267
+ F32 = FLOAT_TYPES["float32"]
268
+ F64 = FLOAT_TYPES["float64"]
269
+
270
+
271
+ class TypesMismatch(Exception):
272
+ """Type unification failed."""
273
+
274
+
275
+ def resolve(t: Type) -> Type:
276
+ """Follow to the underlying type; an unbound inference variable is returned as-is."""
277
+ while isinstance(t, TVar) and t.bound is not None:
278
+ t = t.bound
279
+ return t
280
+
281
+
282
+ def base(t: Type) -> Scalar:
283
+ """Absorb a constant type into the default scalar type."""
284
+ t = resolve(t)
285
+ if isinstance(t, ConstInt):
286
+ return I32
287
+ if isinstance(t, ConstFloat):
288
+ return F32
289
+ if isinstance(t, Enum):
290
+ # An enum's underlying type is int (C's typedef enum defaults to integer)
291
+ return I32
292
+ assert isinstance(t, Scalar), f"undetermined type: {t!r}"
293
+ return t
294
+
295
+
296
+ def _category(t: Type) -> Optional[str]:
297
+ r = resolve(t)
298
+ if isinstance(r, (TVar, Struct, Ptr, Array, PtrTypeValue, Enum)):
299
+ return None
300
+ return base(r).category
301
+
302
+
303
+ def is_int(t: Type) -> bool:
304
+ """Whether t is a fixed-width integer type (resolve first, then check category)."""
305
+ return _category(t) == "int"
306
+
307
+
308
+ def is_float(t: Type) -> bool:
309
+ """Whether t is a float type."""
310
+ return _category(t) == "float"
311
+
312
+
313
+ def is_bool(t: Type) -> bool:
314
+ """Whether t is a boolean type."""
315
+ return _category(t) == "bool"
316
+
317
+
318
+ def is_str(t: Type) -> bool:
319
+ """Whether t is an immutable string type."""
320
+ return _category(t) == "str"
321
+
322
+
323
+ def is_char(t: Type) -> bool:
324
+ """Whether t belongs to the single-byte char family (does not participate in arithmetic, nor implicitly mix with the integer family)."""
325
+ return _category(t) == "char"
326
+
327
+
328
+ def is_byte_char(t: Type) -> bool:
329
+ """Whether t is one of char / schar / uchar (C side: char / signed char / unsigned char respectively)."""
330
+ tr = resolve(t)
331
+ return isinstance(tr, Scalar) and tr.name in ("char", "schar", "uchar")
332
+
333
+
334
+ def is_bytes(t: Type) -> bool:
335
+ """Whether t is an immutable bytestring type."""
336
+ return _category(t) == "bytes"
337
+
338
+
339
+ def is_file(t: Type) -> bool:
340
+ """Whether t is a file-handle type."""
341
+ return _category(t) == "file"
342
+
343
+
344
+ def is_void(t: Type) -> bool:
345
+ """Whether t is void."""
346
+ return _category(t) == "void"
347
+
348
+
349
+ def is_struct(t: Type) -> bool:
350
+ """Whether t is a struct type."""
351
+ return isinstance(resolve(t), Struct)
352
+
353
+
354
+ def is_enum(t: Type) -> bool:
355
+ """Whether t is an enum type."""
356
+ return isinstance(resolve(t), Enum)
357
+
358
+
359
+ def is_ptr(t: Type) -> bool:
360
+ """Whether t is a pointer type."""
361
+ return isinstance(resolve(t), Ptr)
362
+
363
+
364
+ def is_numeric(t: Type) -> bool:
365
+ """Whether t can participate in arithmetic and bit operations (integers, floats, booleans, and enums whose underlying type is integer)."""
366
+ r = resolve(t)
367
+ if isinstance(r, Enum):
368
+ # An enum's underlying type is integer, so it can participate in arithmetic and bit operations
369
+ return True
370
+ return _category(r) in ("int", "float", "bool")
371
+
372
+
373
+ def describe(t: Type) -> str:
374
+ """Return a human-readable English name of the type, for diagnostic messages; falls back to the category name for unknown types."""
375
+ t = resolve(t)
376
+ if isinstance(t, TVar):
377
+ return "uninferred type"
378
+ if isinstance(t, ConstInt):
379
+ return "integer literal"
380
+ if isinstance(t, ConstFloat):
381
+ return "float literal"
382
+ if isinstance(t, Struct):
383
+ return t.name
384
+ if isinstance(t, Enum):
385
+ return t.name
386
+ if isinstance(t, Ptr):
387
+ return f"{describe(t.target)}*"
388
+ if isinstance(t, PtrTypeValue):
389
+ return f"Ptr[{describe(t.target)}]"
390
+ if isinstance(t, Func):
391
+ args = ", ".join(describe(a) for a in t.args) or "void"
392
+ return f"Func[{args}] -> {describe(t.ret)}"
393
+ if isinstance(t, Array):
394
+ n = "?" if t.length < 0 else str(t.length)
395
+ return f"{describe(t.element)}[{n}]"
396
+ return t.name
397
+
398
+
399
+ def struct_field_access(t: Type) -> Optional[Tuple[Struct, int]]:
400
+ """Resolve the base type of a "struct field access".
401
+
402
+ Returns ``(struct type, pointer level)``:
403
+ - level 0: struct **value**, accessed in C as ``s.f``
404
+ - level 1: ``Struct *``, accessed in C as ``p->f``
405
+ - level 2: ``Struct **``, accessed in C as ``(*p)->f`` (C's ``->`` dereferences only one level)
406
+
407
+ Returns None when it is not a struct and does not point to a struct.
408
+ """
409
+ r = resolve(t)
410
+ levels = 0
411
+ while isinstance(r, Ptr):
412
+ levels += 1
413
+ r = resolve(r.target)
414
+ if isinstance(r, Struct):
415
+ return r, levels
416
+ return None
417
+
418
+
419
+ def int_range(t: Scalar) -> Tuple[int, int]:
420
+ """Return ``(min, max)`` for a fixed-width integer type, computed by signedness."""
421
+ if t.signed:
422
+ return -(1 << (t.bits - 1)), (1 << (t.bits - 1)) - 1
423
+ return 0, (1 << t.bits) - 1
424
+
425
+
426
+ def _check_fit(const: ConstInt, target: Scalar) -> Scalar:
427
+ low, high = int_range(target)
428
+ if not (low <= const.value <= high):
429
+ raise TypesMismatch(
430
+ f"integer literal {const.value} is out of range for {target.name}: [{low}, {high}]"
431
+ )
432
+ return target
433
+
434
+
435
+ def _promote_int(a: Scalar, b: Scalar) -> Scalar:
436
+ if a.signed and b.signed:
437
+ return a if a.bits >= b.bits else b
438
+ if not a.signed and not b.signed:
439
+ return a if a.bits >= b.bits else b
440
+ signed = a if a.signed else b
441
+ unsigned = b if a.signed else a
442
+ # Only a wider signed type can safely hold the unsigned operand
443
+ if signed.bits > unsigned.bits:
444
+ return signed
445
+ raise TypesMismatch(
446
+ f"signed and unsigned types {a.name} and {b.name} cannot be implicitly mixed; use a cast to specify the result width"
447
+ )
448
+
449
+
450
+ def unify(a: Type, b: Type) -> Type:
451
+ """Compute the common type of two types, binding inference variables when necessary. Raises TypesMismatch on failure."""
452
+ a = resolve(a)
453
+ b = resolve(b)
454
+
455
+ if isinstance(a, TVar):
456
+ a.bound = base(b) if isinstance(b, (ConstInt, ConstFloat)) else b
457
+ return a.bound
458
+ if isinstance(b, TVar):
459
+ b.bound = base(a) if isinstance(a, (ConstInt, ConstFloat)) else a
460
+ return b.bound
461
+ if a is b:
462
+ return a
463
+
464
+ # Function signature: unify parameters and return type separately (before the scalar branch, to avoid base() assertions)
465
+ if isinstance(a, Func) and isinstance(b, Func):
466
+ if len(a.args) != len(b.args):
467
+ raise TypesMismatch(
468
+ f"function signature arity mismatch: {len(a.args)} vs {len(b.args)}"
469
+ )
470
+ unified_args = [unify(x, y) for x, y in zip(a.args, b.args)]
471
+ ret = unify(a.ret, b.ret)
472
+ return Func(tuple(unified_args), ret)
473
+ if isinstance(a, Func) or isinstance(b, Func):
474
+ other = b if isinstance(a, Func) else a
475
+ raise TypesMismatch(f"function signature cannot be mixed with {describe(other)}")
476
+
477
+ if isinstance(a, ConstInt) and isinstance(b, ConstInt):
478
+ return I32
479
+ if isinstance(a, ConstFloat) and isinstance(b, ConstFloat):
480
+ return F32
481
+
482
+ if isinstance(a, ConstInt):
483
+ if is_int(b):
484
+ return _check_fit(a, base(b))
485
+ if is_bool(b):
486
+ return I32
487
+ if is_float(b):
488
+ return base(b)
489
+ if isinstance(b, Enum):
490
+ return b # an enum constant can be assigned to an enum type
491
+ raise TypesMismatch(f"integer constant cannot be mixed with {describe(b)}")
492
+ if isinstance(b, ConstInt):
493
+ if is_int(a):
494
+ return _check_fit(b, base(a))
495
+ if is_bool(a):
496
+ return I32
497
+ if is_float(a):
498
+ return base(a)
499
+ if isinstance(a, Enum):
500
+ return a # an enum constant can be assigned to an enum type
501
+ raise TypesMismatch(f"integer constant cannot be mixed with {describe(a)}")
502
+
503
+ if isinstance(a, ConstFloat):
504
+ if is_float(b):
505
+ return base(b)
506
+ if is_bool(b):
507
+ return F64
508
+ raise TypesMismatch(f"float constant cannot be mixed with {describe(b)}")
509
+ if isinstance(b, ConstFloat):
510
+ if is_float(a):
511
+ return base(a)
512
+ if is_bool(a):
513
+ return F64
514
+ raise TypesMismatch(f"float constant cannot be mixed with {describe(a)}")
515
+
516
+ if is_bool(a) and is_bool(b):
517
+ return BOOL
518
+ if is_bool(a) and is_int(b):
519
+ return I32 if base(b).bits <= 32 else base(b)
520
+ if is_int(a) and is_bool(b):
521
+ return I32 if base(a).bits <= 32 else base(a)
522
+ if is_bool(a) and is_float(b):
523
+ return base(b)
524
+ if is_float(a) and is_bool(b):
525
+ return base(a)
526
+
527
+ if is_int(a) and is_int(b):
528
+ return _promote_int(base(a), base(b))
529
+ if is_float(a) and is_float(b):
530
+ return a if base(a).bits >= base(b).bits else b
531
+ if (is_int(a) and is_float(b)) or (is_float(a) and is_int(b)):
532
+ return F64
533
+
534
+ if is_str(a) and is_str(b):
535
+ return STR
536
+ if is_bytes(a) and is_bytes(b):
537
+ return BYTES
538
+ if is_file(a) and is_file(b):
539
+ return FILE
540
+ if is_void(a) and is_void(b):
541
+ return VOID
542
+
543
+ if isinstance(a, Struct) and isinstance(b, Struct):
544
+ if a is b:
545
+ return a
546
+ raise TypesMismatch(f"type mismatch: {describe(a)} and {describe(b)}")
547
+ if isinstance(a, Struct) or isinstance(b, Struct):
548
+ raise TypesMismatch(f"struct cannot be mixed with {describe(b if isinstance(a, Struct) else a)}")
549
+
550
+ # Enum: the underlying type is integer, so it can mix with integers
551
+ if isinstance(a, Enum) and isinstance(b, Enum):
552
+ if a is b or a.name == b.name:
553
+ return a
554
+ raise TypesMismatch(f"different enums cannot be mixed: {describe(a)} and {describe(b)}")
555
+ if isinstance(a, Enum) or isinstance(b, Enum):
556
+ other = b if isinstance(a, Enum) else a
557
+ # An enum constant (ConstInt) can be assigned to an enum type: preserve the enum identity
558
+ if isinstance(other, ConstInt):
559
+ return a if isinstance(a, Enum) else b
560
+ # Ordinary integer variable: an enum can be compared/mixed with integers, unified to integer
561
+ if is_int(other):
562
+ return base(other)
563
+ raise TypesMismatch(f"enum cannot be mixed with {describe(other)}")
564
+
565
+ if isinstance(a, Func) and isinstance(b, Func):
566
+ if len(a.args) != len(b.args):
567
+ raise TypesMismatch(
568
+ f"function signature arity mismatch: {len(a.args)} vs {len(b.args)}"
569
+ )
570
+ unified_args = [unify(x, y) for x, y in zip(a.args, b.args)]
571
+ ret = unify(a.ret, b.ret)
572
+ return Func(tuple(unified_args), ret)
573
+ if isinstance(a, Func) or isinstance(b, Func):
574
+ other = b if isinstance(a, Func) else a
575
+ raise TypesMismatch(f"function signature cannot be mixed with {describe(other)}")
576
+
577
+ if isinstance(a, Ptr) and isinstance(b, Ptr):
578
+ try:
579
+ inner = unify(a.target, b.target)
580
+ except TypesMismatch as exc:
581
+ raise TypesMismatch(f"pointer target type mismatch: {exc}")
582
+ return Ptr(inner)
583
+ if isinstance(a, Ptr) or isinstance(b, Ptr):
584
+ raise TypesMismatch(
585
+ f"pointer cannot be mixed with {describe(b if isinstance(a, Ptr) else a)}"
586
+ )
587
+
588
+ # Pointer type value (Ptr[T]): can only unify with the same kind of type value
589
+ if isinstance(a, PtrTypeValue) and isinstance(b, PtrTypeValue):
590
+ try:
591
+ inner = unify(a.target, b.target)
592
+ except TypesMismatch as exc:
593
+ raise TypesMismatch(f"pointer-type target mismatch: {exc}")
594
+ return PtrTypeValue(inner)
595
+ if isinstance(a, PtrTypeValue) or isinstance(b, PtrTypeValue):
596
+ other = b if isinstance(a, PtrTypeValue) else a
597
+ raise TypesMismatch(f"pointer type cannot be mixed with {describe(other)}")
598
+
599
+ if isinstance(a, Array) and isinstance(b, Array):
600
+ try:
601
+ elem = unify(a.element, b.element)
602
+ except TypesMismatch as exc:
603
+ raise TypesMismatch(f"array element type mismatch: {exc}")
604
+ if a.length != -1 and b.length != -1 and a.length != b.length:
605
+ raise TypesMismatch(
606
+ f"array length mismatch: {a.length} and {b.length}"
607
+ )
608
+ length = a.length if a.length != -1 else b.length
609
+ return Array(elem, length)
610
+ if isinstance(a, Array) or isinstance(b, Array):
611
+ raise TypesMismatch(
612
+ f"array cannot be mixed with {describe(b if isinstance(a, Array) else a)}"
613
+ )
614
+
615
+ raise TypesMismatch(f"type mismatch: {describe(a)} and {describe(b)}")
616
+
617
+
618
+ def same(a: Type, b: Type) -> bool:
619
+ """Whether two types (after resolution) are the same."""
620
+ ra = resolve(a)
621
+ rb = resolve(b)
622
+ if isinstance(ra, Struct) or isinstance(rb, Struct):
623
+ return ra is rb
624
+ if isinstance(ra, Enum) or isinstance(rb, Enum):
625
+ # An enum and an enum constant (ConstInt) are treated as the same type: the enum's underlying type is integer
626
+ if isinstance(ra, Enum) and isinstance(rb, Enum):
627
+ return ra.name == rb.name
628
+ other = rb if isinstance(ra, Enum) else ra
629
+ return isinstance(other, ConstInt)
630
+ if isinstance(ra, Func) or isinstance(rb, Func):
631
+ return (
632
+ isinstance(ra, Func)
633
+ and isinstance(rb, Func)
634
+ and len(ra.args) == len(rb.args)
635
+ and all(same(x, y) for x, y in zip(ra.args, rb.args))
636
+ and same(ra.ret, rb.ret)
637
+ )
638
+ if isinstance(ra, Ptr) or isinstance(rb, Ptr):
639
+ return isinstance(ra, Ptr) and isinstance(rb, Ptr) and same(ra.target, rb.target)
640
+ if isinstance(ra, PtrTypeValue) or isinstance(rb, PtrTypeValue):
641
+ return (
642
+ isinstance(ra, PtrTypeValue)
643
+ and isinstance(rb, PtrTypeValue)
644
+ and same(ra.target, rb.target)
645
+ )
646
+ if isinstance(ra, Array) or isinstance(rb, Array):
647
+ if not (isinstance(ra, Array) and isinstance(rb, Array)):
648
+ return False
649
+ # Length -1 means "unknown length" (function parameter), treated as compatible with any length
650
+ len_ok = ra.length == rb.length or ra.length < 0 or rb.length < 0
651
+ return len_ok and same(ra.element, rb.element)
652
+ if isinstance(ra, ConstInt) and isinstance(rb, ConstInt):
653
+ return ra.value == rb.value
654
+ if isinstance(ra, ConstFloat) and isinstance(rb, ConstFloat):
655
+ return ra.value == rb.value
656
+ if isinstance(ra, ConstInt) or isinstance(rb, ConstInt):
657
+ return False
658
+ if isinstance(ra, ConstFloat) or isinstance(rb, ConstFloat):
659
+ return False
660
+ return ra == rb
661
+
662
+
663
+ Kind = Union[Scalar, TVar, ConstInt, ConstFloat, Struct, Ptr, PtrTypeValue, Array]