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
45 changes: 39 additions & 6 deletions docs/design/typedpython-aot.md
Original file line number Diff line number Diff line change
Expand Up @@ -511,17 +511,50 @@ when it is used and keeps that dict when the dict's name is bound again, as CPyt
used as the views above are, and by a `for` loop (CPython's dict iterator, so a dict that changes size raises), its
truth (`if ks`, `not ks`, `bool(ks)`), and binding it to another view name of the same view and kinds. Anything else of
a view name (subscript, a dict method, `==`, the set operators, `list()` / `dict()` of it, putting it in a list or a
dict, passing or returning it) is refused naming the view. In a library an export may bind views of its dict
dict) is refused naming the view. A view is also passed to a function and returned from one (agent proposal, not
confirmed): the parameter or result is annotated `KeysView[K]`, `ValuesView[V]` or `ItemsView[K, V]`, imported by
`from collections.abc import KeysView, ValuesView, ItemsView` (the one `from` import of an AOT program, for annotations
only), and it holds the view's dict as a view name does; a view of a dict made in the callee keeps that dict alive. A
KeysView does not name the values of its dict, nor a ValuesView its keys, and the view reads only its half, so a
`KeysView[str]` parameter takes the keys of a `dict[str, int]` and of a `dict[str, float]` alike (`ir.view_match`).
The argument is a view of that half (`d.keys()`, a view name, a call of a function returning one); a dict or another
view is refused naming both views. A call returning a view is used as a view is (a `for` loop, len(), `in`, its truth,
the repr, binding it to a view name, passing it on). A method returns a view the same way (`def names(self) ->
KeysView[str]: return self.items.keys()`, called as `obj.names()` on a local of the class, the call method_call
makes directly); a view does not cross the library boundary (aot/export). In a library an export may bind views of its dict
parameter: a view name is only read, so it is no write (aot/library-dict-write). `set(xs)` of a list[str] or list[int] name and `set([a, b])`
follow too. A dict crosses the library boundary as `dict[int, int]`, `dict[int, float]` and `dict[int, bool]` (8.1 to
8.3, ABI version 3): the library only reads a dict parameter of an export (aot/library-dict-write otherwise, through
the callees it is passed to), so one handle may be shared by threads without the per-dict lock of tier T. Still to come
in S2b: a view passed to a function or returned from one (annotated `KeysView[K]`, `ValuesView[V]`, `ItemsView[K, V]`,
which needs `from collections.abc import ...` in an AOT program).
the callees it is passed to), so one handle may be shared by threads without the per-dict lock of tier T. What S2b
listed is in place (agent proposal, not confirmed).

