From 84e1d7f304fc92f69eb1120682fe91dff7188ddc Mon Sep 17 00:00:00 2001 From: Thea Flowers Date: Tue, 12 Nov 2019 12:33:52 -0800 Subject: [PATCH] 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. --- py/compile.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/py/compile.c b/py/compile.c index 8b17935bda..77715d3fe5 100644 --- a/py/compile.c +++ b/py/compile.c @@ -775,13 +775,22 @@ STATIC bool compile_built_in_decorator(compiler_t *comp, int name_len, mp_parse_ qstr attr = MP_PARSE_NODE_LEAF_ARG(name_nodes[1]); if (attr == MP_QSTR_bytecode) { *emit_options = MP_EMIT_OPT_BYTECODE; -#if MICROPY_EMIT_NATIVE + // @micropython.native decorator. } else if (attr == MP_QSTR_native) { + // Different from MicroPython: native doesn't raise SyntaxError if native support isn't + // compiled, it just passes through the function unmodified. + #if MICROPY_EMIT_NATIVE *emit_options = MP_EMIT_OPT_NATIVE_PYTHON; + #else + return true; + #endif + #if MICROPY_EMIT_NATIVE + // @micropython.viper decorator. } else if (attr == MP_QSTR_viper) { *emit_options = MP_EMIT_OPT_VIPER; -#endif + #endif #if MICROPY_EMIT_INLINE_ASM + // @micropython.asm_thumb decorator. } else if (attr == ASM_DECORATOR_QSTR) { *emit_options = MP_EMIT_OPT_ASM; #endif