Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@ When changing parsing behavior, add a regression test in `tests/test_compiler.py
Use a separate branch and pull request. Keep version changes and release publication separate from ordinary fixes; package publication is a deliberate workflow dispatch.

When editing the C compiler accelerator, run the same tests with `REPY_PURE_PYTHON=1`, and use `python benchmarks/compiler.py` to compare native and reference throughput. Native wheels must pass backend-parity tests; source-only installation remains supported.

## Python compatibility: release-blocking invariant

REPY is a Python superset. Valid Python source must preserve its logical behavior under the default compiler configuration. No new syntax, optimization, runtime dependency, static typing, native compilation, memoization, concurrency, changed evaluation order, or changed error behavior may be imposed on ordinary Python. A developer may explicitly opt in through a documented REPY syntax construct, directive, CLI flag, config setting, or API option. Opt-ins must define their semantic contract and limitations; even then prefer equivalent behavior and safe fallback where practical. Never silently approximate financial arithmetic, authorization, or error handling. O0 is the default; use exact source passthrough for valid Python and regression tests comparing the generated code with CPython. Changes that violate this invariant are release blockers. Include cross-version native/fallback differential tests for new compiler features.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ repy repyconfig.toml --mode full --check

Paths are relative to the directory containing `repyconfig.toml`. Individual files use their nearest ancestor config, if present. Explicit loop unrolling is bounded by `max_unroll = 128` (config) or `--max-unroll 512` (CLI override), with a hard factor ceiling of 4096 and a separate expansion budget.

## Runtime optimization (experimental)

Use `repy main.repy -O2` or set `optimization = 2` in `[config]`. The opt-in AST optimizer performs bounded literal folding, constant expression branch simplification and immutable membership lowering. See [optimizer documentation](docs/optimizer.md); runtime improvements must be measured separately from compiler throughput.

## Compiler performance

The C accelerator handles Unicode-aware lexical scanning, delimiter nesting and top-level pipeline detection. Python retains the reference implementation and high-level compiler orchestration. This speeds up transpilation, not the execution of generated Python programs.
Expand Down
19 changes: 19 additions & 0 deletions docs/optimizer.md
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.
3 changes: 2 additions & 1 deletion restructuredpython/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"""reStructuredPython compiler and runtime API."""
from .check_syntax import check_syntax
from .parser import parse_repython
from .optimizer import optimize_python
from .restructuredpython import (
__version__, compile_file, compile_header_file, compile_project,
launch, main, parse, process_includes, run_file,
Expand All @@ -23,5 +24,5 @@
__all__ = [
"__version__", "check_syntax", "compile_file", "compile_header_file",
"compile_project", "launch", "main", "parse", "parse_repython",
"process_includes", "run_file",
"process_includes", "run_file", "optimize_python",
]
167 changes: 167 additions & 0 deletions restructuredpython/optimizer.py
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)
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
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
Comment thread
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())))
Loading
Loading