diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fda0417..3ac6ae7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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. diff --git a/README.md b/README.md index 652fe91..6ce13c5 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/docs/optimizer.md b/docs/optimizer.md new file mode 100644 index 0000000..2d3ff30 --- /dev/null +++ b/docs/optimizer.md @@ -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. diff --git a/restructuredpython/__init__.py b/restructuredpython/__init__.py index 02003ed..90565fd 100644 --- a/restructuredpython/__init__.py +++ b/restructuredpython/__init__.py @@ -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, @@ -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", ] diff --git a/restructuredpython/optimizer.py b/restructuredpython/optimizer.py new file mode 100644 index 0000000..337fc4d --- /dev/null +++ b/restructuredpython/optimizer.py @@ -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 + + +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, "", "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, "", "exec") + return OptimizationResult(result, dict(sorted(transform.stats.items()))) diff --git a/restructuredpython/restructuredpython.py b/restructuredpython/restructuredpython.py index 818a595..b530771 100644 --- a/restructuredpython/restructuredpython.py +++ b/restructuredpython/restructuredpython.py @@ -25,6 +25,7 @@ from pathlib import Path from .parser import parse_repython, split_includes +from .optimizer import optimize_python, validate_optimization from .unroll import DEFAULT_MAX_UNROLL, validate_max_unroll from .tempload import execute_code_temporarily @@ -46,17 +47,26 @@ def _source_root(directory): return directory -def _configured_unroll(root, override): - if override is not None: - return validate_max_unroll(override) +def _config_table(root): config_path = root / "repyconfig.toml" if not config_path.is_file(): - return DEFAULT_MAX_UNROLL + return {} with config_path.open("rb") as file: config = tomllib.load(file).get("config", {}) if not isinstance(config, dict): raise ValueError("[config] must be a TOML table") - return validate_max_unroll(config.get("max_unroll", DEFAULT_MAX_UNROLL)) + return config + + +def _configured_optimization(root, override): + return validate_optimization(_config_table(root).get("optimization", 0) + if override is None else override) + + +def _configured_unroll(root, override): + if override is not None: + return validate_max_unroll(override) + return validate_max_unroll(_config_table(root).get("max_unroll", DEFAULT_MAX_UNROLL)) def _read_source(path): @@ -108,11 +118,12 @@ def _process_includes(code, directory, mode, stack, seen, root, max_unroll): return "".join(headers), body -def compile_header_file(header_filename, mode="classic", *, max_unroll=None): +def compile_header_file(header_filename, mode="classic", *, max_unroll=None, optimization=None): """Transpile a header, resolving nested includes inside its source tree.""" path = Path(header_filename).resolve() root = _source_root(path.parent) - return _expand_header(path, mode, (), set(), root, _configured_unroll(root, max_unroll)) + generated = _expand_header(path, mode, (), set(), root, _configured_unroll(root, max_unroll)) + return optimize_python(generated, _configured_optimization(root, optimization)).source def process_includes(code, input_file=".", mode="classic", *, include_root=None, @@ -134,14 +145,15 @@ def process_includes(code, input_file=".", mode="classic", *, include_root=None, def parse(source_code, *, filename=".", mode="classic", include_root=None, - max_unroll=None): + max_unroll=None, optimization=None): """Transpile text without executing it; includes are confined to the source root.""" directory = Path.cwd().resolve() if str(filename) == "." else Path(filename).resolve().parent root = Path(include_root).resolve() if include_root is not None else _source_root(directory) max_unroll = _configured_unroll(root, max_unroll) headers, body = process_includes(source_code, filename, mode, include_root=root, max_unroll=max_unroll) - return headers + parse_repython(body, mode, max_unroll=max_unroll) + generated = headers + parse_repython(body, mode, max_unroll=max_unroll) + return optimize_python(generated, _configured_optimization(root, optimization)).source def _output_path(source, output=None): @@ -159,11 +171,11 @@ def _output_path(source, output=None): return target -def _generate(source, *, include_root=None, mode="classic", max_unroll=None): +def _generate(source, *, include_root=None, mode="classic", max_unroll=None, optimization=None): if source.suffix.lower() != ".repy": raise ValueError(f"Expected a .repy source file: {source}") code = parse(_read_source(source), filename=source, mode=mode, include_root=include_root, - max_unroll=max_unroll) + max_unroll=max_unroll, optimization=optimization) compiled = compile(code, str(source), "exec") return code, compiled @@ -242,17 +254,17 @@ def _write_outputs(outputs): def compile_file(filename, output=None, *, check=False, include_root=None, - max_unroll=None): + max_unroll=None, optimization=None): """Validate and compile a .repy file, returning the output path.""" source = Path(filename) target = _output_path(source, output) - code, _ = _generate(source, include_root=include_root, max_unroll=max_unroll) + code, _ = _generate(source, include_root=include_root, max_unroll=max_unroll, optimization=optimization) if not check: _write_outputs([(target, code)]) return target -def compile_project(filename, *, mode=None, check=False, max_unroll=None): +def compile_project(filename, *, mode=None, check=False, max_unroll=None, optimization=None): """Compile sources relative to the directory containing the config.""" config_path = Path(filename).resolve() with config_path.open("rb") as file: @@ -269,6 +281,7 @@ def compile_project(filename, *, mode=None, check=False, max_unroll=None): raise ValueError("config.compile must be 'all'") max_unroll = validate_max_unroll(config.get("max_unroll", DEFAULT_MAX_UNROLL) if max_unroll is None else max_unroll) + optimization = validate_optimization(config.get("optimization", 0) if optimization is None else optimization) root = config_path.parent patterns = config.get("exclude", []) if not isinstance(patterns, list) or not all(isinstance(p, str) for p in patterns): @@ -297,7 +310,7 @@ def excluded(path): seen[key] = source pairs.append((source, target)) # Compile each source once and stage every result before replacing any output. - outputs = [(target, _generate(source, include_root=root, max_unroll=max_unroll)[0]) + outputs = [(target, _generate(source, include_root=root, max_unroll=max_unroll, optimization=optimization)[0]) for source, target in pairs] if not check: _write_outputs(outputs) @@ -306,15 +319,15 @@ def excluded(path): for target, _ in outputs] -def _prepare_run(filename, max_unroll=None): +def _prepare_run(filename, max_unroll=None, optimization=None): source = Path(filename).resolve() - _, compiled = _generate(source, mode="launch", max_unroll=max_unroll) + _, compiled = _generate(source, mode="launch", max_unroll=max_unroll, optimization=optimization) return source, compiled -def run_file(filename, args=(), *, max_unroll=None): +def run_file(filename, args=(), *, max_unroll=None, optimization=None): """Run trusted code in a fresh main namespace (not a security sandbox).""" - source, compiled = _prepare_run(filename, max_unroll) + source, compiled = _prepare_run(filename, max_unroll, optimization) execute_code_temporarily(compiled, source, args) @@ -337,9 +350,9 @@ def _report_error(error): return 1 -def _launch_cli(filename, args=(), *, max_unroll=None): +def _launch_cli(filename, args=(), *, max_unroll=None, optimization=None): try: - source, compiled = _prepare_run(filename, max_unroll) + source, compiled = _prepare_run(filename, max_unroll, optimization) except (OSError, SyntaxError, ValueError, RuntimeError) as error: return _report_error(error) # Keep user-script tracebacks separate from compiler diagnostics. @@ -352,6 +365,7 @@ def main(argv=None): _configure_windows_stdio() parser = argparse.ArgumentParser(prog="repy", description="Compile REPY to Python.") _version_option(parser) + parser.add_argument("-O", "--optimization", type=int, choices=range(4), help="Compiler optimization level (default 0)") parser.add_argument("filename", help="A .repy file or repyconfig.toml") parser.add_argument("--max-unroll", type=int, help="Maximum explicit loop unroll factor (default 128)") parser.add_argument("-o", "--output", help="Output path for a single source") @@ -363,17 +377,17 @@ def main(argv=None): if args.launch: if args.output or args.check or args.mode: parser.error("--launch cannot be combined with --output, --check or --mode") - return _launch_cli(args.filename, max_unroll=args.max_unroll) + return _launch_cli(args.filename, max_unroll=args.max_unroll, optimization=args.optimization) try: if Path(args.filename).name == "repyconfig.toml": if args.output: parser.error("--output is only supported for single-file compilation") - outputs = compile_project(args.filename, mode=args.mode, check=args.check, max_unroll=args.max_unroll) + outputs = compile_project(args.filename, mode=args.mode, check=args.check, max_unroll=args.max_unroll, optimization=args.optimization) else: if args.mode: parser.error("--mode requires repyconfig.toml") outputs = [compile_file(args.filename, args.output, check=args.check, - max_unroll=args.max_unroll)] + max_unroll=args.max_unroll, optimization=args.optimization)] if not args.quiet: action = "Checked" if args.check else "Compiled" for output in outputs: @@ -388,11 +402,12 @@ def launch(argv=None): _configure_windows_stdio() parser = argparse.ArgumentParser(prog="repycl", description="Run a REPY script.") _version_option(parser) + parser.add_argument("-O", "--optimization", type=int, choices=range(4), help="Compiler optimization level (default 0)") parser.add_argument("--max-unroll", type=int, default=None) parser.add_argument("filename") parser.add_argument("args", nargs=argparse.REMAINDER, help="Arguments for the script") args = parser.parse_args(argv) - return _launch_cli(args.filename, args.args, max_unroll=args.max_unroll) + return _launch_cli(args.filename, args.args, max_unroll=args.max_unroll, optimization=args.optimization) if __name__ == "__main__": diff --git a/tests/test_optimizer.py b/tests/test_optimizer.py new file mode 100644 index 0000000..bac55d4 --- /dev/null +++ b/tests/test_optimizer.py @@ -0,0 +1,116 @@ +import tempfile +import unittest +from pathlib import Path + +import restructuredpython as repy +from restructuredpython.optimizer import optimize_python + + +class OptimizerTests(unittest.TestCase): + def test_disabled_and_no_change_preserve_text(self): + text = "# keep\nx = 1 < 2\n" + self.assertEqual(optimize_python(text, 0).source, text) + self.assertEqual(optimize_python("# keep\nx = f()\n", 3).source, "# keep\nx = f()\n") + + def test_passes_and_equivalence(self): + source = ("def classify(x):\n" + " return (x in ['a', 'b'], 1 < 2, not '', 4 if True else 5)\n") + optimized = optimize_python(source, 2) + self.assertEqual(set(optimized.passes), {"literal_comparison", "immutable_membership", "literal_truth", "constant_branch"}) + original, result = {}, {} + exec(source, original) + exec(optimized.source, result) + for value in ("a", "b", "😀", None, 3): + self.assertEqual(original["classify"](value), result["classify"](value)) + + def test_custom_equality_order(self): + source = "def check(x):\n return x in ['a', 'b', 'c']\n" + class Probe: + def __init__(self): + self.seen = [] + def __eq__(self, other): + self.seen.append(other) + return other == "b" + for level in (0, 2): + namespace = {} + exec(optimize_python(source, level).source, namespace) + probe = Probe() + self.assertTrue(namespace["check"](probe)) + self.assertEqual(probe.seen, ["a", "b"]) + + def test_discarded_binding_and_yield_preserved(self): + source = "def f():\n return 1 if True else (x := 2)\ndef g():\n return 1 if True else (yield 2)\n" + self.assertEqual(optimize_python(source, 3).source, source) + + def test_invalid_options_and_source(self): + for level in (-1, 4, True, "2"): + with self.assertRaises(ValueError): + optimize_python("pass", level) + with self.assertRaises(SyntaxError): + optimize_python("return 1 if True else 2", 1) + + def test_config_and_cli_override(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = root / "app.repy" + source.write_text("value = 1 < 2\n", encoding="utf-8") + config = root / "repyconfig.toml" + config.write_text('[config]\ncompile = "all"\noptimization = 2\n', encoding="utf-8") + target = repy.compile_file(source) + self.assertIn("value = True", target.read_text(encoding="utf-8")) + repy.compile_project(config, optimization=0) + self.assertIn("1 < 2", target.read_text(encoding="utf-8")) + self.assertEqual(repy.main([str(source), "-O0"]), 0) + self.assertIn("1 < 2", target.read_text(encoding="utf-8")) + self.assertEqual(repy.main([str(source), "-O2"]), 0) + self.assertIn("value = True", target.read_text(encoding="utf-8")) + + def test_includes_and_header_api(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + header = root / "shared.cdata" + header.write_text("shared = 2 + 3\n", encoding="utf-8") + main = root / "main.repy" + main.write_text("include 'shared.cdata'\nvalue = 4 + 5\n", encoding="utf-8") + output = repy.compile_file(main, optimization=2).read_text(encoding="utf-8") + self.assertIn("shared = 5", output) + self.assertIn("value = 9", output) + self.assertIn("shared = 5", repy.compile_header_file(header, optimization=2)) + + def test_arithmetic_and_discarded_pass_counts(self): + result = optimize_python("x = 2 + 3 if True else 4 + 5\n", 2) + self.assertEqual(result.passes, {"constant_branch": 1, "literal_arithmetic": 1}) + self.assertIn("x = 5", result.source) + for source in ("x = 1 // 0", "x = 2 ** 1000000", "x = 1 << 1000000"): + self.assertEqual(optimize_python(source, 2).source, source) + + def test_no_new_docstrings_or_changed_annotations(self): + source = 'from __future__ import annotations\ndef f(x: 1 + 2) -> 2 + 3:\n "one" if True else "two"\n return 4 + 5\n' + before, after = {}, {} + exec(source, before) + exec(optimize_python(source, 2).source, after) + self.assertIsNone(after["f"].__doc__) + self.assertEqual(before["f"].__annotations__, after["f"].__annotations__) + + + def test_plain_python_compatibility_default(self): + source = ( + '"""Python source: include and are text."""\n' + 'from __future__ import annotations\n' + 'include = "ordinary Python"\n' + 'def f(x: 1 + 2):\n' + ' values = {"emoji": "😀", "pipe": "|>"}\n' + ' return (x in ["a", "b"], 1 < 2, values)\n' + 'result = f("a")\n' + ) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "ordinary.repy" + path.write_text(source, encoding="utf-8") + self.assertEqual(repy.parse(source, filename=path), source) + target = repy.compile_file(path) + self.assertEqual(target.read_text(encoding="utf-8"), source) + original, generated = {}, {} + exec(source, original) + exec(target.read_text(encoding="utf-8"), generated) + self.assertEqual(generated["result"], original["result"]) + self.assertEqual(generated["f"].__annotations__, original["f"].__annotations__)