embeddedpy 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

embeddedpy/types.py ADDED
@@ -0,0 +1,510 @@
1
+ """The type layer of embeddedpy: **all type names live here**.
2
+
3
+ Public usage: `from embeddedpy.types import int32, Str, Array, Ptr`.
4
+
5
+ **Type names have a single source: import.** This module exports:
6
+
7
+ - Scalars: ``int8``…``int64``, ``uint8``…``uint64``, ``float32``, ``float64``, ``Bool``
8
+ -- wrapping/rounding by bit width, replicating C's fixed-width semantics;
9
+ - Empty value: ``void``
10
+ -- C's "no value", appearing only in function return-type annotation position (``def f() -> void:``);
11
+ - Text and bytes: ``Str``, ``Bytes``
12
+ - Containers and pointers: ``Array``, ``Ptr``, ``Func``
13
+ -- ``Array[T]``/``Ptr[T]`` are the forms used in type annotations; ``Func[[...], R]`` itself is a function pointer;
14
+ - Aggregates: ``Struct``, ``Union``, ``Bits``, ``Enum``
15
+ -- ``class Point(Struct)`` defines a struct, ``class Word(Union)`` defines a union,
16
+ ``en: Bits[1]`` declares a bit-field field, ``class Mode(Enum)`` defines an enum;
17
+ - Qualifiers: ``const``, ``volatile``
18
+ -- appearing only in type annotation position (``x: const[int32]``).
19
+
20
+ Note that there is **no** ``int`` / ``float`` here: a default width is harmful implicit information in embedded;
21
+ if you want a width, write the width explicitly (``int64`` / ``float64``).
22
+
23
+ Belonging criterion: **every name entering this module must produce a type.**
24
+ Concrete types, type constructors (``Array``/``Ptr``/``Func``), type qualifiers (``const``/``volatile``),
25
+ and type-definition entry points (``Struct``/``Enum``) all satisfy this.
26
+
27
+ Counter-example: the output of ``sizeof`` is a **byte count** (an integer), not a type --
28
+ it is a **measurement tool**, living in ``embeddedpy.memory`` (in the same domain as allocation APIs like ``mem.alloc``,
29
+ all of which are "about byte counts"). Likewise ``make_array``/``ptr``/``auto`` produce values,
30
+ and are not in this module.
31
+
32
+ The remaining modules (``arrays`` / ``pointers`` / ``memory`` / ``io`` / ``interop``)
33
+ hold only functions, not types.
34
+ """
35
+
36
+ import builtins
37
+ import math
38
+ import struct
39
+
40
+
41
+ # ---------------------------------------------------------------- Scalar types
42
+ #
43
+ # Fixed-width integers and floats: wrapping/rounding by bit width on call,
44
+ # replicating C's fixed-width semantics.
45
+
46
+
47
+ class _IntegerType:
48
+ """Fixed-width integer type; simulates C integer wrapping on call."""
49
+
50
+ kind = "int"
51
+
52
+ def __init__(self, name: str, bits: int, signed: bool) -> None:
53
+ self.name = name
54
+ self.bits = bits
55
+ self.signed = signed
56
+
57
+ def __call__(self, value: object = 0) -> int:
58
+ if isinstance(value, float):
59
+ value = int(value)
60
+ if isinstance(value, str):
61
+ # Parse the text as a decimal integer literal: leading/trailing ASCII whitespace and a single optional sign are allowed, followed by one or more ASCII digits; any other form is rejected.
62
+ text = value.strip()
63
+ if not text:
64
+ raise ValueError(f"{self.name}() requires a decimal integer literal")
65
+ start = 1 if text[0] in "+-" else 0
66
+ digits = text[start:]
67
+ if not digits or any(c not in "0123456789" for c in digits):
68
+ raise ValueError(f"{self.name}() requires a decimal integer literal, got {value!r}")
69
+ magnitude = int(digits)
70
+ parsed = -magnitude if (start == 1 and text[0] == "-") else magnitude
71
+ # The parsed result must fall within the int64 range.
72
+ if not -(1 << 63) <= parsed <= (1 << 63) - 1:
73
+ raise ValueError(f"{self.name}() integer literal out of range")
74
+ value = parsed
75
+ elif isinstance(value, bytes):
76
+ if not value:
77
+ raise ValueError(f"{self.name}() cannot convert an empty bytes")
78
+ value = value[0]
79
+ raw = int(value) & ((1 << self.bits) - 1)
80
+ if self.signed and raw >= (1 << (self.bits - 1)):
81
+ raw -= 1 << self.bits
82
+ return raw
83
+
84
+ def __repr__(self) -> str:
85
+ return f"embeddedpy.{self.name}"
86
+
87
+
88
+ class _FloatType:
89
+ """Fixed-width float type; float32 rounds to single precision."""
90
+
91
+ kind = "float"
92
+
93
+ def __init__(self, name: str, bits: int) -> None:
94
+ self.name = name
95
+ self.bits = bits
96
+
97
+ def __call__(self, value: object = 0.0) -> float:
98
+ v = float(value)
99
+ if self.bits == 32:
100
+ try:
101
+ v = struct.unpack("f", struct.pack("f", v))[0]
102
+ except OverflowError:
103
+ v = math.inf if v > 0 else -math.inf
104
+ return v
105
+
106
+ def __repr__(self) -> str:
107
+ return f"embeddedpy.{self.name}"
108
+
109
+
110
+ int8 = _IntegerType("int8", 8, True)
111
+ int16 = _IntegerType("int16", 16, True)
112
+ int32 = _IntegerType("int32", 32, True)
113
+ int64 = _IntegerType("int64", 64, True)
114
+
115
+ uint8 = _IntegerType("uint8", 8, False)
116
+ uint16 = _IntegerType("uint16", 16, False)
117
+ uint32 = _IntegerType("uint32", 32, False)
118
+ uint64 = _IntegerType("uint64", 64, False)
119
+
120
+ # Single-byte character family: char / schar / uchar, spelled on the C side as
121
+ # char / signed char / unsigned char. All three are exactly one byte, do not take
122
+ # part in arithmetic, and are not implicitly mixed with the integer family; only
123
+ # explicit construction converts to/from integers.
124
+ #
125
+ # Two print forms: char prints as a string like A, its value on the Python track
126
+ # is str; schar / uchar print as a byte string like b'A', their value on the Python
127
+ # track is bytes. The literal form matches the print form; cross-form conversion
128
+ # requires explicit construction.
129
+
130
+
131
+ class _CharType:
132
+ """Single-byte character type: char / signed char / unsigned char.
133
+
134
+ Calling converts: string takes its first byte, byte string takes its first
135
+ byte, integer is truncated to 8 bits into a byte. The text form (char) becomes
136
+ str, the byte forms (schar / uchar) become bytes.
137
+ """
138
+
139
+ kind = "char"
140
+
141
+ def __init__(
142
+ self,
143
+ name: str,
144
+ bits: int,
145
+ signed: bool,
146
+ ctype: str,
147
+ text: bool,
148
+ ) -> None:
149
+ self.name = name
150
+ self.bits = bits
151
+ self.signed = signed
152
+ self.ctype = ctype
153
+ # Compile-time scalar classification: character types are separate from the
154
+ # integer family and do not take part in arithmetic.
155
+ self.category = "char"
156
+ # Text semantics (printed as a string like A) or byte semantics (printed as
157
+ # a byte string like b'A').
158
+ self.text = text
159
+
160
+ def __call__(self, value: object = 0) -> object:
161
+ if isinstance(value, bool):
162
+ raise TypeError(f"{self.name}() does not accept a boolean")
163
+ if isinstance(value, str):
164
+ encoded = value.encode("utf-8")
165
+ if not encoded:
166
+ raise ValueError(f"{self.name}() cannot convert an empty string")
167
+ raw = encoded[0:1]
168
+ elif isinstance(value, bytes):
169
+ if not value:
170
+ raise ValueError(f"{self.name}() cannot convert an empty bytes")
171
+ raw = value[0:1]
172
+ elif isinstance(value, int):
173
+ raw = bytes([value & 0xFF])
174
+ else:
175
+ raise TypeError(
176
+ f"{self.name}() expects a string, bytes, or integer"
177
+ )
178
+ if self.text:
179
+ # Single-byte text: decode with latin-1, preserving "one byte = one character".
180
+ return raw.decode("latin-1")
181
+ return raw
182
+
183
+ def __repr__(self) -> str:
184
+ return f"embeddedpy.{self.name}"
185
+
186
+
187
+ char = _CharType("char", 8, False, "char", text=True)
188
+
189
+ schar = _CharType("schar", 8, True, "signed char", text=False)
190
+
191
+ uchar = _CharType("uchar", 8, False, "unsigned char", text=False)
192
+
193
+ float32 = _FloatType("float32", 32)
194
+ float64 = _FloatType("float64", 64)
195
+
196
+ # Bool directly reuses the builtins.bool object: the import is a pure declaration
197
+ # with zero side effects. The capitalized name avoids clashing with Python's builtin
198
+ # bool (same rule as Str / Bytes). (embeddedpy.types.Bool is builtins.bool) -- annotation
199
+ # evaluation, conversion calls and isinstance all work as usual. The compiler binds it
200
+ # to C's _Bool on that side.
201
+ Bool = builtins.bool
202
+
203
+
204
+ # ---------------------------------------------------------------- Empty value type
205
+ #
206
+ # void is C's "no value": it appears only in function return-type annotation position
207
+ # (def f() -> void:). Python has no void (its None is "empty value", not "no value"), so
208
+ # here we use a placeholder object; it cannot be used as a value, and the compiler also
209
+ # rejects other uses of void.
210
+
211
+
212
+ class _VoidType:
213
+ """C's void: no value. Appears only in function return-type annotation position."""
214
+
215
+ def __repr__(self) -> str:
216
+ return "embeddedpy.void"
217
+
218
+
219
+ void = _VoidType()
220
+
221
+
222
+ # ---------------------------------------------------------------- Text and bytes
223
+ #
224
+ # Str / Bytes are value types for text and bytes: immutable, passed by value.
225
+ # On the C side they are py_str / py_bytes respectively.
226
+ #
227
+ # They reuse builtin objects (embeddedpy.types.Str is builtins.str), with zero
228
+ # import side effects; annotation evaluation, conversion calls and isinstance all
229
+ # work as usual; the compiler thus binds the C-side mapping
230
+ # (Str -> py_str, Bytes -> py_bytes).
231
+
232
+ Str = builtins.str
233
+ Bytes = builtins.bytes
234
+
235
+
236
+ # ---------------------------------------------------------------- Containers and pointers
237
+
238
+
239
+ class _PtrType:
240
+ """The CPython-side pointer type marker, produced by Ptr[T], for type annotations only."""
241
+
242
+ def __init__(self, target: object) -> None:
243
+ self.target = target
244
+
245
+ def __repr__(self) -> str:
246
+ return f"Ptr[{self.target!r}]"
247
+
248
+
249
+ class _ArrayType:
250
+ """The CPython-side fixed-length array type marker, for type-annotation evaluation only."""
251
+
252
+ def __init__(self, element: object) -> None:
253
+ self.element = element
254
+
255
+ def __repr__(self) -> str:
256
+ return f"Array[{self.element!r}]"
257
+
258
+
259
+ class _FuncSig:
260
+ """The placeholder object after evaluating ``Func[[...], ret]`` (used only for CPython-side annotation evaluation)."""
261
+
262
+ def __init__(self, item: object) -> None:
263
+ self.item = item
264
+
265
+
266
+ class Ptr:
267
+ """Pointer type constructor; Ptr[int32] corresponds to C's int32_t*."""
268
+
269
+ def __class_getitem__(cls, item: object) -> _PtrType:
270
+ return _PtrType(item)
271
+
272
+
273
+ class Array:
274
+ """Fixed-length array type constructor; Array[int32] corresponds to C's int32_t buf[N]."""
275
+
276
+ def __class_getitem__(cls, item: object) -> _ArrayType:
277
+ return _ArrayType(item)
278
+
279
+
280
+ class Func:
281
+ """Function signature placeholder type: ``Func[[int32, int32], int32]``.
282
+
283
+ It **is itself a function pointer** (C's ``int32_t (*)(int32_t, int32_t)``),
284
+ and does not need another layer of ``Ptr``. Internally the compiler still stores
285
+ a bare Func as ``Ptr(Func(...))``, reusing the existing pointer machinery.
286
+
287
+ ``Ptr[Func[...]]`` is a "pointer to a function pointer" (C's ``int (**p)(void)``),
288
+ rarely used.
289
+
290
+ embeddedpy has no runtime object for ``Func`` -- it is only a placeholder at the
291
+ type level; the real function pointer is implemented separately by the compiler on
292
+ the C side (``ret (*)(args...)``) and on the CPython side (Python function object).
293
+ Here it only needs to be evaluable in annotations without error.
294
+ """
295
+
296
+ def __class_getitem__(cls, item: object) -> _FuncSig:
297
+ return _FuncSig(item)
298
+
299
+
300
+ # ---------------------------------------------------------------- Aggregate types
301
+
302
+
303
+ class Struct:
304
+ """Struct base class.
305
+
306
+ Usage:
307
+ from embeddedpy.types import Struct
308
+
309
+ class Point(Struct):
310
+ x: int32
311
+ y: int32
312
+
313
+ On the CPython side, this base class's ``__init__`` provides construction
314
+ semantics consistent with C (``Point(1, 2)`` / ``Point(x=1, y=2)`` / ``Point()``);
315
+ when compiled to C, the compiler generates the struct from the class fields.
316
+ """
317
+
318
+ def __init__(self, *args: object, **kwargs: object) -> None:
319
+ fields = list(getattr(self.__class__, "__annotations__", {}).keys())
320
+ if not args and not kwargs:
321
+ # No-argument construction: a zero-value struct, fields filled in by later
322
+ # assignment (corresponds to C's (T){0}).
323
+ return
324
+ if args and kwargs:
325
+ raise TypeError("struct constructor cannot mix positional and keyword arguments")
326
+ if args:
327
+ if len(args) != len(fields):
328
+ raise TypeError(
329
+ f"{self.__class__.__name__} expects {len(fields)} positional arguments, got {len(args)}"
330
+ )
331
+ for name, value in zip(fields, args):
332
+ setattr(self, name, value)
333
+ else:
334
+ missing = [f for f in fields if f not in kwargs]
335
+ if missing:
336
+ raise TypeError(
337
+ f"{self.__class__.__name__} missing required fields: {', '.join(missing)}"
338
+ )
339
+ for name, value in kwargs.items():
340
+ if name not in fields:
341
+ raise TypeError(f"{self.__class__.__name__} has no field {name!r}")
342
+ setattr(self, name, value)
343
+
344
+
345
+ class Union(Struct):
346
+ """Union base class: all members share the same storage.
347
+
348
+ Usage::
349
+
350
+ from embeddedpy.types import Union, int32, float32
351
+
352
+ class Word(Union):
353
+ i: int32
354
+ f: float32
355
+
356
+ The C track emits ``typedef union { int32_t i; float f; } Word;``.
357
+ It inherits from ``Struct`` to reuse the full set of construction, field access and
358
+ pointer semantics: on the CPython track it is just a normal class with members stored
359
+ independently; differences between the two tracks are decided by the downstream C
360
+ compiler, not translated at the language layer.
361
+ """
362
+
363
+
364
+ class _BitsSig:
365
+ """The placeholder object after evaluating ``Bits[N]`` (used only for CPython-side annotation evaluation)."""
366
+
367
+ __slots__ = ("width",)
368
+
369
+ def __init__(self, width: object) -> None:
370
+ self.width = width
371
+
372
+ def __repr__(self) -> str:
373
+ return f"Bits[{self.width!r}]"
374
+
375
+
376
+ class Bits:
377
+ """Bit-field field type constructor; written as ``en: Bits[1]``.
378
+
379
+ Allowed only in the field annotation position of ``Struct`` / ``Union``. The bit width
380
+ is given by the integer literal in brackets; which integer type the C side uses to hold
381
+ it and how many padding bits are appended at the tail are computed by the compiler from
382
+ the class's ``@c.word(W)`` total width. The user does not write the storage type nor the
383
+ padding fields.
384
+ """
385
+
386
+ def __class_getitem__(cls, item: object) -> _BitsSig:
387
+ return _BitsSig(item)
388
+
389
+
390
+ class Enum:
391
+ """Enum base class: members are compile-time integer constants.
392
+
393
+ Usage:
394
+ from embeddedpy.types import Enum, auto
395
+
396
+ class Mode(Enum):
397
+ IDLE = 0
398
+ RUN = auto()
399
+
400
+ On CPython, members are ordinary integers (matching the values of the enum constants
401
+ generated on the C side), so ``Mode.RUN`` equals 1 on both tracks and can take part
402
+ directly in arithmetic and comparison. When compiled to C, it generates
403
+ ``typedef enum { Mode_IDLE = 0, Mode_RUN = 1 } Mode;``.
404
+ """
405
+
406
+ def __init_subclass__(cls, **kwargs: object) -> None:
407
+ super().__init_subclass__(**kwargs)
408
+ # Convert all members defined in the class body to int (auto() takes the previous
409
+ # value + 1).
410
+ next_value = 0
411
+ for name in list(vars(cls)):
412
+ if name.startswith("_"):
413
+ continue
414
+ value = vars(cls)[name]
415
+ if isinstance(value, _Auto):
416
+ value = next_value
417
+ elif not isinstance(value, int) or isinstance(value, bool):
418
+ continue
419
+ next_value = value + 1
420
+ setattr(cls, name, int(value))
421
+
422
+
423
+ class _Auto:
424
+ """auto() marker: automatically takes the previous member value + 1.
425
+
426
+ auto() itself is a **function**, living in ``embeddedpy.enums``; this marker class is
427
+ kept together with Enum because only Enum's class-body initialization needs to recognize
428
+ it.
429
+ """
430
+
431
+ def __repr__(self) -> str:
432
+ return "auto()"
433
+
434
+
435
+ # ---------------------------------------------------------------- Qualifiers
436
+ #
437
+ # C's volatile / const are written before the type (volatile int32_t x;);
438
+ # embeddedpy uses subscript syntax to keep the Python style: x: volatile[int32].
439
+ # Qualifiers only affect code generation and compile-time checks, with no runtime
440
+ # overhead on CPython.
441
+
442
+
443
+ class _QualifiedType:
444
+ """A type with a qualifier: const[int32] / volatile[int32]."""
445
+
446
+ __slots__ = ("qualifier", "target")
447
+
448
+ def __init__(self, qualifier: str, target: object) -> None:
449
+ self.qualifier = qualifier
450
+ self.target = target
451
+
452
+ def __repr__(self) -> str:
453
+ return f"{self.qualifier}[{self.target!r}]"
454
+
455
+
456
+ class _Qualifier:
457
+ """Qualifier constructor: const[T] / volatile[T]."""
458
+
459
+ __slots__ = ("name",)
460
+
461
+ def __init__(self, name: str) -> None:
462
+ self.name = name
463
+
464
+ def __getitem__(self, item: object) -> _QualifiedType:
465
+ return _QualifiedType(self.name, item)
466
+
467
+ def __class_getitem__(cls, item: object) -> _QualifiedType:
468
+ return _QualifiedType(cls.name, item)
469
+
470
+ def __repr__(self) -> str:
471
+ return f"embeddedpy.{self.name}"
472
+
473
+
474
+ const = _Qualifier("const")
475
+ volatile = _Qualifier("volatile")
476
+
477
+ __all__ = [
478
+ # Scalars
479
+ "int8",
480
+ "int16",
481
+ "int32",
482
+ "int64",
483
+ "uint8",
484
+ "uint16",
485
+ "uint32",
486
+ "uint64",
487
+ "char",
488
+ "schar",
489
+ "uchar",
490
+ "float32",
491
+ "float64",
492
+ "Bool",
493
+ # Empty value
494
+ "void",
495
+ # Text and bytes
496
+ "Str",
497
+ "Bytes",
498
+ # Containers and pointers
499
+ "Array",
500
+ "Ptr",
501
+ "Func",
502
+ # Aggregates
503
+ "Struct",
504
+ "Union",
505
+ "Bits",
506
+ "Enum",
507
+ # Qualifiers
508
+ "const",
509
+ "volatile",
510
+ ]