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,364 @@
1
+ """Preprocessor layer: translate Python shapes into C preprocessor directives.
2
+
3
+ The user writes valid Python syntax; the compiler only does shape translation,
4
+ it does not evaluate or judge macros:
5
+
6
+ if c.defined("STM32F4") and c.macro("HW_VER") >= 2:
7
+ c.define("BOARD", 1)
8
+ c.include("regs_f4.h")
9
+ elif c.defined("STM32F1"):
10
+ c.pragma("pack(1)")
11
+ else:
12
+ c.error("unsupported board")
13
+
14
+ Which branch of ``#if`` / ``#elif`` / ``#else`` / ``#endif`` survives in the
15
+ output is decided by the downstream C compiler's ``-D``; this compiler only
16
+ guarantees line-by-line predictability.
17
+
18
+ Three groups of members:
19
+
20
+ - Conditional-expression functions ``c.defined(name)`` / ``c.macro(name)``:
21
+ only appear in ``if`` / ``elif`` conditions, translated to ``defined(X)`` /
22
+ ``X``.
23
+ - Directive functions ``c.emit / pragma / error / warning / undef``:
24
+ module-level standalone statements or standalone statements inside a condition
25
+ block, translated to one line of C preprocessor text.
26
+ - Named declarations ``c.define(name, value)`` / ``c.include(header)``: when
27
+ written inside a condition block they emit ``#define`` / ``#include`` in source
28
+ order in place; when written at module top level they still go through the
29
+ existing registration area (macro area / file header), with unchanged behavior.
30
+
31
+ ``c.emit`` is the general escape hatch: for C constructs that have no dedicated
32
+ Python shape yet, the surrounding remains a valid Python statement. Common
33
+ capabilities use the named calls.
34
+ """
35
+
36
+ import ast
37
+ from typing import List, Optional, Tuple
38
+
39
+ from .cgen_helpers import c_string
40
+
41
+ # Directive functions: rendered into one (or more) line(s) of preprocessor text
42
+ PP_DIRECTIVES = ("emit", "pragma", "error", "warning", "undef")
43
+ # Conditional-expression functions: rendered as an identifier inside the #if
44
+ # expression
45
+ PP_COND_FUNCS = ("defined", "macro")
46
+ PP_MEMBERS = frozenset(PP_DIRECTIVES + PP_COND_FUNCS)
47
+ # Named declarations: only emitted in-place inside compile-time condition blocks;
48
+ # at module top level they are still handled by the registration area
49
+ PP_DECL_MEMBERS = ("define", "include")
50
+
51
+ _CMP_OPS = {
52
+ ast.Eq: "==",
53
+ ast.NotEq: "!=",
54
+ ast.Lt: "<",
55
+ ast.LtE: "<=",
56
+ ast.Gt: ">",
57
+ ast.GtE: ">=",
58
+ }
59
+ _BIN_OPS = {
60
+ ast.Add: "+",
61
+ ast.Sub: "-",
62
+ ast.Mult: "*",
63
+ ast.Div: "/",
64
+ ast.FloorDiv: "/",
65
+ ast.Mod: "%",
66
+ ast.BitAnd: "&",
67
+ ast.BitOr: "|",
68
+ ast.BitXor: "^",
69
+ ast.LShift: "<<",
70
+ ast.RShift: ">>",
71
+ }
72
+ _UNARY_OPS = {
73
+ ast.Not: "!",
74
+ ast.USub: "-",
75
+ ast.UAdd: "+",
76
+ ast.Invert: "~",
77
+ }
78
+
79
+
80
+ def pp_member_name(node: ast.AST) -> Optional[str]:
81
+ """Recognize c.<member>(...); only return the member name registered in this module."""
82
+ if not isinstance(node, ast.Call):
83
+ return None
84
+ f = node.func
85
+ if not (
86
+ isinstance(f, ast.Attribute)
87
+ and isinstance(f.value, ast.Name)
88
+ and f.value.id == "c"
89
+ ):
90
+ return None
91
+ return f.attr if f.attr in PP_MEMBERS else None
92
+
93
+
94
+ def pp_decl_member_name(node: ast.AST) -> Optional[str]:
95
+ """Recognize c.define(...) / c.include(...) calls; only return these two member names."""
96
+ if not isinstance(node, ast.Call):
97
+ return None
98
+ f = node.func
99
+ if not (
100
+ isinstance(f, ast.Attribute)
101
+ and isinstance(f.value, ast.Name)
102
+ and f.value.id == "c"
103
+ ):
104
+ return None
105
+ return f.attr if f.attr in PP_DECL_MEMBERS else None
106
+
107
+
108
+ def is_pp_directive_call(node: ast.AST) -> bool:
109
+ """Whether this is a c.emit / pragma / error / warning / undef call."""
110
+ name = pp_member_name(node)
111
+ return name is not None and name in PP_DIRECTIVES
112
+
113
+
114
+ def is_pp_block_directive(stmt: ast.AST) -> bool:
115
+ """Whether a standalone statement is a preprocessor directive to be emitted in source order.
116
+
117
+ Named declarations inside condition blocks are recognized via the
118
+ ``_pp_block_decl`` marker set during prescan, so that module-top-level
119
+ ``c.define`` / ``c.include`` (which belong to the registration area) are not
120
+ mistaken for in-place directives.
121
+ """
122
+ if not isinstance(stmt, ast.Expr):
123
+ return False
124
+ if getattr(stmt, "_pp_block_decl", False):
125
+ return True
126
+ return isinstance(stmt.value, ast.Call) and is_pp_directive_call(stmt.value)
127
+
128
+
129
+ def _looks_pp_cond(node: ast.AST) -> bool:
130
+ """Whether the condition contains c.defined / c.macro (does not require the expression to have passed validation)."""
131
+ return any(
132
+ isinstance(n, ast.Call) and pp_member_name(n) in PP_COND_FUNCS
133
+ for n in ast.walk(node)
134
+ )
135
+
136
+
137
+ def mark_pp_block_decls(tree: ast.Module) -> None:
138
+ """Prescan: mark c.define / c.include standalone statements inside compile-time condition blocks.
139
+
140
+ Must run before ``_collect_includes`` / ``_scan_bare_decls``: the former judges
141
+ any include not at module top level as an error and pulls it into the file
142
+ header, the latter collects top-level defines into the macro area. Marked
143
+ statements are skipped by both, and instead emitted in-place by codegen inside
144
+ the ``#if`` block.
145
+
146
+ Nested ``elif`` is an If inside orelse in the AST, handled the same way
147
+ recursively.
148
+ """
149
+ def walk(body: list) -> None:
150
+ for stmt in body:
151
+ if isinstance(stmt, ast.If) and _looks_pp_cond(stmt.test):
152
+ stmt._pp_if = True
153
+ walk(stmt.body)
154
+ walk(stmt.orelse)
155
+ elif (
156
+ isinstance(stmt, ast.Expr)
157
+ and isinstance(stmt.value, ast.Call)
158
+ and pp_decl_member_name(stmt.value) is not None
159
+ ):
160
+ stmt._pp_block_decl = True
161
+ stmt.value._pp_block_decl = True
162
+
163
+ walk(tree.body)
164
+
165
+
166
+ def _literal_arg(call: ast.Call, name: str) -> Tuple[Optional[str], Optional[str]]:
167
+ """Fetch the single string-constant argument, returning (text, error)."""
168
+ if call.keywords:
169
+ return None, f"c.{name} does not support keyword arguments"
170
+ if len(call.args) != 1:
171
+ return None, f"c.{name} requires exactly one string literal"
172
+ arg = call.args[0]
173
+ if not (isinstance(arg, ast.Constant) and isinstance(arg.value, str)):
174
+ return None, f"c.{name} argument must be a string literal"
175
+ return arg.value, None
176
+
177
+
178
+ def render_directive(call: ast.Call) -> Tuple[List[str], Optional[str]]:
179
+ """Render a directive call into several lines of C preprocessor text, returning (lines, error)."""
180
+ name = pp_member_name(call)
181
+ if name not in PP_DIRECTIVES:
182
+ return [], f"not a preprocessor directive: c.{name}"
183
+ text, err = _literal_arg(call, name)
184
+ if err is not None:
185
+ return [], err
186
+ assert text is not None
187
+ if name == "emit":
188
+ # Emit verbatim: multi-line text is allowed; the output is whatever the
189
+ # user wrote
190
+ return text.splitlines() or [""], None
191
+ if not text or "\n" in text or "\r" in text:
192
+ return [], f"c.{name} argument must be a single non-empty line"
193
+ if name == "undef":
194
+ if not _is_c_ident(text):
195
+ return [], "c.undef argument must be a C identifier"
196
+ return [f"#undef {text}"], None
197
+ prefix = {"pragma": "#pragma ", "error": "#error ", "warning": "#warning "}[name]
198
+ return [prefix + text], None
199
+
200
+
201
+ def _c_literal(value: object) -> str:
202
+ """C literal for a macro value: integer, float, or C string (reusing the output's escaping rules)."""
203
+ if isinstance(value, int):
204
+ return str(value)
205
+ if isinstance(value, float):
206
+ return repr(value)
207
+ return c_string(str(value))
208
+
209
+
210
+ def render_decl_directive(call: ast.Call) -> Tuple[List[str], Optional[str]]:
211
+ """Render c.define / c.include inside a condition block into one line of C directive, returning (lines, error).
212
+
213
+ The parameter shape matches the same-named module-top-level calls, so the
214
+ user does not need to remember two styles; the only difference is the emit
215
+ location: top level goes to the registration area, inside a condition block
216
+ it is emitted in-place in source order.
217
+ """
218
+ name = pp_decl_member_name(call)
219
+ if name is None:
220
+ return [], "not a named preprocessor declaration"
221
+ if name == "define":
222
+ if call.keywords or len(call.args) != 2:
223
+ return [], "c.define requires exactly (name: str, value)"
224
+ name_arg, val_arg = call.args
225
+ if not (
226
+ isinstance(name_arg, ast.Constant)
227
+ and isinstance(name_arg.value, str)
228
+ and name_arg.value
229
+ ):
230
+ return [], "c.define name must be a non-empty string literal"
231
+ if not _is_c_ident(name_arg.value):
232
+ return [], "c.define name must be a C identifier"
233
+ if (
234
+ not isinstance(val_arg, ast.Constant)
235
+ or isinstance(val_arg.value, bool)
236
+ or not isinstance(val_arg.value, (int, float, str))
237
+ ):
238
+ return [], "c.define value must be an integer, float, or string literal"
239
+ if isinstance(val_arg.value, str) and (
240
+ "\n" in val_arg.value or "\r" in val_arg.value
241
+ ):
242
+ return [], "c.define value must be a single line"
243
+ return [f"#define {name_arg.value} {_c_literal(val_arg.value)}"], None
244
+
245
+ system = False
246
+ for kw in call.keywords:
247
+ if kw.arg != "system":
248
+ return [], f"c.include does not support keyword argument {kw.arg}"
249
+ if not (isinstance(kw.value, ast.Constant) and kw.value.value is True):
250
+ return [], "c.include 'system' argument must be True"
251
+ system = True
252
+ if len(call.args) not in (1, 2):
253
+ return [], (
254
+ "c.include requires a header name; the optional second argument "
255
+ "is system=True"
256
+ )
257
+ header = call.args[0]
258
+ if not (
259
+ isinstance(header, ast.Constant)
260
+ and isinstance(header.value, str)
261
+ and header.value
262
+ ):
263
+ return [], "c.include header name must be a non-empty string literal"
264
+ if any(ch in header.value for ch in ('"', "\n", "\r")):
265
+ return [], "c.include header name contains an invalid character"
266
+ if len(call.args) == 2:
267
+ flag = call.args[1]
268
+ if not (isinstance(flag, ast.Constant) and flag.value is True):
269
+ return [], "c.include second argument must be system=True"
270
+ system = True
271
+ if system:
272
+ return [f"#include <{header.value}>"], None
273
+ return [f'#include "{header.value}"'], None
274
+
275
+
276
+ def _is_c_ident(text: str) -> bool:
277
+ """C identifier: starts with an ASCII letter/underscore, followed by letters/digits/underscores."""
278
+ if not text or not (text[0].isalpha() or text[0] == "_"):
279
+ return False
280
+ return all(ch.isalnum() or ch == "_" for ch in text) and text.isascii()
281
+
282
+
283
+ def validate_cond(node: ast.AST) -> Optional[str]:
284
+ """Validate whether the condition expression falls within the whitelist, returning an English error or None."""
285
+ if isinstance(node, ast.Call):
286
+ name = pp_member_name(node)
287
+ if name in PP_COND_FUNCS:
288
+ _, err = _literal_arg(node, name)
289
+ if err is not None:
290
+ return err
291
+ text = node.args[0].value
292
+ if not _is_c_ident(text):
293
+ return f"c.{name} argument must be a C identifier"
294
+ return None
295
+ return "only c.defined(...) and c.macro(...) are allowed in a preprocessor condition"
296
+ if isinstance(node, ast.BoolOp):
297
+ if not isinstance(node.op, (ast.And, ast.Or)):
298
+ return "unsupported boolean operator in preprocessor condition"
299
+ for value in node.values:
300
+ err = validate_cond(value)
301
+ if err is not None:
302
+ return err
303
+ return None
304
+ if isinstance(node, ast.UnaryOp):
305
+ if type(node.op) not in _UNARY_OPS:
306
+ return "unsupported unary operator in preprocessor condition"
307
+ return validate_cond(node.operand)
308
+ if isinstance(node, ast.BinOp):
309
+ if type(node.op) not in _BIN_OPS:
310
+ return "unsupported arithmetic operator in preprocessor condition"
311
+ for part in (node.left, node.right):
312
+ err = validate_cond(part)
313
+ if err is not None:
314
+ return err
315
+ return None
316
+ if isinstance(node, ast.Compare):
317
+ if len(node.ops) != 1:
318
+ return "chained comparison is not supported in a preprocessor condition"
319
+ for op in node.ops:
320
+ if type(op) not in _CMP_OPS:
321
+ return "unsupported comparison in preprocessor condition"
322
+ parts = [node.left] + list(node.comparators)
323
+ for part in parts:
324
+ err = validate_cond(part)
325
+ if err is not None:
326
+ return err
327
+ return None
328
+ if isinstance(node, ast.Constant):
329
+ if isinstance(node.value, bool) or not isinstance(node.value, int):
330
+ return "preprocessor condition only allows integer literals"
331
+ return None
332
+ return (
333
+ "preprocessor condition only allows c.defined(...), c.macro(...), "
334
+ "integer literals, comparisons, and/or/not, arithmetic and bitwise operators"
335
+ )
336
+
337
+
338
+ def is_pp_cond(node: ast.AST) -> bool:
339
+ """Whether the condition is a compile-time preprocessor condition (already validated by validate_cond's shape)."""
340
+ return validate_cond(node) is None
341
+
342
+
343
+ def render_cond(node: ast.AST) -> str:
344
+ """Render the #if expression; must be validated with validate_cond before calling."""
345
+ if isinstance(node, ast.Call):
346
+ name = pp_member_name(node)
347
+ text = node.args[0].value
348
+ return f"defined({text})" if name == "defined" else text
349
+ if isinstance(node, ast.BoolOp):
350
+ sep = " && " if isinstance(node.op, ast.And) else " || "
351
+ return "(" + sep.join(render_cond(v) for v in node.values) + ")"
352
+ if isinstance(node, ast.UnaryOp):
353
+ return f"({_UNARY_OPS[type(node.op)]}{render_cond(node.operand)})"
354
+ if isinstance(node, ast.BinOp):
355
+ return f"({render_cond(node.left)} {_BIN_OPS[type(node.op)]} {render_cond(node.right)})"
356
+ if isinstance(node, ast.Compare):
357
+ left = render_cond(node.left)
358
+ pieces = []
359
+ for op, right in zip(node.ops, node.comparators):
360
+ pieces.append(f"{_CMP_OPS[type(op)]} {render_cond(right)}")
361
+ return "(" + left + " " + " ".join(pieces) + ")"
362
+ if isinstance(node, ast.Constant):
363
+ return str(node.value)
364
+ raise AssertionError("render_cond called on an unvalidated node")