**S2c.** List, dict and set comprehensions (a hidden local per comprehension variable, Python 3 scoping, the
accumulator built in place), `enumerate`, `zip` (shortest), `reversed`, `range` objects as iterables, in `for` loops
and comprehensions; `sum`, `any`, `all`, `min` / `max` of an iterable (`ValueError: min() iterable argument is
accumulator built in place). First step in (agent proposal, not confirmed): a comprehension that is the whole value
of an assignment to a name or of a `return` is rewritten into the loop it means before lowering
(typedpython/comprehensions.py). Each variable becomes a hidden local typed by Pyrefly at a probe (a
`[(x, y,) for x in xs for y in ys]` put before the statement in the copy Pyrefly types, the clauses without their
conditions, so a variable has its declared type). The accumulator is hidden and typed as its target, so the target is
bound once the comprehension is complete and `xs = [x + 1 for x in xs]` iterates the old list. The first iterable is
evaluated first, and a dict comprehension's key before its value (through a temporary of the key type). A
comprehension anywhere else (an operand, an argument) is refused as "bind it to a name first", and so are `:=` and a
comprehension, generator or lambda inside one. Second step in (agent proposal, not confirmed): `enumerate` and
`zip` as the iterable of a `for` loop or of a comprehension clause (typedpython/loops.py), each unpacked into names.
`for i, x in enumerate(it, start)` takes any iterable a loop takes and an int constant start; it is the loop over
`it` with a hidden counter bound to `i` before the body, so a `continue` counts and `i` keeps its last value after
the loop. `for a, b in zip(xs, ys)` takes names of lists or strs (or a str constant) that the loop does not rebind;
it reads each by index while the index is below every length, the lengths read at each step left to right, so a
list that grows in the loop is seen growing as CPython's list iterator sees it. zip's names are typed as the
elements of the operands, from the type Pyrefly gives each operand in the `for` header. A dict or a set operand
is refused (zip reads by index), and so are `strict=`, a single name as the target, and enumerate or zip anywhere
else. `for x in reversed(xs)` (also inside enumerate()) takes the same operands and reads from the end, the index
checked against the length at every step as CPython's reversed list iterator checks it: a list that shrinks in the
loop ends it early, one that grows is not seen growing. A range object held in a name (`r = range(a, b, STEP)`,
typedpython/ranges.py) is its start and stop in hidden int locals, its length computed once per binding, and its
constant step; a `for` loop over it (also in a comprehension or an enumerate()), len(), `in`, its truth and its
repr (print, str, repr, an f-string) are rewritten into what CPython computes. A step that is not an int
constant, a step of 0 (CPython's ValueError at run time, refused at compile time here), a name bound to a range
and to anything else, and any other use (passing, returning, indexing, list(), zip(), reversed()) are refused.
Then `zip` and `reversed` of other iterables, range objects passed and indexed, in `for` loops and comprehensions; `sum`, `any`, `all`, `min` / `max` of an iterable (`ValueError: min() iterable argument is
empty`); `sorted(xs, key=..., reverse=...)` and `list.sort(...)` with a key that is a compiled function or a
lambda written in place: CPython's own algorithm (timsort, `listsort` in Objects/listobject.c, ported as it is), so
the order of equal and of unordered elements (NaN) is CPython's, not merely some stable order. `bytes`: an immutable
Expand Down
102 changes: 99 additions & 3 deletions python-multiplatform-ksp/src/main/python/typedpython/aot/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@
LIST_ELEMENTS = ("int", "float") # `list[int]` and `list[float]` are the native lists
# builtin names a program must not rebind: the AOT mode compiles a call of each of these as the builtin
BUILTINS_USED = frozenset({"print", "float", "range", "len", "abs", "min", "max", "int", "bool", "list",
"str", "repr", "ord", "chr"}) # (str ... chr: tier S1)
"str", "repr", "ord", "chr", # (str ... chr: tier S1)
"enumerate", "zip", "reversed"}) # (tier S2c: the iterable of a loop)
RESERVED_PREFIX = "__tp_"
MAIN = frontend.AOT_ENTRY

Expand Down Expand Up @@ -99,6 +100,12 @@ def error(self, node_or_line, rule: str, name: str, message: str) -> None:

# --- the checks ----------------------------------------------------------------------------------

def _int_constant(e: ast.expr) -> bool:
if isinstance(e, ast.UnaryOp) and isinstance(e.op, (ast.USub, ast.UAdd)):
e = e.operand
return isinstance(e, ast.Constant) and type(e.value) is int


def _bound_names(fn: ast.AST) -> set[str]:
"""Every name a function binds anywhere inside it (parameters and assignment targets)."""
names: set[str] = set()
Expand Down Expand Up @@ -236,6 +243,8 @@ def annotation(self, ann: ast.expr | None, what: str, node: ast.AST, allow_none:
return # tier S2b: set[T]
elif _is_dict_list_annotation(ann):
return # tier S2b: list[dict[K, V]]
elif _is_view_annotation(ann):
return # tier S2b: KeysView[K], ValuesView[V], ItemsView[K, V]
elif allow_tuple and _is_tuple_list_annotation(ann):
return # tier S2a: one list per element (typedpython/tuples.py)
else:
Expand Down Expand Up @@ -288,6 +297,13 @@ def stmt(self, s: ast.stmt) -> None:
and ((self.var_classes.get(t0.value.id), t0.attr) in self.field_list_class
or (self.var_classes.get(t0.value.id), t0.attr) in self.field_dict_lists)):
pass # tier S2a: `self.items = []`, an empty list of the field's class (S2b: dicts)
elif (isinstance(t0, ast.Name) and isinstance(s.value, ast.Call) and isinstance(s.value.func, ast.Name)
and s.value.func.id == "range" and "range" not in self.shadow):
# tier S2c: a range object held in a name (typedpython/ranges.py checks its uses and its step)
if s.value.keywords or not 1 <= len(s.value.args) <= 3:
self.rep.error(s.value, "aot/call", "range", "range() takes one to three positional arguments")
for a in s.value.args:
self.expr(a)
else:
self.expr(s.value)
if len(s.targets) == 1 and isinstance(s.targets[0], ast.Name):
Expand Down Expand Up @@ -409,6 +425,10 @@ def target_ok(self, t: ast.expr) -> bool:

def for_stmt(self, s: ast.For) -> None:
it = s.iter
if isinstance(it, ast.Call) and isinstance(it.func, ast.Name) and it.func.id in ("enumerate", "zip", "reversed") \
and it.func.id not in self.shadow:
self.counted_loop(s, it) # tier S2c (typedpython/loops.py)
return
if isinstance(it, ast.Call) and isinstance(it.func, ast.Name) and it.func.id == "range":
if not (1 <= len(it.args) <= 3 and not it.keywords):
self.rep.error(s, "aot/statement", "for", "range() takes one to three positional arguments")
Expand All @@ -433,6 +453,55 @@ def for_stmt(self, s: ast.For) -> None:
for b in s.body + s.orelse:
self.stmt(b)

def counted_loop(self, s: ast.For, it: ast.Call) -> None:
"""Tier S2c: `for i, x in enumerate(it[, start])` (start an int constant) and `for a, b in zip(xs, ys, ...)` (names
of lists or strs, which the front end checks), each unpacked into names; `for x in reversed(xs)` (a name of a
list or a str)."""
n = it.func.id # type: ignore[attr-defined]
if it.keywords:
self.rep.error(it, "aot/call", n, f"{n}() takes no keyword argument in an AOT program")
if n == "enumerate":
if not 1 <= len(it.args) <= 2:
self.rep.error(it, "aot/call", n, "enumerate() takes an iterable and an optional start")
return
if len(it.args) == 2 and not _int_constant(it.args[1]):
self.rep.error(it.args[1], "aot/call", n, "the start of enumerate() is an int constant in an AOT program")
if not (isinstance(s.target, ast.Tuple) and len(s.target.elts) == 2
and isinstance(s.target.elts[0], ast.Name)):
self.rep.error(s, "aot/statement", "for", "enumerate() is unpacked into two names in an AOT program "
"(`for i, x in enumerate(xs)`)")
return
self.for_stmt(ast.copy_location(ast.For(target=s.target.elts[1], iter=it.args[0], body=s.body,
orelse=s.orelse, type_comment=None), s))
return
if n == "reversed" and len(it.args) != 1:
self.rep.error(it, "aot/call", n, "reversed() takes one list or str")
return
if n == "reversed" and not isinstance(s.target, ast.Name):
self.rep.error(s, "aot/statement", "for", "a loop over reversed() binds one name in an AOT program")
if not it.args:
self.rep.error(it, "aot/call", n, "zip() takes one or more lists or strs")
return
for a in it.args:
if not (isinstance(a, ast.Name) or (isinstance(a, ast.Constant) and isinstance(a.value, str))):
self.rep.error(a, "aot/call", n, f"{n}() takes names of lists or strs (or a str constant) in an AOT "
"program")
self.expr(a)
if n == "zip" and not (isinstance(s.target, ast.Tuple) and len(s.target.elts) == len(it.args)
and all(isinstance(e, ast.Name) for e in s.target.elts)):
self.rep.error(s, "aot/statement", "for", f"zip() of {len(it.args)} is unpacked into {len(it.args)} names "
"in an AOT program (`for a, b in zip(xs, ys)`)")
bound = {x.id for b in s.body for x in ast.walk(b) if isinstance(x, ast.Name) and isinstance(x.ctx, ast.Store)}
bound |= {e.id for e in ast.walk(s.target) if isinstance(e, ast.Name)}
for a in it.args:
if isinstance(a, ast.Name) and a.id in bound:
self.rep.error(a, "aot/statement", "for", f"the loop rebinds `{a.id}`, which {n}() reads: CPython's {n} "
f"keeps the object it was given, an AOT {n} reads the name")
if s.orelse:
self.rep.error(s.orelse[0], "aot/statement", "for-else", "`else` on a loop is outside the first AOT step")
for b in s.body:
self.stmt(b)

def expr_stmt(self, s: ast.Expr) -> None:
v = s.value
if isinstance(v, ast.Constant) and isinstance(v.value, str):
Expand Down Expand Up @@ -573,6 +642,13 @@ def expr(self, e: ast.expr) -> None:
self.subscript(e)
elif isinstance(e, ast.Lambda):
self.rep.error(e, "aot/expression", "lambda", "a lambda is outside the first AOT step")
elif isinstance(e, (ast.ListComp, ast.SetComp, ast.DictComp)):
for g in e.generators: # tier S2c: each clause is the loop it means (the front end checks the rest)
self.for_stmt(ast.copy_location(ast.For(target=g.target, iter=g.iter, body=[], orelse=[]), e))
for c in g.ifs:
self.expr(c)
for x in ((e.key, e.value) if isinstance(e, ast.DictComp) else (e.elt,)):
self.expr(x)
elif type(e).__name__ in _CONTAINER_NAMES:
kind = _CONTAINER_NAMES[type(e).__name__]
self.rep.error(e, "aot/container", kind, f"a {kind} is outside the first AOT step (containers arrive in a later step)")
Expand Down Expand Up @@ -870,6 +946,23 @@ def _is_set_annotation(ann: ast.expr) -> bool:
ast.Name(id="int")])))


VIEW_TYPES = ("KeysView", "ValuesView", "ItemsView")


def _is_view_annotation(ann: ast.expr) -> bool:
"""`KeysView[K]`, `ValuesView[V]` or `ItemsView[K, V]` of collections.abc, of the keys and values a dict holds (tier
S2b): a view passed to or returned from a function."""
if not (isinstance(ann, ast.Subscript) and isinstance(ann.value, ast.Name) and ann.value.id in VIEW_TYPES):
return False
if ann.value.id == "ItemsView":
pair = ann.slice
elif ann.value.id == "KeysView":
pair = ast.Tuple(elts=[ann.slice, ast.Name(id="int")])
else:
pair = ast.Tuple(elts=[ast.Name(id="int"), ann.slice])
return _is_dict_annotation(ast.Subscript(value=ast.Name(id="dict"), slice=pair))


def _is_dict_list_annotation(ann: ast.expr) -> bool:
"""`list[dict[K, V]]` (tier S2b)."""
return (isinstance(ann, ast.Subscript) and isinstance(ann.value, ast.Name) and ann.value.id in ("list", "List")
Expand Down Expand Up @@ -954,9 +1047,12 @@ def analyze(entry: Path, *, library: bool = False) -> Program:
else:
rep.error(s, "aot/import", ", ".join(a.name for a in s.names),
"only a single `import math`, `import sys` and `import time` are supported in the AOT mode")
elif (isinstance(s, ast.ImportFrom) and s.level == 0 and s.module == "collections.abc"
and all(a.name in VIEW_TYPES and a.asname is None for a in s.names)):
pass # tier S2b: the view types, for annotations
elif isinstance(s, ast.ImportFrom):
rep.error(s, "aot/import", s.module or ".", "only a single `import math`, `import sys` and `import time` are "
"supported in the AOT mode")
rep.error(s, "aot/import", s.module or ".", "only a single `import math`, `import sys` and `import time`, and "
"`from collections.abc import KeysView, ValuesView, ItemsView` are supported in the AOT mode")
elif isinstance(s, ast.FunctionDef):
program.functions.append(s)
if s.name in seen_names:
Expand Down
Loading
Loading