From 23ef20b18a2adb7278a21cee069d958dff01bd85 Mon Sep 17 00:00:00 2001 From: Rihaan Meher Date: Sun, 6 Dec 2026 17:18:35 -0500 Subject: [PATCH 1/3] Compile explicit native function shapes to guarded C runtime kernels --- .github/workflows/native-sanitizer.yml | 2 +- README.md | 4 + docs/native-runtime.md | 38 +++++++ restructuredpython/lib/compiler.c | 95 ++++++++++++++++++ restructuredpython/native_compiler.py | 134 +++++++++++++++++++++++++ restructuredpython/native_runtime.py | 44 ++++++++ restructuredpython/parser.py | 36 ++++--- tests/test_native_runtime.py | 93 +++++++++++++++++ 8 files changed, 433 insertions(+), 13 deletions(-) create mode 100644 docs/native-runtime.md create mode 100644 restructuredpython/native_compiler.py create mode 100644 restructuredpython/native_runtime.py create mode 100644 tests/test_native_runtime.py diff --git a/.github/workflows/native-sanitizer.yml b/.github/workflows/native-sanitizer.yml index 5e4bf3e..6be273f 100644 --- a/.github/workflows/native-sanitizer.yml +++ b/.github/workflows/native-sanitizer.yml @@ -34,4 +34,4 @@ jobs: PYTHONMALLOC: malloc run: | export LD_PRELOAD="$(gcc -print-file-name=libasan.so)" - python -m unittest discover -s tests -p 'test_native.py' -v + python -m unittest discover -s tests -p 'test_native*.py' -v diff --git a/README.md b/README.md index 652fe91..4719ad7 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. +## Native runtime specialization (experimental) + +Explicit `` functions can use guarded native C kernels for supported integer/string reductions and ordered substring matching. See [supported shapes and fallback behavior](docs/native-runtime.md). This is distinct from accelerating the compiler itself. + ## 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/native-runtime.md b/docs/native-runtime.md new file mode 100644 index 0000000..6403395 --- /dev/null +++ b/docs/native-runtime.md @@ -0,0 +1,38 @@ +# Native runtime specialization (experimental) + +`` 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 + +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. 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. diff --git a/restructuredpython/lib/compiler.c b/restructuredpython/lib/compiler.c index 0d544e9..ba4a53f 100644 --- a/restructuredpython/lib/compiler.c +++ b/restructuredpython/lib/compiler.c @@ -8,6 +8,7 @@ #define PY_SSIZE_T_CLEAN #include #include +#include static int is_open(Py_UCS4 c) { return c == '(' || c == '[' || c == '{'; @@ -254,7 +255,101 @@ static PyObject *native_pipeline_positions(PyObject *self, PyObject *mask) { return Py_BuildValue("NN", pipes, position); } + +/* These kernels operate only on exact built-in objects under the GIL. + * No user callbacks run on the fast path. NotImplemented means retry the + * original Python function, including arbitrary-precision arithmetic. */ +static Py_ssize_t sequence_size(PyObject *value) { + if (PyList_CheckExact(value)) { + return PyList_GET_SIZE(value); + } + if (PyTuple_CheckExact(value)) { + return PyTuple_GET_SIZE(value); + } + return -1; +} + +static PyObject *sequence_item(PyObject *value, Py_ssize_t i) { + return PyList_CheckExact(value) ? PyList_GET_ITEM(value, i) : PyTuple_GET_ITEM(value, i); +} + +static PyObject *native_sum_lengths(PyObject *self, PyObject *value) { + (void)self; + Py_ssize_t n = sequence_size(value); + if (n < 0) { + Py_RETURN_NOTIMPLEMENTED; + } + Py_ssize_t total = 0; + for (Py_ssize_t i = 0; i < n; ++i) { + PyObject *item = sequence_item(value, i); + if (!PyUnicode_CheckExact(item)) { + Py_RETURN_NOTIMPLEMENTED; + } + Py_ssize_t length = PyUnicode_GET_LENGTH(item); + if (length > PY_SSIZE_T_MAX - total) { + Py_RETURN_NOTIMPLEMENTED; + } + total += length; + } + return PyLong_FromSsize_t(total); +} + +static PyObject *native_sum_ints(PyObject *self, PyObject *value) { + (void)self; + Py_ssize_t n = sequence_size(value); + if (n < 0) { + Py_RETURN_NOTIMPLEMENTED; + } + long long total = 0; + for (Py_ssize_t i = 0; i < n; ++i) { + PyObject *item = sequence_item(value, i); + if (!PyLong_CheckExact(item)) { + Py_RETURN_NOTIMPLEMENTED; + } + int overflow = 0; + long long number = PyLong_AsLongLongAndOverflow(item, &overflow); + if (PyErr_Occurred()) { + return NULL; + } + if (overflow || (number > 0 && total > LLONG_MAX - number) + || (number < 0 && total < LLONG_MIN - number)) { + Py_RETURN_NOTIMPLEMENTED; + } + total += number; + } + return PyLong_FromLongLong(total); +} + +static PyObject *native_contains_any(PyObject *self, PyObject *args) { + (void)self; + PyObject *text, *needles; + if (!PyArg_ParseTuple(args, "OO:contains_any", &text, &needles)) { + return NULL; + } + Py_ssize_t n = sequence_size(needles); + if (!PyUnicode_CheckExact(text) || n < 0) { + Py_RETURN_NOTIMPLEMENTED; + } + for (Py_ssize_t i = 0; i < n; ++i) { + PyObject *needle = sequence_item(needles, i); + if (!PyUnicode_CheckExact(needle)) { + Py_RETURN_NOTIMPLEMENTED; + } + int contains = PyUnicode_Contains(text, needle); + if (contains < 0) { + return NULL; + } + if (contains) { + Py_RETURN_TRUE; + } + } + Py_RETURN_FALSE; +} + static PyMethodDef methods[] = { + {"sum_lengths", native_sum_lengths, METH_O, "Sum lengths of exact Unicode strings."}, + {"sum_ints", native_sum_ints, METH_O, "Guarded signed integer reduction."}, + {"contains_any", native_contains_any, METH_VARARGS, "Ordered Unicode substring search."}, {"lex_line", native_lex_line, METH_VARARGS, "Mask strings and comments with code-point offsets."}, {"depth_after", native_depth_after, METH_VARARGS, "Scan delimiter nesting."}, {"pipeline_positions", native_pipeline_positions, METH_O, "Find top-level pipeline and assignment offsets."}, diff --git a/restructuredpython/native_compiler.py b/restructuredpython/native_compiler.py new file mode 100644 index 0000000..8f6e2a7 --- /dev/null +++ b/restructuredpython/native_compiler.py @@ -0,0 +1,134 @@ +"""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 unicodedata + +from .unroll import marker_name + + +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 on its own") + return True + + +def native_marker(source): + return marker_name(unicodedata.normalize("NFKC", source)).replace( + "_repy_unroll_marker_", "_repy_native_marker_" + ) if "_repy_native_marker_" not in source else _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") + alias = _unique(source) + 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" diff --git a/restructuredpython/native_runtime.py b/restructuredpython/native_runtime.py new file mode 100644 index 0000000..0da6491 --- /dev/null +++ b/restructuredpython/native_runtime.py @@ -0,0 +1,44 @@ +"""Guarded runtime dispatch for compiler-recognized native kernels.""" +import builtins +import functools +import os +import sys + +_LEN = builtins.len +if os.environ.get("REPY_PURE_PYTHON") == "1": + _native = None +else: + try: + from . import _native + except ImportError: + _native = None + + +def native_function(kernel): + if kernel not in {"sum_lengths", "sum_ints", "contains_any"}: + raise ValueError(f"Unknown native kernel: {kernel}") + + def decorate(function): + implementation = getattr(_native, kernel, None) + if implementation is None: + return function + arity = 2 if kernel == "contains_any" else 1 + + @functools.wraps(function) + def call(*args, **kwargs): + if (kwargs or len(args) != arity or sys.gettrace() is not None + or sys.getprofile() is not None): + return function(*args, **kwargs) + # Do not bypass a global or custom builtins override of len. + if kernel == "sum_lengths" and function.__globals__.get( + "len", function.__builtins__.get("len")) is not _LEN: + return function(*args) + result = implementation(*args) + if result is NotImplemented: + return function(*args) + return result + + call.__repy_native_kernel__ = kernel + return call + + return decorate diff --git a/restructuredpython/parser.py b/restructuredpython/parser.py index 1efc8b5..9265cdc 100644 --- a/restructuredpython/parser.py +++ b/restructuredpython/parser.py @@ -19,6 +19,7 @@ import token import tokenize from .check_syntax import check_syntax +from .native_compiler import native_options, native_marker, lower_native from .unroll import DEFAULT_MAX_UNROLL, validate_max_unroll, directive_unroll, marker_name, expand_unroll def wrap_loops_for_optimization(code, loop_lines): @@ -512,6 +513,8 @@ def parse_repython(code, mode="classic", *, max_unroll=DEFAULT_MAX_UNROLL): loop_lines = set() unroll_marker = marker_name(code) has_unroll = False + native_tag = native_marker(code) + has_native = False for number, (line, mask, comment, continued) in enumerate(_source_lines(code), 1): stripped = mask.strip() if not continued and depth == 0: @@ -530,18 +533,25 @@ def parse_repython(code, mode="classic", *, max_unroll=DEFAULT_MAX_UNROLL): decorator = "optimize_function" else: raise SyntaxError(f"OPTIMIZE must precede a loop or function at line {number}") - factor, profile, gct = directive_unroll(pending, max_unroll) - if factor > 1: - if decorator != "optimize_loop": - raise SyntaxError("unroll applies only to loops") - modified.append(f"{indent}{unroll_marker}({factor}, {profile}, {gct})") - has_unroll = True + if native_options(pending): + if decorator != "optimize_function": + raise SyntaxError("native=True applies only to functions") + modified.append(f"{indent}@{native_tag}") + has_native = True + pending = None else: - imports.add(decorator) - if decorator == "optimize_loop": - loop_lines.add(len(modified)) - modified.append(f"{indent}@{decorator}({pending})") - pending = None + factor, profile, gct = directive_unroll(pending, max_unroll) + if factor > 1: + if decorator != "optimize_loop": + raise SyntaxError("unroll applies only to loops") + modified.append(f"{indent}{unroll_marker}({factor}, {profile}, {gct})") + has_unroll = True + else: + imports.add(decorator) + if decorator == "optimize_loop": + loop_lines.add(len(modified)) + modified.append(f"{indent}@{decorator}({pending})") + pending = None if _is_block_open(mask, line): brace = mask.rfind("{") header = line[:brace] + ":" + line[brace + 1:] @@ -585,4 +595,6 @@ def parse_repython(code, mode="classic", *, max_unroll=DEFAULT_MAX_UNROLL): result = "\n".join(lines) else: result = "\n".join(modified) - return expand_unroll(result, unroll_marker) if has_unroll else result + if has_unroll: + result = expand_unroll(result, unroll_marker) + return lower_native(result, native_tag) if has_native else result diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py new file mode 100644 index 0000000..3b3f3de --- /dev/null +++ b/tests/test_native_runtime.py @@ -0,0 +1,93 @@ +import random +import unittest +import warnings +from unittest.mock import patch + +import restructuredpython as repy +from restructuredpython.parser import NATIVE_AVAILABLE + +SOURCE = """ + +def count_chars(values: list[str]) -> int { + total = 0 + for item in values { + total += len(item) + } + return total +} + +def sum_ints(values: list[int]) -> int { + total = 0 + for value in values { + total += value + } + return total +} + +def contains_any(text: str, needles: list[str]) -> bool { + for needle in needles { + if needle in text { + return True + } + } + return False +} +""" + + +class NativeRuntimeTests(unittest.TestCase): + def setUp(self): + self.namespace = {} + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + exec(repy.parse(SOURCE), self.namespace) + + def test_runtime_dispatch_and_unicode(self): + fn = self.namespace["count_chars"] + if NATIVE_AVAILABLE: + self.assertEqual(fn.__repy_native_kernel__, "sum_lengths") + self.assertEqual(fn(["😀", "你好", "e\u0301", "\ud800"]), 6) + self.assertEqual(fn(values=["hello"]), 5) + self.assertEqual(fn(iter(["one", "two"])), 6) + self.assertEqual(fn([b"abc"]), 3) + + def test_integer_overflow_and_subclasses(self): + fn = self.namespace["sum_ints"] + for values in ([], [1, -2, 3], [2**63-1, 1], [-2**63, -1], [10**100, 1], [True, 2], [1.5, 3]): + self.assertEqual(fn(values), sum(values)) + class Custom(int): + def __radd__(self, other): + return 42 + self.assertEqual(fn([Custom(1)]), 42) + + def test_dynamic_len_binding(self): + fn = self.namespace["count_chars"] + self.namespace["len"] = lambda x: 99 + self.assertEqual(fn(["a", "b"]), 198) + del self.namespace["len"] + self.assertEqual(fn(["a"]), 1) + + def test_ordered_matching(self): + fn = self.namespace["contains_any"] + self.assertTrue(fn("你好😀", ["no", "😀"])) + self.assertFalse(fn("abc", ["z", "q"])) + self.assertTrue(fn("abc", ["a", object()])) + with self.assertRaises(TypeError): + fn("abc", [object()]) + + def test_randomized_equivalence(self): + rng = random.Random(17) + for _ in range(200): + data = [rng.choice(["hello", "😀", "你好", "", "\0"]) for _ in range(rng.randrange(100))] + ints = [rng.randint(-10**12, 10**12) for _ in data] + self.assertEqual(self.namespace["count_chars"](data), sum(map(len, data))) + self.assertEqual(self.namespace["sum_ints"](ints), sum(ints)) + self.assertEqual(self.namespace["contains_any"]("你好", data), any(x in "你好" for x in data)) + + def test_unsupported_patterns_fail(self): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + with self.assertRaisesRegex(SyntaxError, "Unsupported native function"): + repy.parse("\ndef f(x) {\n return x * 2\n}\n") + with self.assertRaisesRegex(SyntaxError, "on its own"): + repy.parse(SOURCE.replace("native=True", "native=True, cache=True")) From 26ed627bcf383f2f9c87256d8b560da17226298b Mon Sep 17 00:00:00 2001 From: Rihaan Meher Date: Sun, 6 Dec 2026 17:23:43 -0500 Subject: [PATCH 2/3] Bound native calls and harden dispatch and generated names --- docs/native-runtime.md | 2 +- restructuredpython/lib/compiler.c | 23 +++++++- restructuredpython/native_compiler.py | 70 ++++++++++++++++++++++-- restructuredpython/native_runtime.py | 15 +++-- restructuredpython/restructuredpython.py | 5 +- tests/test_native_runtime.py | 29 ++++++++++ 6 files changed, 128 insertions(+), 16 deletions(-) diff --git a/docs/native-runtime.md b/docs/native-runtime.md index 6403395..60b8dc8 100644 --- a/docs/native-runtime.md +++ b/docs/native-runtime.md @@ -30,7 +30,7 @@ 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. REPY_PURE_PYTHON=1 or a +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. diff --git a/restructuredpython/lib/compiler.c b/restructuredpython/lib/compiler.c index ba4a53f..1f22d23 100644 --- a/restructuredpython/lib/compiler.c +++ b/restructuredpython/lib/compiler.c @@ -259,6 +259,9 @@ static PyObject *native_pipeline_positions(PyObject *self, PyObject *mask) { /* These kernels operate only on exact built-in objects under the GIL. * No user callbacks run on the fast path. NotImplemented means retry the * original Python function, including arbitrary-precision arithmetic. */ +#define MAX_KERNEL_ITEMS 32768 +#define MAX_SEARCH_CODEPOINTS (8 * 1024 * 1024) + static Py_ssize_t sequence_size(PyObject *value) { if (PyList_CheckExact(value)) { return PyList_GET_SIZE(value); @@ -275,8 +278,11 @@ static PyObject *sequence_item(PyObject *value, Py_ssize_t i) { static PyObject *native_sum_lengths(PyObject *self, PyObject *value) { (void)self; + if (PyErr_CheckSignals() < 0) { + return NULL; + } Py_ssize_t n = sequence_size(value); - if (n < 0) { + if (n < 0 || n > MAX_KERNEL_ITEMS) { Py_RETURN_NOTIMPLEMENTED; } Py_ssize_t total = 0; @@ -296,8 +302,11 @@ static PyObject *native_sum_lengths(PyObject *self, PyObject *value) { static PyObject *native_sum_ints(PyObject *self, PyObject *value) { (void)self; + if (PyErr_CheckSignals() < 0) { + return NULL; + } Py_ssize_t n = sequence_size(value); - if (n < 0) { + if (n < 0 || n > MAX_KERNEL_ITEMS) { Py_RETURN_NOTIMPLEMENTED; } long long total = 0; @@ -326,8 +335,16 @@ static PyObject *native_contains_any(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, "OO:contains_any", &text, &needles)) { return NULL; } + if (PyErr_CheckSignals() < 0) { + return NULL; + } Py_ssize_t n = sequence_size(needles); - if (!PyUnicode_CheckExact(text) || n < 0) { + if (!PyUnicode_CheckExact(text) || n < 0 || n > MAX_KERNEL_ITEMS) { + Py_RETURN_NOTIMPLEMENTED; + } + Py_ssize_t text_length = PyUnicode_GET_LENGTH(text); + if (text_length > MAX_SEARCH_CODEPOINTS || + (text_length > 0 && n > MAX_SEARCH_CODEPOINTS / text_length)) { Py_RETURN_NOTIMPLEMENTED; } for (Py_ssize_t i = 0; i < n; ++i) { diff --git a/restructuredpython/native_compiler.py b/restructuredpython/native_compiler.py index 8f6e2a7..5df366f 100644 --- a/restructuredpython/native_compiler.py +++ b/restructuredpython/native_compiler.py @@ -4,9 +4,9 @@ functions are eligible; unsupported patterns raise a useful compile error. """ import ast +import hashlib import unicodedata -from .unroll import marker_name def native_options(options): @@ -21,9 +21,7 @@ def native_options(options): def native_marker(source): - return marker_name(unicodedata.normalize("NFKC", source)).replace( - "_repy_unroll_marker_", "_repy_native_marker_" - ) if "_repy_native_marker_" not in source else _unique(source) + return _unique(source) def _unique(source): @@ -116,7 +114,10 @@ def lower_native(source, marker): marked.append((node, kernel)) if not marked: raise SyntaxError("No eligible native function") - alias = _unique(source) + 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=[])] @@ -132,3 +133,62 @@ def lower_native(source, marker): 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 diff --git a/restructuredpython/native_runtime.py b/restructuredpython/native_runtime.py index 0da6491..4bf9656 100644 --- a/restructuredpython/native_runtime.py +++ b/restructuredpython/native_runtime.py @@ -3,8 +3,12 @@ import functools import os import sys +from types import BuiltinFunctionType -_LEN = builtins.len +_candidate = builtins.len +_LEN = (_candidate if isinstance(_candidate, BuiltinFunctionType) + and _candidate.__name__ == 'len' and _candidate.__self__ is builtins else None) +_MONITORING = getattr(sys, 'monitoring', None) if os.environ.get("REPY_PURE_PYTHON") == "1": _native = None else: @@ -26,12 +30,13 @@ def decorate(function): @functools.wraps(function) def call(*args, **kwargs): - if (kwargs or len(args) != arity or sys.gettrace() is not None - or sys.getprofile() is not None): + if (kwargs or args.__len__() != arity or sys.gettrace() is not None + or sys.getprofile() is not None + or (_MONITORING is not None and any(_MONITORING.get_tool(i) is not None for i in range(6)))): return function(*args, **kwargs) # Do not bypass a global or custom builtins override of len. - if kernel == "sum_lengths" and function.__globals__.get( - "len", function.__builtins__.get("len")) is not _LEN: + if kernel == "sum_lengths" and (_LEN is None or function.__globals__.get( + "len", function.__builtins__.get("len")) is not _LEN): return function(*args) result = implementation(*args) if result is NotImplemented: diff --git a/restructuredpython/restructuredpython.py b/restructuredpython/restructuredpython.py index 818a595..848bebe 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 .native_compiler import validate_native_bindings from .unroll import DEFAULT_MAX_UNROLL, validate_max_unroll from .tempload import execute_code_temporarily @@ -112,7 +113,7 @@ def compile_header_file(header_filename, mode="classic", *, max_unroll=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)) + return validate_native_bindings(_expand_header(path, mode, (), set(), root, _configured_unroll(root, max_unroll))) def process_includes(code, input_file=".", mode="classic", *, include_root=None, @@ -141,7 +142,7 @@ def parse(source_code, *, filename=".", mode="classic", include_root=None, 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) + return validate_native_bindings(headers + parse_repython(body, mode, max_unroll=max_unroll)) def _output_path(source, output=None): diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index 3b3f3de..ac437e2 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -91,3 +91,32 @@ def test_unsupported_patterns_fail(self): repy.parse("\ndef f(x) {\n return x * 2\n}\n") with self.assertRaisesRegex(SyntaxError, "on its own"): repy.parse(SOURCE.replace("native=True", "native=True, cache=True")) + + + @unittest.skipUnless(NATIVE_AVAILABLE, "native extension required") + def test_kernels_handle_supported_inputs_directly(self): + from restructuredpython import _native + self.assertEqual(_native.sum_lengths(["😀", "你好"]), 3) + self.assertEqual(_native.sum_ints([2, -3, 4]), 3) + self.assertIs(_native.contains_any("hello", ["lo"]), True) + self.assertIs(_native.sum_ints([2**63-1, 1]), NotImplemented) + self.assertIs(_native.sum_lengths(["a"] * 32769), NotImplemented) + + def test_compatibility_unicode_marker(self): + from restructuredpython.native_compiler import native_marker + import unicodedata + source = "_repy_native_marker_0" + self.assertNotIn(native_marker(source), unicodedata.normalize("NFKC", source)) + + def test_combined_header_alias_collision_rejected(self): + import ast + import tempfile + from pathlib import Path + from restructuredpython.native_compiler import validate_native_bindings + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + code = repy.parse(SOURCE) + alias = next(node.names[0].asname for node in ast.walk(ast.parse(code)) + if isinstance(node, ast.ImportFrom) and node.module == "restructuredpython.native_runtime") + with self.assertRaisesRegex(SyntaxError, "collision"): + validate_native_bindings(f"{alias} = 3\n" + code) From 6ce337cf8293ce1a7c4880fa641000840ade0118 Mon Sep 17 00:00:00 2001 From: Rihaan Meher Date: Sun, 6 Dec 2026 17:53:05 -0500 Subject: [PATCH 3/3] Preserve ordinary Python names and check signals at native boundaries --- docs/native-runtime.md | 2 ++ restructuredpython/lib/compiler.c | 12 ++++++++++++ restructuredpython/restructuredpython.py | 11 +++++++++-- tests/test_native_runtime.py | 7 +++++++ 4 files changed, 30 insertions(+), 2 deletions(-) diff --git a/docs/native-runtime.md b/docs/native-runtime.md index 60b8dc8..8991799 100644 --- a/docs/native-runtime.md +++ b/docs/native-runtime.md @@ -36,3 +36,5 @@ 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. diff --git a/restructuredpython/lib/compiler.c b/restructuredpython/lib/compiler.c index 1f22d23..6cce3bd 100644 --- a/restructuredpython/lib/compiler.c +++ b/restructuredpython/lib/compiler.c @@ -297,6 +297,9 @@ static PyObject *native_sum_lengths(PyObject *self, PyObject *value) { } total += length; } + if (PyErr_CheckSignals() < 0) { + return NULL; + } return PyLong_FromSsize_t(total); } @@ -326,6 +329,9 @@ static PyObject *native_sum_ints(PyObject *self, PyObject *value) { } total += number; } + if (PyErr_CheckSignals() < 0) { + return NULL; + } return PyLong_FromLongLong(total); } @@ -357,9 +363,15 @@ static PyObject *native_contains_any(PyObject *self, PyObject *args) { return NULL; } if (contains) { + if (PyErr_CheckSignals() < 0) { + return NULL; + } Py_RETURN_TRUE; } } + if (PyErr_CheckSignals() < 0) { + return NULL; + } Py_RETURN_FALSE; } diff --git a/restructuredpython/restructuredpython.py b/restructuredpython/restructuredpython.py index 848bebe..a3f6da9 100644 --- a/restructuredpython/restructuredpython.py +++ b/restructuredpython/restructuredpython.py @@ -113,7 +113,10 @@ def compile_header_file(header_filename, mode="classic", *, max_unroll=None): """Transpile a header, resolving nested includes inside its source tree.""" path = Path(header_filename).resolve() root = _source_root(path.parent) - return validate_native_bindings(_expand_header(path, mode, (), set(), root, _configured_unroll(root, max_unroll))) + generated = _expand_header(path, mode, (), set(), root, _configured_unroll(root, max_unroll)) + if generated == _read_source(path) + "\n": + return generated + return validate_native_bindings(generated) def process_includes(code, input_file=".", mode="classic", *, include_root=None, @@ -142,7 +145,11 @@ def parse(source_code, *, filename=".", mode="classic", include_root=None, max_unroll = _configured_unroll(root, max_unroll) headers, body = process_includes(source_code, filename, mode, include_root=root, max_unroll=max_unroll) - return validate_native_bindings(headers + parse_repython(body, mode, max_unroll=max_unroll)) + generated = headers + parse_repython(body, mode, max_unroll=max_unroll) + # Plain Python must not be subject to compiler-internal name reservations. + if generated == source_code.replace("\r\n", "\n").replace("\r", "\n"): + return generated + return validate_native_bindings(generated) def _output_path(source, output=None): diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index ac437e2..84cb384 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -120,3 +120,10 @@ def test_combined_header_alias_collision_rejected(self): if isinstance(node, ast.ImportFrom) and node.module == "restructuredpython.native_runtime") with self.assertRaisesRegex(SyntaxError, "collision"): validate_native_bindings(f"{alias} = 3\n" + code) + + + def test_plain_python_internal_looking_names_are_not_reserved(self): + source = ("from restructuredpython.native_runtime import native_function as _repy_native_dispatch_example\n" + "def f(x):\n return x\n" + "alias = _repy_native_dispatch_example\n") + self.assertEqual(repy.parse(source), source)