Repository navigation
Add native runtime function specialization with exact-type fallback #138
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
+571
−13
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
23ef20b
Compile explicit native function shapes to guarded C runtime kernels
sharktide 26ed627
Bound native calls and harden dispatch and generated names
sharktide 6ce337c
Preserve ordinary Python names and check signals at native boundaries
sharktide a8d732c
Merge optimizer foundation and preserve both opt-in compiler paths
sharktide 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,40 @@ | ||
| # Native runtime specialization (experimental) | ||
|
|
||
| `<OPTIMIZE native=True>` on a module-level synchronous function selects a | ||
| compiler-recognized native kernel. Currently supported: | ||
|
|
||
| * A zero-initialized accumulator adding each integer in an iterable. | ||
| * A zero-initialized accumulator adding `len(item)` for each string. | ||
| * A loop returning true on the first substring match, otherwise false | ||
| (arguments in order: text, needles). | ||
|
|
||
| Example: | ||
|
|
||
| ```python | ||
| <OPTIMIZE native=True> | ||
| def count_chars(values: list[str]) -> int { | ||
| total = 0 | ||
| for item in values { | ||
| total += len(item) | ||
| } | ||
| return total | ||
| } | ||
| ``` | ||
|
|
||
| The compiler retains the original function and emits guarded dispatch to | ||
| ahead-of-time compiled C kernels shipped in the REPY native extension. | ||
| No compiler or subprocess is invoked on application startup. It is not | ||
| arbitrary function-to-C code generation. Unsupported source shapes fail | ||
| compilation rather than silently promising a speedup. | ||
|
|
||
| Exact built-in lists/tuples, strings and integers are optimized. Subclasses, | ||
| iterators, overflow, keyword arguments, tracing/profiling and overridden len | ||
| use the original Python function. Arithmetic never wraps or coerces integers. | ||
| The C kernels hold the GIL and use no user callbacks. Fast-path work is bounded to 32,768 items and an estimated 8 Mi code-point search budget; larger workloads fall back to interruptible Python. Active Python monitoring also falls back. REPY_PURE_PYTHON=1 or a | ||
| missing extension uses the original function. Opt-in wrappers change function | ||
| introspection and do not promise identical tracing/timing. Do not use this | ||
| as a substitute for authorization or billing correctness tests. | ||
|
|
||
| Do not combine native=True with other OPTIMIZE options or decorators. | ||
|
|
||
| The GIL stays held for short, bounded kernels over borrowed references from mutable Python lists. Releasing it mid-scan would permit concurrent list mutation and unsafe borrowed-pointer access. Pending signals are checked before and after bounded fast paths, not while borrowing objects; larger workloads use the original Python implementation. |
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,194 @@ | ||
| """Recognize narrow, auditable native function IR patterns. | ||
|
|
||
| The original Python function is always emitted. Only explicitly annotated | ||
| functions are eligible; unsupported patterns raise a useful compile error. | ||
| """ | ||
| import ast | ||
| import hashlib | ||
| import unicodedata | ||
|
|
||
|
|
||
|
|
||
| def native_options(options): | ||
| call = ast.parse(f"_options({options})", mode="eval").body | ||
| native = [kw.value for kw in call.keywords if kw.arg == "native"] | ||
| if not native: | ||
| return False | ||
| if (len(native) != 1 or call.args or len(call.keywords) != 1 | ||
| or not isinstance(native[0], ast.Constant) or native[0].value is not True): | ||
| raise SyntaxError("Native compilation requires <OPTIMIZE native=True> on its own") | ||
| return True | ||
|
|
||
|
|
||
| def native_marker(source): | ||
| return _unique(source) | ||
|
|
||
|
|
||
| def _unique(source): | ||
| normalized = unicodedata.normalize("NFKC", source) | ||
| index = 0 | ||
| while f"_repy_native_marker_{index}" in normalized: | ||
| index += 1 | ||
| return f"_repy_native_marker_{index}" | ||
|
|
||
|
|
||
| def _name(node, value): | ||
| return isinstance(node, ast.Name) and node.id == value | ||
|
|
||
|
|
||
| def _constant(node, value): | ||
| return isinstance(node, ast.Constant) and type(node.value) is type(value) and node.value == value | ||
|
|
||
|
|
||
| def _body(fn): | ||
| body = fn.body | ||
| if (body and isinstance(body[0], ast.Expr) | ||
| and isinstance(body[0].value, ast.Constant) and isinstance(body[0].value.value, str)): | ||
| return body[1:] | ||
| return body | ||
|
|
||
|
|
||
| def recognize(fn): | ||
| """Return a kernel ID for a structurally identical supported function.""" | ||
| args = fn.args | ||
| if (args.posonlyargs or args.kwonlyargs or args.vararg or args.kwarg or args.defaults | ||
| or any(a.annotation is not None and not isinstance(a.annotation, (ast.Name, ast.Subscript)) | ||
| for a in args.args)): | ||
| return None | ||
| names = [arg.arg for arg in args.args] | ||
| body = _body(fn) | ||
| if len(names) == 1 and len(body) == 3: | ||
| init, loop, ret = body | ||
| if (isinstance(init, ast.Assign) and len(init.targets) == 1 | ||
| and isinstance(init.targets[0], ast.Name) and _constant(init.value, 0) | ||
| and isinstance(loop, ast.For) and isinstance(loop.target, ast.Name) | ||
| and _name(loop.iter, names[0]) and not loop.orelse and len(loop.body) == 1 | ||
| and isinstance(ret, ast.Return)): | ||
| accumulator, item = init.targets[0].id, loop.target.id | ||
| update = loop.body[0] | ||
| if (len({accumulator, item, names[0]}) == 3 | ||
| and isinstance(update, ast.AugAssign) and _name(update.target, accumulator) | ||
| and isinstance(update.op, ast.Add) and _name(ret.value, accumulator)): | ||
| if _name(update.value, item): | ||
| return "sum_ints" | ||
| call = update.value | ||
| if (isinstance(call, ast.Call) and _name(call.func, "len") | ||
| and len(call.args) == 1 and _name(call.args[0], item) and not call.keywords | ||
| and "len" not in {accumulator, item, names[0]}): | ||
| return "sum_lengths" | ||
| if len(names) == 2 and len(body) == 2: | ||
| loop, ret = body | ||
| if (isinstance(loop, ast.For) and isinstance(loop.target, ast.Name) | ||
| and loop.target.id not in names and _name(loop.iter, names[1]) | ||
| and not loop.orelse and len(loop.body) == 1 | ||
| and isinstance(ret, ast.Return) and _constant(ret.value, False)): | ||
| condition = loop.body[0] | ||
| if (isinstance(condition, ast.If) and not condition.orelse and len(condition.body) == 1 | ||
| and isinstance(condition.body[0], ast.Return) and _constant(condition.body[0].value, True)): | ||
| test = condition.test | ||
| if (isinstance(test, ast.Compare) and len(test.ops) == 1 | ||
| and isinstance(test.ops[0], ast.In) and _name(test.left, loop.target.id) | ||
| and _name(test.comparators[0], names[0])): | ||
| return "contains_any" | ||
| return None | ||
|
|
||
|
|
||
| def lower_native(source, marker): | ||
| """Replace compiler markers with native runtime decorators.""" | ||
| tree = ast.parse(source) | ||
| # Native wrappers are only supported at module scope: class/nested functions | ||
| # may have class cells or closure semantics that this backend doesn't model. | ||
| marked = [] | ||
| for node in ast.walk(tree): | ||
| if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): | ||
| if any(_name(dec, marker) for dec in node.decorator_list): | ||
| if node not in tree.body or not isinstance(node, ast.FunctionDef): | ||
| raise SyntaxError("native=True requires a module-level synchronous function") | ||
| if len(node.decorator_list) != 1: | ||
| raise SyntaxError("Native functions cannot have additional decorators") | ||
| kernel = recognize(node) | ||
| if kernel is None: | ||
| raise SyntaxError( | ||
| f"Unsupported native function {node.name!r}: use a supported reduction or membership loop" | ||
| ) | ||
| marked.append((node, kernel)) | ||
| if not marked: | ||
| raise SyntaxError("No eligible native function") | ||
| digest = hashlib.sha256(source.encode('utf-8', errors='surrogatepass')).hexdigest()[:24] | ||
| alias = f'_repy_native_dispatch_{digest}' | ||
| while alias in unicodedata.normalize('NFKC', source): | ||
| alias += '_' | ||
| for node, kernel in marked: | ||
| node.decorator_list = [ast.Call(func=ast.Name(id=alias, ctx=ast.Load()), | ||
| args=[ast.Constant(kernel)], keywords=[])] | ||
| index = 0 | ||
| for i, node in enumerate(tree.body): | ||
| if (i == 0 and isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) | ||
| and isinstance(node.value.value, str)): | ||
| index = i + 1 | ||
| elif isinstance(node, ast.ImportFrom) and node.module == "__future__": | ||
| index = i + 1 | ||
| else: | ||
| break | ||
| tree.body.insert(index, ast.ImportFrom(module="restructuredpython.native_runtime", | ||
| names=[ast.alias(name="native_function", asname=alias)], level=0)) | ||
| return ast.unparse(ast.fix_missing_locations(tree)) + "\n" | ||
|
|
||
|
|
||
| def validate_native_bindings(source): | ||
| """Reject a generated import name colliding with any included source. | ||
|
|
||
| Each independently transpiled source has a deterministic name. Validate | ||
| the complete module as a second line of defense against deliberate or | ||
| accidental collisions. Dynamic globals() mutation is outside this contract. | ||
| """ | ||
| if "_repy_native_dispatch_" not in source: | ||
| return source | ||
| tree = ast.parse(source) | ||
| imports = {} | ||
| for node in ast.walk(tree): | ||
| if isinstance(node, ast.ImportFrom) and node.module == "restructuredpython.native_runtime": | ||
| for alias in node.names: | ||
| if alias.name == "native_function" and (alias.asname or "").startswith("_repy_native_dispatch_"): | ||
| imports[alias.asname] = alias | ||
| if not imports: | ||
| return source | ||
| allowed = set(imports.values()) | ||
| for node in ast.walk(tree): | ||
| if isinstance(node, ast.FunctionDef): | ||
| for dec in node.decorator_list: | ||
| if (isinstance(dec, ast.Call) and isinstance(dec.func, ast.Name) | ||
| and dec.func.id in imports and len(dec.args) == 1 | ||
| and isinstance(dec.args[0], ast.Constant) | ||
| and dec.args[0].value in {"sum_lengths", "sum_ints", "contains_any"} | ||
| and not dec.keywords): | ||
| allowed.add(dec.func) | ||
| for node in ast.walk(tree): | ||
| if node in allowed: | ||
| continue | ||
| if isinstance(node, ast.Name): | ||
| names = [node.id] | ||
| elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.ExceptHandler, | ||
| ast.MatchAs, ast.MatchStar)): | ||
| names = [node.name] | ||
| elif isinstance(node, ast.MatchMapping): | ||
| names = [node.rest] | ||
| elif isinstance(node, ast.arg): | ||
| names = [node.arg] | ||
| elif isinstance(node, ast.alias): | ||
| names = [node.asname or node.name.split(".")[0]] | ||
| if (node.name == "native_function" and node.asname in imports): | ||
| # Identical generated imports across included files are safe. | ||
| if node in imports.values(): | ||
| continue | ||
| if any(isinstance(parent, ast.ImportFrom) | ||
| and parent.module == "restructuredpython.native_runtime" | ||
| and node in parent.names for parent in ast.walk(tree)): | ||
| continue | ||
| elif isinstance(node, (ast.Global, ast.Nonlocal)): | ||
| names = node.names | ||
| else: | ||
| continue | ||
| if any(name in imports for name in names): | ||
| raise SyntaxError("Native compiler generated-name collision in combined source") | ||
| return source |
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.