Repository navigation
Add opt-in optimizing AST backend and optimization levels #137
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+352
−26
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| # Optimizing compiler (experimental) | ||
|
|
||
| REPY's Python backend now has explicit optimization levels: `-O0` (default, | ||
| no new passes), `-O1` (bounded literal folding and constant expression branch | ||
| simplification), and `-O2`/`-O3` (also immutable literal membership). | ||
| Levels 2 and 3 currently have identical behavior, reserved for further passes. | ||
| No application code is executed during optimization. | ||
|
|
||
| Set `optimization = 2` in `[config]` or override with | ||
| `repy repyconfig.toml -O2`. Single-file compilation and repycl use the | ||
| nearest project config; a CLI override wins. The Python API accepts | ||
| `optimization=2`. The lower-level `optimize_python(source, level=2)` | ||
| returns a source string and pass counts via an OptimizationResult. | ||
|
|
||
| This is an opt-in AST pass framework, not a native runtime backend. | ||
| Some passes overlap with CPython's own optimizer. Do not assume runtime | ||
| speedups without benchmarking. AST rewriting may change comments, formatting, | ||
| line numbers, and introspection. Dynamic calls, attribute access, arbitrary | ||
| user-defined objects, security checks and arithmetic semantics remain intact. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,167 @@ | ||
| """Opt-in, bounded AST optimization passes for generated Python. | ||
|
|
||
| Never evaluate application code or import application modules at compile time. | ||
| Only exact immutable literal values are eligible for constant evaluation. | ||
| """ | ||
| import ast | ||
| import operator | ||
| from collections import Counter | ||
| from dataclasses import dataclass | ||
|
|
||
| MAX_LITERAL_ITEMS = 128 | ||
| MAX_INT_BITS = 256 | ||
| MAX_STRING_SIZE = 4096 | ||
| MAX_AST_NODES = 200_000 | ||
| MAX_SOURCE_CHARS = 8 * 1024 * 1024 | ||
|
|
||
| _OPERATORS = { | ||
| ast.Eq: operator.eq, ast.NotEq: operator.ne, ast.Lt: operator.lt, | ||
| ast.LtE: operator.le, ast.Gt: operator.gt, ast.GtE: operator.ge, | ||
| } | ||
| _INTEGER_OPERATORS = { | ||
| ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, | ||
| ast.FloorDiv: operator.floordiv, ast.Mod: operator.mod, | ||
| ast.BitAnd: operator.and_, ast.BitOr: operator.or_, ast.BitXor: operator.xor, | ||
| } | ||
| _LITERAL_TYPES = (int, bool, str, bytes, type(None)) | ||
|
|
||
|
|
||
| def validate_optimization(level): | ||
| if type(level) is not int or not 0 <= level <= 3: | ||
| raise ValueError("optimization must be an integer from 0 to 3") | ||
| return level | ||
|
|
||
|
|
||
| def _literal(node): | ||
| if not isinstance(node, ast.Constant) or type(node.value) not in _LITERAL_TYPES: | ||
| return False | ||
| value = node.value | ||
| if type(value) is int: | ||
| return value.bit_length() <= MAX_INT_BITS | ||
| if isinstance(value, (str, bytes)): | ||
| return len(value) <= MAX_STRING_SIZE | ||
| return True | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class OptimizationResult: | ||
| source: str | ||
| passes: dict[str, int] | ||
|
|
||
|
|
||
| class _Optimizer(ast.NodeTransformer): | ||
| def __init__(self, level): | ||
| self.level = level | ||
| self.stats = Counter() | ||
|
|
||
| def replace(self, node, replacement, name): | ||
| self.stats[name] += 1 | ||
| return ast.copy_location(replacement, node) | ||
|
|
||
| def visit_Compare(self, node): | ||
| node = self.generic_visit(node) | ||
| if len(node.ops) != 1: | ||
| return node | ||
| rhs = node.comparators[0] | ||
| op = node.ops[0] | ||
| if type(op) in _OPERATORS and _literal(node.left) and _literal(rhs): | ||
| try: | ||
| result = _OPERATORS[type(op)](node.left.value, rhs.value) | ||
| except TypeError: | ||
| return node | ||
| return self.replace(node, ast.Constant(result), "literal_comparison") | ||
| # A tuple here is never exposed to user code. Preserve equality order; | ||
| # do not substitute sets (which change hashing and comparison behavior). | ||
| if (self.level >= 2 and isinstance(op, (ast.In, ast.NotIn)) | ||
| and isinstance(rhs, ast.List) and len(rhs.elts) <= MAX_LITERAL_ITEMS | ||
| and all(_literal(item) for item in rhs.elts)): | ||
| node.comparators[0] = ast.copy_location(ast.Tuple(elts=rhs.elts, ctx=ast.Load()), rhs) | ||
| self.stats["immutable_membership"] += 1 | ||
| return node | ||
|
|
||
| def visit_BinOp(self, node): | ||
| node = self.generic_visit(node) | ||
| if (type(node.op) in _INTEGER_OPERATORS and _literal(node.left) | ||
| and _literal(node.right) and type(node.left.value) is int | ||
| and type(node.right.value) is int): | ||
| try: | ||
| result = _INTEGER_OPERATORS[type(node.op)](node.left.value, node.right.value) | ||
| except ArithmeticError: | ||
| return node | ||
| if result.bit_length() <= MAX_INT_BITS: | ||
| return self.replace(node, ast.Constant(result), "literal_arithmetic") | ||
| return node | ||
|
|
||
| def visit_Expr(self, node): | ||
| # Turning a leading conditional string expression into a literal | ||
| # would create a new module/class/function docstring. | ||
| if isinstance(node.value, ast.IfExp): | ||
| return node | ||
| return self.generic_visit(node) | ||
|
|
||
| def visit_IfExp(self, node): | ||
| node.test = self.visit(node.test) | ||
| if isinstance(node.test, ast.Constant) and type(node.test.value) is bool: | ||
| discarded = node.orelse if node.test.value else node.body | ||
| # Removing bindings, await/yield or name references can change | ||
| # scope, closure contents or generator status. | ||
| if not any(isinstance(n, (ast.Name, ast.NamedExpr, ast.Yield, ast.YieldFrom, ast.Await)) | ||
| for n in ast.walk(discarded)): | ||
| chosen = node.body if node.test.value else node.orelse | ||
| return self.replace(node, self.visit(chosen), "constant_branch") | ||
| node.body = self.visit(node.body) | ||
| node.orelse = self.visit(node.orelse) | ||
| return node | ||
|
|
||
| def visit_AnnAssign(self, node): | ||
| # Annotations may be stringized or evaluated lazily. | ||
| if node.value is not None: | ||
| node.value = self.visit(node.value) | ||
| return node | ||
|
|
||
| def visit_arg(self, node): | ||
| return node | ||
|
|
||
| def visit_FunctionDef(self, node): | ||
| saved = node.returns | ||
| node.returns = None | ||
| try: | ||
| return self.generic_visit(node) | ||
| finally: | ||
| node.returns = saved | ||
|
|
||
| visit_AsyncFunctionDef = visit_FunctionDef | ||
|
|
||
| def visit_UnaryOp(self, node): | ||
| node = self.generic_visit(node) | ||
| if isinstance(node.op, ast.Not) and _literal(node.operand): | ||
| return self.replace(node, ast.Constant(not node.operand.value), "literal_truth") | ||
| return node | ||
|
sourcery-ai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
|
|
||
| def optimize_python(source, level=1): | ||
| """Return optimized source and pass counts; level 0 preserves source verbatim. | ||
|
|
||
| Levels 2/3 currently enable the same conservative additional passes. | ||
| AST roundtripping changes formatting/comments only when a pass fires. | ||
| """ | ||
| validate_optimization(level) | ||
| if not isinstance(source, str): | ||
| raise TypeError("source must be a string") | ||
| if level == 0: | ||
| return OptimizationResult(source, {}) | ||
| if len(source) > MAX_SOURCE_CHARS: | ||
| return OptimizationResult(source, {}) | ||
| tree = ast.parse(source) | ||
| for count, _ in enumerate(ast.walk(tree), 1): | ||
| if count > MAX_AST_NODES: | ||
| return OptimizationResult(source, {}) | ||
| # Validate the parsed AST before rewriting control flow. | ||
| compile(tree, "<repy optimizer>", "exec") | ||
| transform = _Optimizer(level) | ||
| tree = transform.visit(tree) | ||
| if not transform.stats: | ||
| return OptimizationResult(source, {}) | ||
| result = ast.unparse(ast.fix_missing_locations(tree)) + "\n" | ||
| compile(result, "<repy optimized>", "exec") | ||
| return OptimizationResult(result, dict(sorted(transform.stats.items()))) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.