|
| 1 | +# The MIT License (MIT) |
| 2 | +# |
| 3 | +# Copyright (c) 2024 Jeff Epler for Adafruit Industries |
| 4 | +# |
| 5 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | +# of this software and associated documentation files (the "Software"), to deal |
| 7 | +# in the Software without restriction, including without limitation the rights |
| 8 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | +# copies of the Software, and to permit persons to whom the Software is |
| 10 | +# furnished to do so, subject to the following conditions: |
| 11 | +# |
| 12 | +# The above copyright notice and this permission notice shall be included in |
| 13 | +# all copies or substantial portions of the Software. |
| 14 | +# |
| 15 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 21 | +# THE SOFTWARE. |
| 22 | + |
| 23 | +# Filter program removes some code patterns introduced by type checking, |
| 24 | +# to move towards zero overhead static typing in circuitpython libraries |
| 25 | +# |
| 26 | +# Recognized: |
| 27 | +# from __future__ import ... -- eliminated |
| 28 | +# try: import typing -- eliminated, but first except: preserved |
| 29 | +# try: from typing import ... -- eliminated, but first except: preserved |
| 30 | +# if STATIC_TYPING: -- transformed to 'if 0:' |
| 31 | +# if sys.implementation_name... -- transformed to unconditional if |
| 32 | +# __version__ = ... -- set to library version string |
| 33 | +# |
| 34 | +# mpy-cross does constant propagation and dead branch elimination of |
| 35 | +# 'if 0:' and 'if 1:' |
| 36 | +# |
| 37 | +# Depends on the file being black-formatted! |
| 38 | + |
| 39 | +import pathlib |
| 40 | +import sys |
| 41 | +import ast |
| 42 | + |
| 43 | +VERBOSE = 0 |
| 44 | + |
| 45 | +# The canonical spelling of this test... |
| 46 | +sys_implementation_is_circuitpython = ast.unparse(ast.parse('sys.implementation.name == "circuitpython"')) |
| 47 | +sys_implementation_not_circuitpython = ast.unparse(ast.parse('not sys.implementation.name == "circuitpython"')) |
| 48 | +sys_implementation_not_circuitpython2 = ast.unparse(ast.parse('sys.implementation.name != "circuitpython"')) |
| 49 | + |
| 50 | +def munge(src: pathlib.Path|str, version_str: str) -> str: |
| 51 | + path = pathlib.Path(src) |
| 52 | + replacements = {} |
| 53 | + |
| 54 | + def replace(line, new): |
| 55 | + if VERBOSE: |
| 56 | + replacements[line] = f"{new:<40s} ### {lines[line]}" |
| 57 | + else: |
| 58 | + replacements[line] = new |
| 59 | + |
| 60 | + def blank_range(node): |
| 61 | + for i in range(node.lineno, node.end_lineno+1): |
| 62 | + replace(i, "") |
| 63 | + |
| 64 | + def unblank_range(node): |
| 65 | + for i in range(node.lineno, node.end_lineno+1): |
| 66 | + replacements.pop(i, None) |
| 67 | + |
| 68 | + def imports_from_typing(node): |
| 69 | + if isinstance(node, ast.Import) and node.names[0].name == 'typing': |
| 70 | + return True |
| 71 | + if isinstance(node, ast.ImportFrom) and node.module == 'typing': |
| 72 | + return True |
| 73 | + return False |
| 74 | + |
| 75 | + def process_statement(node): |
| 76 | + # filter out 'from future import...' |
| 77 | + if isinstance(node, ast.ImportFrom): |
| 78 | + if node.module == '__future__': |
| 79 | + blank_range(node) |
| 80 | + # filter out 'try: import typing...' |
| 81 | + # but preserve the first 'except:' or 'except ImportError' |
| 82 | + elif isinstance(node, ast.Try): |
| 83 | + b = node.body[0] |
| 84 | + if imports_from_typing(node.body[0]): |
| 85 | + blank_range(node) |
| 86 | + for h in node.handlers: |
| 87 | + if h.type is None or ast.unparse(h.type) == 'ImportError' or ast.unparse(h.type) == 'Exception': |
| 88 | + unblank_range(h) |
| 89 | + replace(h.lineno, 'if 1:') |
| 90 | + break |
| 91 | + return |
| 92 | + elif isinstance(node, ast.If): |
| 93 | + node_test = ast.unparse(node.test) |
| 94 | + # return the statements in the 'if' branch of 'if sys.implementation...: ...' |
| 95 | + if node_test == sys_implementation_is_circuitpython: |
| 96 | + replace(node.lineno, 'if 1:') |
| 97 | + # return the statements in the 'else' branch of 'if sys.implementation...: ...' |
| 98 | + elif node_test == sys_implementation_not_circuitpython or node_test == sys_implementation_not_circuitpython2: |
| 99 | + replace(node.lineno, 'if 0:') |
| 100 | + # return the statements in the else branch of 'if TYPE_CHECKING: ...' |
| 101 | + elif node_test == 'TYPE_CHECKING': |
| 102 | + replace(node.lineno, 'if 0:') |
| 103 | + elif isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name) and node.targets[0].id == '__version__': |
| 104 | + replace(node.lineno, f"__version__ = \"{version_str}\"") |
| 105 | + |
| 106 | + content = pathlib.Path(path).read_text(encoding="utf-8") |
| 107 | + # Insert a blank line 0 because ast line numbers are 1-based |
| 108 | + lines = [''] + content.rstrip().split('\n') |
| 109 | + a = ast.parse(content, path.name) |
| 110 | + |
| 111 | + for node in a.body: process_statement(node) |
| 112 | + |
| 113 | + result = [] |
| 114 | + for i in range(1, len(lines)): |
| 115 | + result.append(replacements.get(i, lines[i])) |
| 116 | + |
| 117 | + return "\n".join(result) + "\n" |
0 commit comments