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
2 changes: 1 addition & 1 deletion .github/workflows/native-sanitizer.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ Paths are relative to the directory containing `repyconfig.toml`. Individual fil

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.

## Native runtime specialization (experimental)

Explicit `<OPTIMIZE native=True>` 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.
Expand Down
40 changes: 40 additions & 0 deletions docs/native-runtime.md
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.
124 changes: 124 additions & 0 deletions restructuredpython/lib/compiler.c
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <string.h>
#include <limits.h>

static int is_open(Py_UCS4 c) {
return c == '(' || c == '[' || c == '{';
Expand Down Expand Up @@ -254,7 +255,130 @@ 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. */
#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);
}
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;
if (PyErr_CheckSignals() < 0) {
return NULL;
}
Py_ssize_t n = sequence_size(value);
if (n < 0 || n > MAX_KERNEL_ITEMS) {
Py_RETURN_NOTIMPLEMENTED;
}
Py_ssize_t total = 0;
for (Py_ssize_t i = 0; i < n; ++i) {
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
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;
}
if (PyErr_CheckSignals() < 0) {
return NULL;
}
return PyLong_FromSsize_t(total);
}

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 || n > MAX_KERNEL_ITEMS) {
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;
}
if (PyErr_CheckSignals() < 0) {
return NULL;
}
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;
}
if (PyErr_CheckSignals() < 0) {
return NULL;
}
Py_ssize_t n = sequence_size(needles);
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) {
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) {
if (PyErr_CheckSignals() < 0) {
return NULL;
}
Py_RETURN_TRUE;
}
}
if (PyErr_CheckSignals() < 0) {
return NULL;
}
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."},
Expand Down
194 changes: 194 additions & 0 deletions restructuredpython/native_compiler.py
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
Loading
Loading