Skip to content

Commit 84e1d7f

Browse files
committed
Make the @micropython.native decorator no-op if support isn't enabled
When adding the ability for boards to turn on the `@micropython.native`, `viper`, and `asm_thumb` decorators it was pointed out that it's somewhat awkward to write libraries and drivers that can take advantage of this since the decorators raise `SyntaxErrors` if they aren't enabled. In the case of `viper` and `asm_thumb` this behavior makes sense as they require writing non-normative code. Drivers could have a normal and viper/thumb implementation and implement them as such: ```python try: import _viper_impl as _impl except SyntaxError: import _python_impl as _impl def do_thing(): return _impl.do_thing() ``` For `native`, however, this behavior and the pattern to work around it is less than ideal. Since `native` code should also be valid Python code (although not necessarily the other way around) using the pattern above means *duplicating* the Python implementation and adding `@micropython.native` in the code. This is an unnecessary maintenance burden. This commit *modifies* the behavior of the `@micropython.native` decorator. On boards with `CIRCUITPY_ENABLE_MPY_NATIVE` turned on it operates as usual. On boards with it turned off it does *nothing*- it doesn't raise a `SyntaxError` and doesn't apply optimizations. This means we can write our drivers/libraries once and take advantage of speedups on boards where they are enabled.
1 parent e560b41 commit 84e1d7f

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

py/compile.c

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -775,13 +775,22 @@ STATIC bool compile_built_in_decorator(compiler_t *comp, int name_len, mp_parse_
775775
qstr attr = MP_PARSE_NODE_LEAF_ARG(name_nodes[1]);
776776
if (attr == MP_QSTR_bytecode) {
777777
*emit_options = MP_EMIT_OPT_BYTECODE;
778-
#if MICROPY_EMIT_NATIVE
778+
// @micropython.native decorator.
779779
} else if (attr == MP_QSTR_native) {
780+
// Different from MicroPython: native doesn't raise SyntaxError if native support isn't
781+
// compiled, it just passes through the function unmodified.
782+
#if MICROPY_EMIT_NATIVE
780783
*emit_options = MP_EMIT_OPT_NATIVE_PYTHON;
784+
#else
785+
return true;
786+
#endif
787+
#if MICROPY_EMIT_NATIVE
788+
// @micropython.viper decorator.
781789
} else if (attr == MP_QSTR_viper) {
782790
*emit_options = MP_EMIT_OPT_VIPER;
783-
#endif
791+
#endif
784792
#if MICROPY_EMIT_INLINE_ASM
793+
// @micropython.asm_thumb decorator.
785794
} else if (attr == ASM_DECORATOR_QSTR) {
786795
*emit_options = MP_EMIT_OPT_ASM;
787796
#endif

0 commit comments

Comments
 (0)