embeddedpy 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of embeddedpy might be problematic. Click here for more details.
- embeddedpy/__init__.py +55 -0
- embeddedpy/arrays.py +142 -0
- embeddedpy/bytes.py +65 -0
- embeddedpy/compiler/__init__.py +55 -0
- embeddedpy/compiler/__main__.py +8 -0
- embeddedpy/compiler/api.py +337 -0
- embeddedpy/compiler/cgen_helpers.py +298 -0
- embeddedpy/compiler/checker.py +244 -0
- embeddedpy/compiler/checker_pass1.py +3229 -0
- embeddedpy/compiler/checker_pass2.py +1879 -0
- embeddedpy/compiler/cli.py +310 -0
- embeddedpy/compiler/codegen.py +2407 -0
- embeddedpy/compiler/config.py +186 -0
- embeddedpy/compiler/errors.py +26 -0
- embeddedpy/compiler/frontend.py +381 -0
- embeddedpy/compiler/irtypes.py +663 -0
- embeddedpy/compiler/lang_api.py +163 -0
- embeddedpy/compiler/modules.py +583 -0
- embeddedpy/compiler/preprocessor.py +364 -0
- embeddedpy/compiler/runtime_lib.py +1395 -0
- embeddedpy/compiler/type_symbols.py +278 -0
- embeddedpy/enums.py +20 -0
- embeddedpy/interop.py +444 -0
- embeddedpy/io.py +119 -0
- embeddedpy/memory.py +196 -0
- embeddedpy/pointers.py +552 -0
- embeddedpy/strings.py +68 -0
- embeddedpy/types.py +510 -0
- embeddedpy-0.1.0.dist-info/METADATA +258 -0
- embeddedpy-0.1.0.dist-info/RECORD +34 -0
- embeddedpy-0.1.0.dist-info/WHEEL +5 -0
- embeddedpy-0.1.0.dist-info/entry_points.txt +2 -0
- embeddedpy-0.1.0.dist-info/licenses/LICENSE +21 -0
- embeddedpy-0.1.0.dist-info/top_level.txt +1 -0
embeddedpy/interop.py
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
"""The C interop category of embeddedpy: declare headers, external symbols,
|
|
2
|
+
local type aliases and macros.
|
|
3
|
+
|
|
4
|
+
Public usage: `from embeddedpy.interop import c`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class _ExternValue:
|
|
9
|
+
"""The CPython placeholder for external type instances: carries no fields.
|
|
10
|
+
|
|
11
|
+
On the C track the real A is defined by the header, and `A()` produces a
|
|
12
|
+
zero-initialized A value; the CPython track has no such C struct and can only
|
|
13
|
+
use an empty object as a placeholder. Field access is rejected at compile time
|
|
14
|
+
to avoid dual-track divergence.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
__slots__ = ()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class _SectionSpec:
|
|
21
|
+
"""The return value of ``c.section("...")``: both a function decorator and a
|
|
22
|
+
section descriptor.
|
|
23
|
+
|
|
24
|
+
For a function write ``@c.section(".ramfunc")`` (a Python decorator call); a
|
|
25
|
+
variable has no decorator syntax, so first bind the descriptor to a plain name
|
|
26
|
+
and then subscript it in the annotation:
|
|
27
|
+
|
|
28
|
+
isr_sec = c.section(".isr_vector")
|
|
29
|
+
vectors: isr_sec[Array[Func[[], void]]] = [...]
|
|
30
|
+
|
|
31
|
+
``isr_sec[T]`` returns T verbatim on the CPython track, and the annotation
|
|
32
|
+
remains an ordinary type; the compiler only reads the section name bound to
|
|
33
|
+
this name at compile time. The descriptor itself occupies no C storage and
|
|
34
|
+
generates no statement.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
__slots__ = ("name",)
|
|
38
|
+
|
|
39
|
+
def __init__(self, name: str) -> None:
|
|
40
|
+
self.name = name
|
|
41
|
+
|
|
42
|
+
def __call__(self, target: object) -> object:
|
|
43
|
+
return target
|
|
44
|
+
|
|
45
|
+
def __getitem__(self, type_expr: object) -> object:
|
|
46
|
+
return type_expr
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class _CInterop:
|
|
50
|
+
"""The single entry point for C interop: declare headers, external symbols,
|
|
51
|
+
local type aliases and macros.
|
|
52
|
+
|
|
53
|
+
Members fall into three groups: the consumption side (extern_type / extern_const /
|
|
54
|
+
extern_var / extern_function, whose declarations are provided by external C and which
|
|
55
|
+
the compiler does not emit definitions for), the definition side (typedef emits a local
|
|
56
|
+
typedef; define / include emit preprocessor directives), and declaration modifiers
|
|
57
|
+
(packed / word / inline / section, which are decorators). On the CPython track, include
|
|
58
|
+
is a no-op, extern_* returns placeholder values/classes, extern_function keeps the
|
|
59
|
+
function body as a mock, and all decorators are no-ops that return the decorated object
|
|
60
|
+
verbatim.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
__slots__ = ()
|
|
64
|
+
|
|
65
|
+
@staticmethod
|
|
66
|
+
def include(header: str, system: bool = False) -> None:
|
|
67
|
+
"""Declare the header file to #include.
|
|
68
|
+
|
|
69
|
+
header is the header file name; system=True wraps it with <> (system header),
|
|
70
|
+
otherwise it is wrapped with "" (user header). No side effect under CPython.
|
|
71
|
+
|
|
72
|
+
When written inside a compile-time conditional block, this line is emitted in
|
|
73
|
+
source order inside the ``#if``, and the downstream C compiler's ``-D`` decides
|
|
74
|
+
whether to include the header -- it will not be duplicated at the top of the file.
|
|
75
|
+
"""
|
|
76
|
+
if not isinstance(header, str) or not header:
|
|
77
|
+
raise TypeError("c.include header name must be a non-empty string")
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
@staticmethod
|
|
81
|
+
def defined(name: str) -> bool:
|
|
82
|
+
"""Compile-time condition: whether a macro is already defined; emits
|
|
83
|
+
``defined(NAME)`` in the output.
|
|
84
|
+
|
|
85
|
+
Can only be written in the condition of an ``if`` / ``elif``. Whether the macro
|
|
86
|
+
is actually defined is decided by the downstream C compiler's ``-D``; when this
|
|
87
|
+
function runs directly against the Python source it only yields a placeholder result.
|
|
88
|
+
"""
|
|
89
|
+
if not isinstance(name, str) or not name:
|
|
90
|
+
raise TypeError("c.defined name must be a non-empty string")
|
|
91
|
+
return False
|
|
92
|
+
|
|
93
|
+
@staticmethod
|
|
94
|
+
def macro(name: str) -> int:
|
|
95
|
+
"""Compile-time condition: take the value of an integer macro; emits the macro
|
|
96
|
+
name itself in the output.
|
|
97
|
+
|
|
98
|
+
Can only be written in the condition of an ``if`` / ``elif``, and can be combined
|
|
99
|
+
with comparison, arithmetic and bitwise operations. An undefined macro is treated
|
|
100
|
+
as 0 in the C preprocessing expression; when running the Python source directly it
|
|
101
|
+
returns 0.
|
|
102
|
+
"""
|
|
103
|
+
if not isinstance(name, str) or not name:
|
|
104
|
+
raise TypeError("c.macro name must be a non-empty string")
|
|
105
|
+
return 0
|
|
106
|
+
|
|
107
|
+
@staticmethod
|
|
108
|
+
def emit(text: str) -> None:
|
|
109
|
+
"""Write a chunk of C preprocessing/declaration text verbatim into the output,
|
|
110
|
+
one line or multiple lines.
|
|
111
|
+
|
|
112
|
+
This is the general outlet: for long-tail capabilities that have no dedicated
|
|
113
|
+
Python shape yet; common capabilities are written as named calls (c.define /
|
|
114
|
+
c.include / c.pragma / ...). What is written is a valid Python statement, and the
|
|
115
|
+
text content is the user's responsibility; source code should not contain large
|
|
116
|
+
blocks of C text.
|
|
117
|
+
"""
|
|
118
|
+
if not isinstance(text, str):
|
|
119
|
+
raise TypeError("c.emit text must be a string")
|
|
120
|
+
return None
|
|
121
|
+
|
|
122
|
+
@staticmethod
|
|
123
|
+
def pragma(text: str) -> None:
|
|
124
|
+
"""Emit one line of ``#pragma text``."""
|
|
125
|
+
if not isinstance(text, str):
|
|
126
|
+
raise TypeError("c.pragma text must be a string")
|
|
127
|
+
return None
|
|
128
|
+
|
|
129
|
+
@staticmethod
|
|
130
|
+
def error(text: str) -> None:
|
|
131
|
+
"""Emit one line of ``#error text`` so that compilation fails outright when a
|
|
132
|
+
condition is not met."""
|
|
133
|
+
if not isinstance(text, str):
|
|
134
|
+
raise TypeError("c.error text must be a string")
|
|
135
|
+
return None
|
|
136
|
+
|
|
137
|
+
@staticmethod
|
|
138
|
+
def warning(text: str) -> None:
|
|
139
|
+
"""Emit one line of ``#warning text`` (a toolchain extension, not a C99 standard directive)."""
|
|
140
|
+
if not isinstance(text, str):
|
|
141
|
+
raise TypeError("c.warning text must be a string")
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
@staticmethod
|
|
145
|
+
def undef(name: str) -> None:
|
|
146
|
+
"""Emit one line of ``#undef NAME``."""
|
|
147
|
+
if not isinstance(name, str):
|
|
148
|
+
raise TypeError("c.undef name must be a string")
|
|
149
|
+
return None
|
|
150
|
+
|
|
151
|
+
@staticmethod
|
|
152
|
+
def extern_type(name: str, signature: object = None) -> type:
|
|
153
|
+
"""Register an external C type name and return an instantiable type object.
|
|
154
|
+
|
|
155
|
+
Three forms:
|
|
156
|
+
|
|
157
|
+
- Struct (1 argument): ``A = c.extern_type("A")`` means A's definition lives in an
|
|
158
|
+
external header; the compiler only registers the name and emits no typedef. ``A()``
|
|
159
|
+
produces a zero-initialized A value on the C track and returns a placeholder object
|
|
160
|
+
on the CPython track; field access is rejected at compile time.
|
|
161
|
+
|
|
162
|
+
- Function pointer (2 arguments, signature is ``Func[...]``):
|
|
163
|
+
``cb = c.extern_type("cb", Func[[int32], void])`` means ``cb`` is a function-pointer
|
|
164
|
+
type name from the header, and signature is its signature. The compiler emits ``cb``
|
|
165
|
+
by value (avoiding an erroneous ``cb *`` that would clash with the header) and uses
|
|
166
|
+
the signature to validate calls and callback registration.
|
|
167
|
+
|
|
168
|
+
- Native scalar (2 arguments, signature is a fixed-width numeric type):
|
|
169
|
+
``size_t = c.extern_type("size_t", uint64)`` means ``size_t`` is a native-width type
|
|
170
|
+
from the header. The C name is spelled verbatim and passed by value, matching the
|
|
171
|
+
real C library prototypes for ``int`` / ``size_t`` / ``ssize_t``; type checking uses
|
|
172
|
+
the fixed-width semantics given by the second argument (here uint64). The CPython
|
|
173
|
+
track returns a placeholder type for annotation only.
|
|
174
|
+
|
|
175
|
+
signature is used only at compile time (the source of truth on the C track remains the
|
|
176
|
+
``#include``d header); the CPython track ignores it. name must match the C name in the
|
|
177
|
+
header verbatim.
|
|
178
|
+
"""
|
|
179
|
+
if not isinstance(name, str) or not name:
|
|
180
|
+
raise TypeError("c.extern_type type name must be a non-empty string")
|
|
181
|
+
return type(name, (_ExternValue,), {"__slots__": ()})
|
|
182
|
+
|
|
183
|
+
@staticmethod
|
|
184
|
+
def extern_const(name: str, value: object) -> object:
|
|
185
|
+
"""Register an external C constant and return its CPython placeholder value.
|
|
186
|
+
|
|
187
|
+
`LIMIT = c.extern_const("LIMIT", 256)` means LIMIT's definition is in an external
|
|
188
|
+
header. The H mode only emits ``extern const <T> LIMIT;`` (no value), and the C mode
|
|
189
|
+
emits **nothing at all** -- the definition is provided by the header brought in via
|
|
190
|
+
``c.include`` and resolved at link time.
|
|
191
|
+
|
|
192
|
+
value is the placeholder value on the CPython track (so the development track can use
|
|
193
|
+
it as an ordinary number); the C track ignores it. name must match the C name in the
|
|
194
|
+
header verbatim.
|
|
195
|
+
"""
|
|
196
|
+
if not isinstance(name, str) or not name:
|
|
197
|
+
raise TypeError("c.extern_const name must be a non-empty string")
|
|
198
|
+
return value
|
|
199
|
+
|
|
200
|
+
@staticmethod
|
|
201
|
+
def extern_var(name: str, type: object) -> object:
|
|
202
|
+
"""Register an external C variable and return the CPython placeholder value 0.
|
|
203
|
+
|
|
204
|
+
`shared = c.extern_var("shared", int32)` means shared's definition is in an external
|
|
205
|
+
translation unit. The H mode only emits ``extern <T> shared;``, and the C mode emits
|
|
206
|
+
**nothing at all** -- the definition is provided externally. type is the type name
|
|
207
|
+
(e.g. ``int32``); the CPython track ignores it and only returns the 0 placeholder.
|
|
208
|
+
name must match the external C variable's name verbatim.
|
|
209
|
+
"""
|
|
210
|
+
if not isinstance(name, str) or not name:
|
|
211
|
+
raise TypeError("c.extern_var name must be a non-empty string")
|
|
212
|
+
return 0
|
|
213
|
+
|
|
214
|
+
@staticmethod
|
|
215
|
+
def define(name: str, value: object) -> object:
|
|
216
|
+
"""Register a C macro (pure text substitution, no type) and return its CPython value.
|
|
217
|
+
|
|
218
|
+
`BUFSZ = c.define("BUFSZ", 256)` emits ``#define BUFSZ 256`` on both the H and C
|
|
219
|
+
ends; value also serves as the placeholder value on the CPython track. name is the
|
|
220
|
+
macro name, and value may be an integer / float / string literal. Macros take no part
|
|
221
|
+
in type checking (they are text substitution).
|
|
222
|
+
|
|
223
|
+
The assignment form requires name to match the bound variable name
|
|
224
|
+
(``BUFSZ = c.define("BUFSZ", ...)``), otherwise it is an error at compile time; a bare
|
|
225
|
+
call ``c.define("BUFSZ", ...)`` only emits the macro definition and the name does not
|
|
226
|
+
enter scope. A macro name must not collide with a compiler-inlined runtime identifier,
|
|
227
|
+
otherwise it would pollute the generated C.
|
|
228
|
+
|
|
229
|
+
When written inside a compile-time conditional block it still uses the two-argument
|
|
230
|
+
form and emits the ``#define`` in place in source order; same-named macros in
|
|
231
|
+
different branches are mutually exclusively selected by ``-D``, with no duplicate check
|
|
232
|
+
and no bound-name constraint.
|
|
233
|
+
"""
|
|
234
|
+
if not isinstance(name, str) or not name:
|
|
235
|
+
raise TypeError("c.define name must be a non-empty string")
|
|
236
|
+
return value
|
|
237
|
+
|
|
238
|
+
@staticmethod
|
|
239
|
+
def typedef(type_expr: object) -> object:
|
|
240
|
+
"""Give a local alias to a type expression (definition side), returning the type
|
|
241
|
+
expression itself.
|
|
242
|
+
|
|
243
|
+
`int32_ptr = c.typedef(Ptr[int32])` is equivalent to the C
|
|
244
|
+
``typedef int32_t *int32_ptr;``. The function returns the passed-in type expression,
|
|
245
|
+
so on the CPython track ``int32_ptr`` is simply an alias for ``Ptr[int32]`` and can be
|
|
246
|
+
used normally in annotations. The compiler emits a ``typedef`` accordingly; this is
|
|
247
|
+
symmetric with the external type ``c.extern_type("DEV")`` (consumption side, zero emit).
|
|
248
|
+
"""
|
|
249
|
+
return type_expr
|
|
250
|
+
|
|
251
|
+
@staticmethod
|
|
252
|
+
def packed(target: object) -> object:
|
|
253
|
+
"""Decorator (no parentheses): give a struct / union a packed layout.
|
|
254
|
+
|
|
255
|
+
``@c.packed`` makes the compiler emit ``__attribute__((packed))`` so there are no
|
|
256
|
+
alignment gaps between fields. It is a **bare decorator** with no parentheses; the
|
|
257
|
+
CPython track returns the decorated class verbatim. The value is decided by the
|
|
258
|
+
compiler; the user does not write alignment numbers like ``1`` / ``2``.
|
|
259
|
+
"""
|
|
260
|
+
return target
|
|
261
|
+
|
|
262
|
+
@staticmethod
|
|
263
|
+
def word(bits: int) -> "callable":
|
|
264
|
+
"""Decorator: declare the total bit width of a bit-field aggregate type (unit: bits),
|
|
265
|
+
written only once.
|
|
266
|
+
|
|
267
|
+
``@c.word(32)`` + ``class Ctrl(Struct): en: Bits[1]; mode: Bits[3]``
|
|
268
|
+
compiles to ``uint32_t en : 1; uint32_t mode : 3;`` with an automatic
|
|
269
|
+
``uint32_t : 28;`` padding. The backing integer, the remaining bit width and the
|
|
270
|
+
padding fields are all computed by the compiler; the user does not write them. The
|
|
271
|
+
allowed W values are 8 / 16 / 32 / 64. The CPython track is a no-op decorator.
|
|
272
|
+
"""
|
|
273
|
+
if isinstance(bits, bool) or not isinstance(bits, int):
|
|
274
|
+
raise TypeError("c.word width must be an integer number of bits")
|
|
275
|
+
|
|
276
|
+
def decorate(target: object) -> object:
|
|
277
|
+
return target
|
|
278
|
+
|
|
279
|
+
return decorate
|
|
280
|
+
|
|
281
|
+
@staticmethod
|
|
282
|
+
def inline(target: object) -> object:
|
|
283
|
+
"""Decorator (no parentheses): compile a function as ``static inline``.
|
|
284
|
+
|
|
285
|
+
The CPython track returns the function verbatim without changing call behavior; the
|
|
286
|
+
C track appends ``inline`` after ``static``. It is a **bare decorator** with no
|
|
287
|
+
parentheses.
|
|
288
|
+
"""
|
|
289
|
+
return target
|
|
290
|
+
|
|
291
|
+
@staticmethod
|
|
292
|
+
def section(name: str) -> _SectionSpec:
|
|
293
|
+
"""Declare a C section and return a section descriptor.
|
|
294
|
+
|
|
295
|
+
Two usages: a function uses it directly as a decorator ``@c.section(".ramfunc")``;
|
|
296
|
+
a variable is first bound to a name and then subscripted in the annotation:
|
|
297
|
+
|
|
298
|
+
noinit_sec = c.section(".noinit")
|
|
299
|
+
scratch: noinit_sec[uint32]
|
|
300
|
+
|
|
301
|
+
Both compile to ``__attribute__((section("...")))``. A global variable with a section
|
|
302
|
+
name is a statically sized static object on the C side, usable for holding an
|
|
303
|
+
interrupt vector table. On the CPython track everything is a no-op: the decorator
|
|
304
|
+
returns the function verbatim and the subscript returns the type verbatim; the section
|
|
305
|
+
name only takes effect at compile time and the descriptor generates no C code.
|
|
306
|
+
"""
|
|
307
|
+
if not isinstance(name, str) or not name:
|
|
308
|
+
raise TypeError("c.section name must be a non-empty string")
|
|
309
|
+
return _SectionSpec(name)
|
|
310
|
+
|
|
311
|
+
@staticmethod
|
|
312
|
+
def aligned(n: int) -> "callable":
|
|
313
|
+
"""Decorator: align an aggregate type or function to N bytes.
|
|
314
|
+
|
|
315
|
+
``@c.aligned(16)`` compiles to ``__attribute__((aligned(16)))``. N must be a positive
|
|
316
|
+
integer (aligned to a power of two). The CPython track is a no-op decorator that
|
|
317
|
+
returns the decorated object verbatim.
|
|
318
|
+
"""
|
|
319
|
+
if isinstance(n, bool) or not isinstance(n, int) or n <= 0:
|
|
320
|
+
raise TypeError("c.aligned requires a positive integer width")
|
|
321
|
+
if n & (n - 1) != 0:
|
|
322
|
+
raise TypeError("c.aligned width must be a power of two")
|
|
323
|
+
|
|
324
|
+
def decorate(target: object) -> object:
|
|
325
|
+
return target
|
|
326
|
+
|
|
327
|
+
return decorate
|
|
328
|
+
|
|
329
|
+
@staticmethod
|
|
330
|
+
def weak(target: object) -> object:
|
|
331
|
+
"""Decorator (no parentheses): compile a function as a weak symbol
|
|
332
|
+
(``__attribute__((weak))``).
|
|
333
|
+
|
|
334
|
+
Used for weak default implementations of HAL / callbacks, overridable by a strong
|
|
335
|
+
symbol at link time. The CPython track returns the function verbatim.
|
|
336
|
+
"""
|
|
337
|
+
return target
|
|
338
|
+
|
|
339
|
+
@staticmethod
|
|
340
|
+
def visibility(name: str) -> "callable":
|
|
341
|
+
"""Decorator: set the visibility of a function symbol.
|
|
342
|
+
|
|
343
|
+
``@c.visibility("hidden")`` compiles to ``__attribute__((visibility("hidden")))``.
|
|
344
|
+
name is one of ``"hidden"`` / ``"default"`` / ``"protected"``. The CPython track is a
|
|
345
|
+
no-op.
|
|
346
|
+
"""
|
|
347
|
+
if not isinstance(name, str) or name not in ("hidden", "default", "protected"):
|
|
348
|
+
raise TypeError("c.visibility name must be 'hidden', 'default' or 'protected'")
|
|
349
|
+
|
|
350
|
+
def decorate(target: object) -> object:
|
|
351
|
+
return target
|
|
352
|
+
|
|
353
|
+
return decorate
|
|
354
|
+
|
|
355
|
+
@staticmethod
|
|
356
|
+
def barrier() -> None:
|
|
357
|
+
"""Emit a memory barrier (a standalone statement, no return value).
|
|
358
|
+
|
|
359
|
+
The C track emits ``__asm__ volatile("" ::: "memory");`` (a compiler barrier, no
|
|
360
|
+
header needed), used to order accesses to variables shared between an ISR and the main
|
|
361
|
+
loop. Cross-core CPU barriers require toolchain support that this language does not
|
|
362
|
+
provide as an atomic read/write API. The output is compiled as C99.
|
|
363
|
+
"""
|
|
364
|
+
return None
|
|
365
|
+
|
|
366
|
+
@staticmethod
|
|
367
|
+
def clz(x: int) -> int:
|
|
368
|
+
"""Return the number of leading zero bits before the highest set bit of x
|
|
369
|
+
(GCC/Clang ``__builtin_clz``, 32-bit operand)."""
|
|
370
|
+
x &= 0xFFFFFFFF
|
|
371
|
+
return 32 - x.bit_length() if x else 32
|
|
372
|
+
|
|
373
|
+
@staticmethod
|
|
374
|
+
def ctz(x: int) -> int:
|
|
375
|
+
"""Return the number of trailing zero bits after the lowest set bit of x
|
|
376
|
+
(GCC/Clang ``__builtin_ctz``, 32-bit operand)."""
|
|
377
|
+
x &= 0xFFFFFFFF
|
|
378
|
+
return (x & -x).bit_length() - 1 if x else 32
|
|
379
|
+
|
|
380
|
+
@staticmethod
|
|
381
|
+
def popcount(x: int) -> int:
|
|
382
|
+
"""Return the number of set bits (1s) in the binary representation of x
|
|
383
|
+
(GCC/Clang ``__builtin_popcount``, 32-bit operand)."""
|
|
384
|
+
return bin(x & 0xFFFFFFFF).count("1")
|
|
385
|
+
|
|
386
|
+
@staticmethod
|
|
387
|
+
def export(name: str) -> "callable":
|
|
388
|
+
"""Decorator: export a function defined in this file to the linker under a given C name.
|
|
389
|
+
|
|
390
|
+
``@c.export("Reset_Handler")`` generates a C function literally named ``Reset_Handler``:
|
|
391
|
+
with no module prefix / ``f_`` prefix, without ``static``, and with the ``used``
|
|
392
|
+
attribute so the linker does not drop an entry point that is never referenced from the
|
|
393
|
+
Python side. The name must match the symbol name in the linker script and startup code
|
|
394
|
+
verbatim. The CPython track is a no-op decorator.
|
|
395
|
+
|
|
396
|
+
The difference from ``@c.extern_function``: the latter means the definition lives
|
|
397
|
+
elsewhere (only a declaration is emitted), whereas the former means the definition is
|
|
398
|
+
here and you only want to expose this symbol name externally.
|
|
399
|
+
"""
|
|
400
|
+
if not isinstance(name, str) or not name:
|
|
401
|
+
raise TypeError("c.export name must be a non-empty string")
|
|
402
|
+
|
|
403
|
+
def decorate(fn: "callable") -> "callable":
|
|
404
|
+
return fn
|
|
405
|
+
|
|
406
|
+
return decorate
|
|
407
|
+
|
|
408
|
+
@staticmethod
|
|
409
|
+
def extern_function(name: object = None) -> "callable":
|
|
410
|
+
"""Decorator: declare a function as an external C function.
|
|
411
|
+
|
|
412
|
+
The C track only generates an `extern` declaration; the function body is not compiled.
|
|
413
|
+
The function body is a mock implementation on the CPython track, executed normally when
|
|
414
|
+
called, and still must satisfy the full language checks.
|
|
415
|
+
|
|
416
|
+
Example:
|
|
417
|
+
@c.extern_function
|
|
418
|
+
def HAL_Init() -> void:
|
|
419
|
+
pass # pure declaration; the Python track call returns None
|
|
420
|
+
|
|
421
|
+
@c.extern_function("HAL_ADC_Read")
|
|
422
|
+
def adc_read(pin: int32) -> int32:
|
|
423
|
+
return pin * 2 # the Python track runs this mock; the C track discards it
|
|
424
|
+
"""
|
|
425
|
+
# When called without parentheses, Python passes the decorated function directly in.
|
|
426
|
+
if callable(name) and not isinstance(name, str):
|
|
427
|
+
return _CInterop.extern_function()(name)
|
|
428
|
+
if name is not None and (not isinstance(name, str) or not name):
|
|
429
|
+
raise TypeError("c.extern_function name must be a non-empty string")
|
|
430
|
+
|
|
431
|
+
def decorate(fn: "callable") -> "callable":
|
|
432
|
+
c_name = name if isinstance(name, str) else getattr(fn, "__name__", "")
|
|
433
|
+
fn.__embeddedpy_extern__ = c_name # type: ignore[attr-defined]
|
|
434
|
+
return fn
|
|
435
|
+
|
|
436
|
+
return decorate
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
c = _CInterop()
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
__all__ = [
|
|
443
|
+
"c",
|
|
444
|
+
]
|
embeddedpy/io.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""File I/O category of embeddedpy: io.open / io.read / io.write / io.close.
|
|
2
|
+
|
|
3
|
+
External usage: `from embeddedpy.io import File, io`.
|
|
4
|
+
|
|
5
|
+
Corresponding to C's fopen / fread / fwrite / fclose:
|
|
6
|
+
|
|
7
|
+
f: File = io.open("data.bin", "rb") # C: py_file f = py_open(...);
|
|
8
|
+
data: bytes = io.read(f, 64) # C: py_bytes data = py_file_read(f, 64);
|
|
9
|
+
io.write(f, b"hello") # C: py_file_write(f, ...);
|
|
10
|
+
io.close(f) # C: py_file_close(f);
|
|
11
|
+
|
|
12
|
+
Files are always opened in binary mode (a 'b' is appended if missing from the mode),
|
|
13
|
+
so the byte behavior of both tracks is exactly identical (not altered by the platform's
|
|
14
|
+
newline translation).
|
|
15
|
+
|
|
16
|
+
`File` is a handle type: on the C side it is the py_file struct (wrapping a void*
|
|
17
|
+
that points to FILE*); on the CPython side it is a real file object. Handles are
|
|
18
|
+
passed by value; do not use them after close.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
# This module defines open itself, so grab the builtin one first
|
|
24
|
+
_builtin_open = open
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class File:
|
|
28
|
+
"""File handle.
|
|
29
|
+
|
|
30
|
+
Compiles to the py_file struct on the C side; on the CPython side it is a real
|
|
31
|
+
file object. This class is only used for type annotation and isinstance checks;
|
|
32
|
+
it carries no data.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
__slots__ = ()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _NullFile:
|
|
39
|
+
"""Empty handle used when opening fails.
|
|
40
|
+
|
|
41
|
+
On the C track, a failed ``py_open`` returns a ``py_file`` with ``fp == NULL``;
|
|
42
|
+
the development track must not raise an exception, otherwise the two tracks would
|
|
43
|
+
diverge on the failure path. This object's truth value is False, and read/write/close
|
|
44
|
+
are all no-ops, matching the C side's behavior of ``py_file_read`` / ``py_file_write`` /
|
|
45
|
+
``py_file_close`` on NULL.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
__slots__ = ()
|
|
49
|
+
|
|
50
|
+
def __bool__(self) -> bool:
|
|
51
|
+
return False
|
|
52
|
+
|
|
53
|
+
def read(self, cap: int) -> bytes:
|
|
54
|
+
return b""
|
|
55
|
+
|
|
56
|
+
def write(self, data: bytes) -> int:
|
|
57
|
+
return 0
|
|
58
|
+
|
|
59
|
+
def close(self) -> None:
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
NULL_FILE = _NullFile()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class _IOAPI:
|
|
67
|
+
"""File read/write API: free functions, no methods introduced."""
|
|
68
|
+
|
|
69
|
+
__slots__ = ()
|
|
70
|
+
|
|
71
|
+
@staticmethod
|
|
72
|
+
def open(path: str, mode: str = "rb") -> Any:
|
|
73
|
+
"""Open a file and return a File handle.
|
|
74
|
+
|
|
75
|
+
path is the file name; mode is the same as C's fopen ("r" / "w" / "a" / "rb" / "wb" ...).
|
|
76
|
+
On failure, returns an empty handle (fp is NULL) and does not raise -- in embedded
|
|
77
|
+
contexts it is preferable to check yourself.
|
|
78
|
+
"""
|
|
79
|
+
if not isinstance(path, str):
|
|
80
|
+
raise TypeError("io.open path must be a string")
|
|
81
|
+
if not isinstance(mode, str):
|
|
82
|
+
raise TypeError("io.open mode must be a string")
|
|
83
|
+
if "b" not in mode:
|
|
84
|
+
mode = mode + "b"
|
|
85
|
+
try:
|
|
86
|
+
return _builtin_open(path, mode)
|
|
87
|
+
except OSError:
|
|
88
|
+
return NULL_FILE
|
|
89
|
+
|
|
90
|
+
@staticmethod
|
|
91
|
+
def read(f: Any, cap: int) -> bytes:
|
|
92
|
+
"""Read at most cap bytes from the file and return bytes.
|
|
93
|
+
|
|
94
|
+
When the end of file is reached, the number of bytes returned is less than cap;
|
|
95
|
+
when cap is 0, an empty byte string is returned.
|
|
96
|
+
"""
|
|
97
|
+
if isinstance(cap, bool) or not isinstance(cap, int):
|
|
98
|
+
raise TypeError("io.read cap must be an integer")
|
|
99
|
+
if cap < 0:
|
|
100
|
+
raise ValueError("io.read cap must not be negative")
|
|
101
|
+
return f.read(cap)
|
|
102
|
+
|
|
103
|
+
@staticmethod
|
|
104
|
+
def write(f: Any, data: bytes) -> int:
|
|
105
|
+
"""Write all of data to the file and return the number of bytes written."""
|
|
106
|
+
return f.write(data)
|
|
107
|
+
|
|
108
|
+
@staticmethod
|
|
109
|
+
def close(f: Any) -> None:
|
|
110
|
+
"""Close the file. Do not use this handle after closing."""
|
|
111
|
+
f.close()
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
io = _IOAPI()
|
|
115
|
+
|
|
116
|
+
__all__ = [
|
|
117
|
+
"File",
|
|
118
|
+
"io",
|
|
119
|
+
]
|