diff --git a/docs/design/typedpython-aot.md b/docs/design/typedpython-aot.md index 71df7f71..4c7460a8 100644 --- a/docs/design/typedpython-aot.md +++ b/docs/design/typedpython-aot.md @@ -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 diff --git a/python-multiplatform-ksp/src/main/python/typedpython/aot/program.py b/python-multiplatform-ksp/src/main/python/typedpython/aot/program.py index 9ca7bcea..79eb91d3 100644 --- a/python-multiplatform-ksp/src/main/python/typedpython/aot/program.py +++ b/python-multiplatform-ksp/src/main/python/typedpython/aot/program.py @@ -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 @@ -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() @@ -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: @@ -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): @@ -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") @@ -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): @@ -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)") @@ -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") @@ -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: diff --git a/python-multiplatform-ksp/src/main/python/typedpython/aotcheck.py b/python-multiplatform-ksp/src/main/python/typedpython/aotcheck.py index 942aa87f..6d1147e2 100644 --- a/python-multiplatform-ksp/src/main/python/typedpython/aotcheck.py +++ b/python-multiplatform-ksp/src/main/python/typedpython/aotcheck.py @@ -33,9 +33,11 @@ from dataclasses import dataclass, field from pathlib import Path -from typedpython import frontend, ir, resume, verify +from typedpython import comprehensions, frontend, ir, resume, verify PROVIDED_MODULES = frozenset({"math", "sys", "time"}) +_UNPLACED = ("a {} comprehension is compiled as the value of an assignment to a name or of a `return` (tier S2c); " + "elsewhere it is not compiled yet") # The IR nodes that are generic C-API object operations today: each needs a CPython object, so a # function containing one is not ready for a build without CPython. BinOp / UnaryOp / Compare whose @@ -293,6 +295,18 @@ def __init__(self, module: _Module, root: Path, program_classes: set[str]) -> No self.locals: set[str] = set() self.print_fstrings: set[int] = set() self.kinds: dict[str, str] = {} # annotated str / set names of the enclosing top-level def + # tier S2c: the comprehensions that are the whole value of an assignment to a name or of a return, which the + # front end compiles (typedpython/comprehensions.py); any other is pending + self.placed = {id(c) for s in ast.walk(module.tree) if (c := comprehensions._comp_of(s)) is not None} \ + if isinstance(module.tree, ast.Module) else set() + # ... and enumerate() / zip() / reversed() (reversed() also inside enumerate()) as the iterable of a `for` statement or of a clause of such a comprehension, the + # loops they mean (typedpython/loops.py); anywhere else they are pending + iters = [f.iter for f in ast.walk(module.tree) if isinstance(f, ast.For)] + [ + g.iter for c in ast.walk(module.tree) if id(c) in self.placed + for g in c.generators] if isinstance(module.tree, ast.Module) else [] # type: ignore[attr-defined] + iters += [i.args[0] for i in iters if isinstance(i, ast.Call) and isinstance(i.func, ast.Name) + and i.func.id == "enumerate" and i.args] + self.loop_iterables = {id(i) for i in iters} # -- helpers @@ -351,6 +365,9 @@ def visit_ImportFrom(self, node: ast.ImportFrom) -> None: "and the sibling modules it imports by name)") return name = node.module or "" + if (name == "collections.abc" and not self.depth + and all(a.name in ("KeysView", "ValuesView", "ItemsView") and a.asname is None for a in node.names)): + return # tier S2b: the view types, for annotations if any(a.name == "*" for a in node.names): self.error("aot/import", name, node, f"`from {name} import *` binds names the checker cannot see") self.import_of(name, node, None) @@ -372,7 +389,8 @@ def import_of(self, name: str, node: ast.stmt, _names: object) -> None: return elif not self.depth: self.error("aot/import", name, node, f"`{name}` is neither a module of this program nor one of the " - "provided standard modules (math, sys, time)") + "provided standard modules (math, sys, time; and KeysView, " + "ValuesView, ItemsView of collections.abc)") # -- definitions @@ -546,15 +564,18 @@ def visit_GeneratorExp(self, node: ast.GeneratorExp) -> None: self.comprehension(node, "generator expression") def visit_ListComp(self, node: ast.ListComp) -> None: - self.pending("S", "aot/container", "list comprehension", node, "a list comprehension is tier S (general containers), not compiled yet") + if id(node) not in self.placed: + self.pending("S", "aot/container", "list comprehension", node, _UNPLACED.format("list")) self.comprehension(node, "list comprehension") def visit_SetComp(self, node: ast.SetComp) -> None: - self.pending("S", "aot/container", "set comprehension", node, "a set comprehension is tier S (general containers), not compiled yet") + if id(node) not in self.placed: + self.pending("S", "aot/container", "set comprehension", node, _UNPLACED.format("set")) self.comprehension(node, "set comprehension") def visit_DictComp(self, node: ast.DictComp) -> None: - self.pending("S", "aot/container", "dict comprehension", node, "a dict comprehension is tier S (general containers), not compiled yet") + if id(node) not in self.placed: + self.pending("S", "aot/container", "dict comprehension", node, _UNPLACED.format("dict")) self.comprehension(node, "dict comprehension") def visit_Dict(self, node: ast.Dict) -> None: @@ -624,6 +645,8 @@ def builtin_call(self, n: str, node: ast.Call) -> None: self.error("aot/introspection", "type", node, "`type(name, bases, dict)` builds a class at run time") elif n in _KERNEL_BUILTINS: self.pending("K", "aot/builtin", n, node, f"`{n}()` is not compiled without CPython yet (tier K)") + elif n in ("enumerate", "zip", "reversed") and id(node) in self.loop_iterables: + return # tier S2c (the front end checks the operands and the target) elif n in _SET_BUILTINS_S: self.pending("S", "aot/builtin", n, node, f"`{n}()` is tier S, not compiled yet") elif n == "dict" and len(node.args) == 1 and not node.keywords: diff --git a/python-multiplatform-ksp/src/main/python/typedpython/comprehensions.py b/python-multiplatform-ksp/src/main/python/typedpython/comprehensions.py new file mode 100644 index 00000000..83dd33ef --- /dev/null +++ b/python-multiplatform-ksp/src/main/python/typedpython/comprehensions.py @@ -0,0 +1,301 @@ +"""AOT mode, tier S2c: list, set and dict comprehensions (design 4.3.2, S2c). Agent proposal, not owner-confirmed. + +A comprehension that is the whole value of an assignment to a name (`xs = [...]`, `xs: list[int] = [...]`) or of a +`return` is rewritten, on the AST the lowering reads, into the loop it means: + + ys = [e for x in xs if c] ys__c1: list[int] = [] + for x__c1 in xs: + if c': + ys__c1.append(e') + ys = ys__c1 + +* Python 3 scoping: every comprehension variable is a hidden local (`x__c1`), so a name of the same spelling in the + enclosing function is not touched; the accumulator is hidden too, so the target is bound only once the comprehension + is complete (and `xs = [x + 1 for x in xs]` iterates the old list). +* The order of evaluation is CPython's: the first iterable first, then per item the conditions left to right and the + element; of a dict comprehension the key before the value (PEP 572 / 3.8 order), through a temporary of the key type + when the key is not a name or a constant. +* Types: the accumulator has the type of what it is bound to (the annotation, the type Pyrefly gives the target name, + or the return annotation). A comprehension variable's type is read from Pyrefly at a probe: the copy of the source + that Pyrefly types gets, just before the statement, `[(x, y,) for x in xs for y in ys]` (the clauses without their + conditions, so a variable has its declared type, not a narrowed one), and each variable's type is the type of its + load in that probe. The hidden local gets that type as an injected `kinds` entry. + +Not rewritten, left for the lowering to refuse naming the reason: a comprehension anywhere else (an operand, an +argument), a generator expression (aot/generator), an async comprehension; and refused here: `:=` inside one (it binds +a name of the enclosing function in CPython), a nested comprehension inside one. +""" +from __future__ import annotations + +import ast +from dataclasses import dataclass, field + +from typedpython import rebinding + +COMPS = (ast.ListComp, ast.SetComp, ast.DictComp) +Kinds = dict[str, dict[str, list[tuple[int, str]]]] + + +@dataclass(frozen=True) +class Site: + """A statement whose whole value is a comprehension, in the function `qname`.""" + qname: str + stmt: ast.stmt + comp: ast.ListComp | ast.SetComp | ast.DictComp + + +@dataclass +class Rewrite: + kinds: Kinds + problems: dict[str, str] = field(default_factory=dict) # IR function name -> skip reason ("line N: ...") + + +class _Problem(Exception): + def __init__(self, line: int, message: str) -> None: + super().__init__(message) + self.line = line + + +def _own_statements(fn: ast.FunctionDef) -> list[ast.stmt]: + return [s for s in rebinding._own_statements(fn) if s is not fn] + + +def _comp_of(s: ast.stmt) -> ast.ListComp | ast.SetComp | ast.DictComp | None: + if isinstance(s, ast.Assign) and len(s.targets) == 1 and isinstance(s.targets[0], ast.Name): + value = s.value + elif isinstance(s, ast.AnnAssign) and isinstance(s.target, ast.Name) and s.value is not None: + value = s.value + elif isinstance(s, ast.Return) and s.value is not None: + value = s.value + else: + return None + if isinstance(value, COMPS) and not any(g.is_async for g in value.generators): + return value + return None + + +def sites(functions: list[tuple[str, ast.FunctionDef]]) -> list[Site]: + """Every statement of the functions whose value is a comprehension this pass rewrites.""" + return [Site(q, s, c) for q, fn in functions for s in _own_statements(fn) if (c := _comp_of(s)) is not None] + + +def _variables(comp: ast.ListComp | ast.SetComp | ast.DictComp) -> list[str]: + """The comprehension's variables, in the order their clauses bind them (each once).""" + names: list[str] = [] + for g in comp.generators: + for n in ast.walk(g.target): + if isinstance(n, ast.Name) and n.id not in names: + names.append(n.id) + return names + + +def probe(probed: str, probes: list[rebinding.Probe], wanted: list[rebinding.Assignment], + found: list[Site]) -> tuple[str, list[rebinding.Probe], dict[tuple[int, str], tuple[int, int]]]: + """`probed` (rebinding.probe's copy) with a probe before each site's statement: (the new copy, the assignment + probes moved to where they now are, (id of the comprehension, variable) -> (line, column) of its load).""" + lines = probed.splitlines(keepends=True) + placed: dict[tuple[int, str], tuple[int, int]] = {} + inserts: list[tuple[int, int, Site]] = [] + for site in found: + s = site.stmt + # the statement's column in the copy: the assignment probes inserted before it on its line come first + shift = sum(len(("; " + a.name).encode()) for a in wanted + if a.end_line == s.lineno and a.end_byte <= s.col_offset) + inserts.append((s.lineno, s.col_offset + shift, site)) + for line_no, at, site in sorted(inserts, key=lambda t: (t[0], t[1]), reverse=True): + names = _variables(site.comp) + if not names: + continue + head = "[(" + "".join(f"{n}, " for n in names) + ") for " + offsets: dict[str, int] = {} + text = head + # the loads: the tuple at the head; offsets in UTF-8 bytes from the start of the insertion + pos = len("[(".encode()) + for n in names: + offsets[n] = pos + pos += len(f"{n}, ".encode()) + text += " for ".join(f"{ast.unparse(g.target)} in {ast.unparse(g.iter)}" for g in site.comp.generators) + text += "]; " + size = len(text.encode()) + encoded = lines[line_no - 1].encode() + lines[line_no - 1] = encoded[:at].decode() + text + encoded[at:].decode() + probes = [rebinding.Probe(p.name, p.line, p.column + size, p.assignment) + if p.line == line_no and p.column > at else p for p in probes] + placed = {k: ((ln, col + size) if ln == line_no and col > at else (ln, col)) for k, (ln, col) in placed.items()} + for n in names: + placed[(id(site.comp), n)] = (line_no, at + offsets[n] + 1) + return "".join(lines), probes, placed + + +def _names(fn: ast.FunctionDef) -> set[str]: + return {n.id for n in ast.walk(fn) if isinstance(n, ast.Name)} | {a.arg for a in ast.walk(fn) + if isinstance(a, ast.arg)} + + +class _Rename(ast.NodeTransformer): + def __init__(self, mapping: dict[str, str]) -> None: + self.mapping = mapping + + def visit_Name(self, node: ast.Name) -> ast.AST: + if node.id in self.mapping: + return ast.copy_location(ast.Name(id=self.mapping[node.id], ctx=node.ctx), node) + return node + + +def _renamed(node: ast.AST, mapping: dict[str, str]) -> ast.AST: + import copy + return _Rename(mapping).visit(copy.deepcopy(node)) + + +def _located(node: ast.AST, at: ast.stmt) -> ast.AST: + """`node` with the location of `at` wherever it has none (the nodes this pass makes).""" + for n in ast.walk(node): + if "lineno" in n._attributes and not hasattr(n, "lineno"): + n.lineno, n.col_offset = at.lineno, at.col_offset + n.end_lineno, n.end_col_offset = at.end_lineno, at.end_col_offset + return node + + +def _annotation_of(spelled: str, line: int) -> ast.expr: + try: + return ast.parse(spelled, mode="eval").body + except SyntaxError: + raise _Problem(line, f"the comprehension is bound to a `{spelled}`, a type the AOT mode does not spell") + + +def rewrite(found: list[Site], functions: list[tuple[str, ast.FunctionDef]], kinds: Kinds, + types: dict[tuple[int, str], str]) -> Rewrite: + """Rewrite every site in place (see the module docstring). `types`: (id of the comprehension, variable) -> the + type Pyrefly gives the variable at its probe.""" + out = Rewrite({q: {n: list(v) for n, v in d.items()} for q, d in kinds.items()}) + by_function = dict(functions) + taken = {q: _names(fn) for q, fn in functions} + counter: dict[str, int] = {} + for site in found: + if site.qname in out.problems: + continue + try: + new = _rewrite_site(site, by_function[site.qname], out.kinds.setdefault(site.qname, {}), types, + taken[site.qname], counter) + except _Problem as e: + out.problems[site.qname] = f"line {e.line}: {e}" + continue + _replace(by_function[site.qname], site.stmt, new) + return out + + +def _fresh(base: str, taken: set[str], counter: dict[str, int], q: str) -> str: + while True: + counter[q] = counter.get(q, 0) + 1 + name = f"{base}__c{counter[q]}" + if name not in taken: + taken.add(name) + return name + + +def _rewrite_site(site: Site, fn: ast.FunctionDef, kinds: dict[str, list[tuple[int, str]]], + types: dict[tuple[int, str], str], taken: set[str], counter: dict[str, int]) -> list[ast.stmt]: + s, comp, line = site.stmt, site.comp, site.stmt.lineno + for n in ast.walk(comp): + if isinstance(n, ast.NamedExpr): + raise _Problem(n.lineno, f"`{ast.unparse(n)}`: `:=` inside a comprehension binds a name of the " + "enclosing function in CPython, which an AOT comprehension does not do yet") + if n is not comp and isinstance(n, (*COMPS, ast.GeneratorExp, ast.Lambda)): + raise _Problem(n.lineno, f"`{ast.unparse(n)}` inside the comprehension `{ast.unparse(comp)}`: a " + "comprehension holds no comprehension, generator or lambda in an AOT program yet") + # the accumulator's type + if isinstance(s, ast.AnnAssign): + annotation = s.annotation + base = s.target.id # type: ignore[union-attr] + elif isinstance(s, ast.Assign): + base = s.targets[0].id # type: ignore[attr-defined] + spelled = [k for ln, k in kinds.get(base, []) if ln == line] + if not spelled: + raise _Problem(line, f"no type is known for `{base}`, bound to a comprehension") + annotation = _annotation_of(spelled[0], line) + else: + if fn.returns is None: + raise _Problem(line, "the function returning a comprehension has no return annotation") + annotation, base = fn.returns, "result" + import copy + annotation = copy.deepcopy(annotation) + acc = _fresh(base, taken, counter, site.qname) + + # the variables: hidden locals typed at their probe + mapping: dict[str, str] = {} + clauses: list[tuple[ast.expr, ast.expr, list[ast.expr]]] = [] + for g in comp.generators: + it = _renamed(g.iter, mapping) # an iterable sees the variables of the clauses before it + for n in ast.walk(g.target): + if not isinstance(n, (ast.Name, ast.Tuple, ast.Store)): + raise _Problem(line, f"the comprehension target `{ast.unparse(g.target)}` is not a name or a tuple of " + "names") + if isinstance(n, ast.Name) and n.id not in mapping: + spelled = types.get((id(comp), n.id)) + if spelled is None: + raise _Problem(line, f"no type is known for the comprehension variable `{n.id}`") + hidden = _fresh(n.id, taken, counter, site.qname) + kinds[hidden] = [(line, spelled)] + mapping[n.id] = hidden + target = _renamed(g.target, mapping) + clauses.append((target, it, [_renamed(c, mapping) for c in g.ifs])) # type: ignore[misc] + + # the innermost statement: add the element + accn = lambda ctx: ast.Name(id=acc, ctx=ctx) # noqa: E731 + if isinstance(comp, ast.DictComp): + key, value = _renamed(comp.key, mapping), _renamed(comp.value, mapping) + inner: list[ast.stmt] = [] + if not isinstance(key, (ast.Name, ast.Constant)): + if not (isinstance(annotation, ast.Subscript) and isinstance(annotation.slice, ast.Tuple) + and len(annotation.slice.elts) == 2): + raise _Problem(line, f"the dict comprehension is bound to `{ast.unparse(annotation)}`, not a " + "dict[K, V]") + ktmp = _fresh("key", taken, counter, site.qname) + inner.append(ast.AnnAssign(target=ast.Name(id=ktmp, ctx=ast.Store()), + annotation=copy.deepcopy(annotation.slice.elts[0]), value=key, simple=1)) + key = ast.Name(id=ktmp, ctx=ast.Load()) + inner.append(ast.Assign(targets=[ast.Subscript(value=accn(ast.Load()), slice=key, ctx=ast.Store())], + value=value)) + empty: ast.expr = ast.Dict(keys=[], values=[]) + else: + method = "append" if isinstance(comp, ast.ListComp) else "add" + inner = [ast.Expr(value=ast.Call(func=ast.Attribute(value=accn(ast.Load()), attr=method, ctx=ast.Load()), + args=[_renamed(comp.elt, mapping)], keywords=[]))] + empty = ast.List(elts=[], ctx=ast.Load()) if isinstance(comp, ast.ListComp) else \ + ast.Call(func=ast.Name(id="set", ctx=ast.Load()), args=[], keywords=[]) + + # the loops, innermost first + body = inner + for target, it, ifs in reversed(clauses): + for cond in reversed(ifs): + body = [ast.If(test=cond, body=body, orelse=[])] + body = [ast.For(target=target, iter=it, body=body, orelse=[])] + + init = ast.AnnAssign(target=accn(ast.Store()), annotation=annotation, value=empty, simple=1) + if isinstance(s, ast.Return): + final: ast.stmt = ast.Return(value=accn(ast.Load())) + elif isinstance(s, ast.AnnAssign): + final = ast.AnnAssign(target=s.target, annotation=s.annotation, value=accn(ast.Load()), simple=s.simple) + else: + final = ast.Assign(targets=s.targets, value=accn(ast.Load())) + return [_located(x, s) for x in (init, *body, final)] # type: ignore[misc] + + +def _replace(fn: ast.FunctionDef, old: ast.stmt, new: list[ast.stmt]) -> None: + """Replace the statement `old` of `fn` (in any block of its own) by `new`.""" + stack: list[ast.AST] = [fn] + while stack: + node = stack.pop() + for name in ("body", "orelse", "finalbody"): + block = getattr(node, name, None) + if isinstance(block, list) and old in block: + i = block.index(old) + block[i:i + 1] = new + return + if isinstance(block, list): + stack += [b for b in block if not isinstance(b, (ast.FunctionDef, ast.ClassDef, ast.AsyncFunctionDef))] + for h in getattr(node, "handlers", []): + stack.append(h) + for c in getattr(node, "cases", []): + stack.append(c) + raise AssertionError("the statement is not in its function") diff --git a/python-multiplatform-ksp/src/main/python/typedpython/frontend.py b/python-multiplatform-ksp/src/main/python/typedpython/frontend.py index 1c5094a8..3ec3c922 100644 --- a/python-multiplatform-ksp/src/main/python/typedpython/frontend.py +++ b/python-multiplatform-ksp/src/main/python/typedpython/frontend.py @@ -115,7 +115,7 @@ from dataclasses import dataclass, field from pathlib import Path -from typedpython import gate, ir, pyrefly, rebinding, resume, taint, tuples +from typedpython import comprehensions, gate, ir, loops, pyrefly, ranges, rebinding, resume, taint, tuples from typedpython.ir import Type I64_MIN, I64_MAX = -2**63, 2**63 - 1 @@ -219,14 +219,43 @@ def _dict_or_set_kinds(kind: str) -> "ir.DictKinds | None": _VIEW_KIND = re.compile(r"(?:_collections_abc\.)?dict_(keys|values|items)\[(.+)\]") +_ABC_VIEW_KIND = re.compile(r"(?:(?:_collections_abc|collections\.abc|typing)\.)?(Keys|Values|Items)View\[(.+)\]") def _view_kinds(kind: str) -> "tuple[str, ir.DictKinds] | None": """AOT mode, tier S2b: (the view, the kinds of its dict) of Pyrefly's type of a view bound to a name - (`_collections_abc.dict_keys[str, int]`), else None.""" - m = _VIEW_KIND.fullmatch(_aot_kind(kind).strip()) - kinds = _dict_kinds(f"dict[{m.group(2)}]") if m is not None else None - return (m.group(1), kinds) if kinds is not None else None + (`_collections_abc.dict_keys[str, int]`) or of a `KeysView[K]`, `ValuesView[V]` or `ItemsView[K, V]` annotation, + else None. A KeysView does not say the values of its dict, nor a ValuesView the keys: that half is int, and only + the half the view reads is compared (`_view_match`).""" + k = _aot_kind(kind).strip() + m = _VIEW_KIND.fullmatch(k) + if m is not None: + kinds = _dict_kinds(f"dict[{m.group(2)}]") + return (m.group(1), kinds) if kinds is not None else None + m = _ABC_VIEW_KIND.fullmatch(k) + if m is None: + return None + view = m.group(1).lower() + pair = {"keys": f"{m.group(2)}, int", "values": f"int, {m.group(2)}", "items": m.group(2)}[view] + kinds = _dict_kinds(f"dict[{pair}]") + return (view, kinds) if kinds is not None and not ir.is_set(kinds) else None + + +def _view_type(view: str, kinds: "ir.DictKinds") -> str: + """The view `view` of a dict of `kinds` by the half it reads: `KeysView[str]`, `ValuesView[int]`, + `ItemsView[str, int]` (collections.abc).""" + return (f"KeysView[{_kname(kinds[0])}]" if view == "keys" else f"ValuesView[{_vname(kinds[1])}]" if view == "values" + else f"ItemsView[{_kname(kinds[0])}, {_vname(kinds[1])}]") + + +def _view_misuse(what: str, view: str, kinds: "ir.DictKinds") -> str: + return (f"{what} is a view, a {_view_type(view, kinds)}: an AOT program uses a view by a `for` loop, " + "len(), `in`, its truth, print / str / repr / an f-string, binds it to another view name, passes it to a " + "view parameter or returns it as a view; what a view has beyond that (set operators, comparison, list() or " + "dict() of it) is not yet") + + +_view_match = ir.view_match def _dict_list_kinds(kind: str) -> "ir.DictKinds | None": @@ -391,6 +420,7 @@ class _Signature: return_cls: str | None = None return_optional: bool = False return_kinds: "ir.DictKinds | None" = None # AOT mode, tier S2b: `-> dict[K, V]` + return_view: str | None = None # ... `-> KeysView[K]` (ValuesView, ItemsView): "keys", ... @property def qname(self) -> str: @@ -427,9 +457,20 @@ def lower(path: Path, *, aot: bool = False) -> ir.Module: every = [(s.name, s) for s in tree.body if isinstance(s, ast.FunctionDef)] every += [(f"{c.name}.{m.name}", m) for c in tree.body if isinstance(c, ast.ClassDef) for m in c.body if isinstance(m, ast.FunctionDef)] - early_kinds = _inferred_kinds(path, source, tree, every) - split = tuples.split(tree, early_kinds) - early_kinds, tuple_problems = split.kinds, split.problems + # tier S2c: a comprehension bound to a name or returned is the loop it means (typedpython/comprehensions.py), + # its variables typed at a probe; rewritten before the tuples are split (a loop over a list of tuples) + comp_sites = comprehensions.sites(every) + comp_types: dict[tuple[int, str], str] = {} + loop_types: dict[int, str] = {} + early_kinds = _inferred_kinds(path, source, tree, every, comp_sites, comp_types, loops.sites(every), loop_types) + rewritten = comprehensions.rewrite(comp_sites, every, early_kinds, comp_types) + # ... and a loop over enumerate() / zip() is the loop it means (typedpython/loops.py), comprehensions' included + rewritten.kinds, loop_problems = loops.rewrite(every, rewritten.kinds, loop_types) + # ... and a range object held in a name is its bounds (typedpython/ranges.py), after the loops that read it + rewritten.kinds, range_problems = ranges.rewrite(every, rewritten.kinds) + split = tuples.split(tree, rewritten.kinds) + early_kinds, tuple_problems = split.kinds, {**split.problems, **range_problems, **loop_problems, + **rewritten.problems} class_decls, class_skips = _classes(tree, source, info, aot) info.classes = class_decls skipped.update(class_skips) @@ -478,7 +519,8 @@ def lower(path: Path, *, aot: bool = False) -> ir.Module: env: dict[str, ir.Function] = { name: ir.Function(name=name, params=s.params, returns=s.returns, locals={}, body=(), pure=True, may_deopt=False, source_line=s.node.lineno, owner=s.owner, - return_cls=s.return_cls, return_optional=s.return_optional, return_kinds=s.return_kinds) + return_cls=s.return_cls, return_optional=s.return_optional, return_kinds=s.return_kinds, + return_view=s.return_view) for name, s in signatures.items() } results: dict[str, ir.Function | str] = {} @@ -1218,6 +1260,8 @@ def _signature(fn: ast.FunctionDef, classes: dict[str, ir.ClassDecl] | None = No params.append(ir.Param(a.arg, Type.DICT, kinds=dk)) # tier S2b: dict[K, V], set[T] elif info is not None and info.aot and (dk := _dict_list_kinds(kind)) is not None: params.append(ir.Param(a.arg, Type.DICT_LIST, kinds=dk)) # tier S2b: list[dict[K, V]] + elif info is not None and info.aot and (vk := _view_kinds(kind)) is not None: + params.append(ir.Param(a.arg, Type.DICT, kinds=vk[1], view=vk[0])) # tier S2b: a view holds its dict else: params.append(ir.Param(a.arg, kinds_map.get(_aot_kind(kind) if kinds_map is AOT_KIND else kind, Type.OBJ))) if fn.returns is None: @@ -1236,12 +1280,16 @@ def _signature(fn: ast.FunctionDef, classes: dict[str, ir.ClassDecl] | None = No elements, ellipsis = _tuple_annotation(fn.returns, aot=info is not None and info.aot) ret_cls, ret_opt = None, False ret_kinds = None + ret_view = None if info is not None and info.aot and not (isinstance(fn.returns, ast.Constant) and fn.returns.value is None): ret_kinds = _dict_or_set_kinds(_annotation_kind(fn.returns)) if ret_kinds is not None: returns = Type.DICT # tier S2b: dict[K, V] elif (ret_kinds := _dict_list_kinds(_annotation_kind(fn.returns))) is not None: returns = Type.DICT_LIST # tier S2b: list[dict[K, V]] + elif (vk := _view_kinds(_annotation_kind(fn.returns))) is not None: + returns = Type.DICT # tier S2b: a view, its dict returned + ret_view, ret_kinds = vk if returns == Type.OBJ and classes: rc = _class_of(_annotation_kind(fn.returns), classes) if rc is not None: @@ -1249,7 +1297,7 @@ def _signature(fn: ast.FunctionDef, classes: dict[str, ir.ClassDecl] | None = No elif info is not None and info.aot and (lc := _obj_list_class(_annotation_kind(fn.returns), classes)): returns, ret_cls = Type.OBJ_LIST, lc # tier S2a: list[C] return _Signature(fn, tuple(params), returns, elements, ellipsis, _src(fn.returns), owner, - return_cls=ret_cls, return_optional=ret_opt, return_kinds=ret_kinds) + return_cls=ret_cls, return_optional=ret_opt, return_kinds=ret_kinds, return_view=ret_view) def _tuple_annotation(annotation: ast.expr, aot: bool = False) -> tuple[tuple[Type, ...] | None, bool]: @@ -1278,15 +1326,23 @@ def _annotation_kind(annotation: ast.expr) -> str: def _inferred_kinds( path: Path, source: str, tree: ast.Module, functions: list[tuple[str, ast.FunctionDef]], + comp_sites: "list[comprehensions.Site] | None" = None, comp_types: dict[tuple[int, str], str] | None = None, + loop_sites: list[ast.Name] | None = None, loop_types: dict[int, str] | None = None, ) -> dict[str, dict[str, list[tuple[int, str]]]]: - """IR function name -> local -> [(line, base type)] for every unannotated assignment (Pyrefly).""" + """IR function name -> local -> [(line, base type)] for every unannotated assignment (Pyrefly). AOT mode, tier + S2c: with `comp_sites`, also the type of each comprehension variable at its probe, into `comp_types`; with + `loop_sites`, the type of each zip() operand at its load in its `for` header, into `loop_types` (the probes insert + nothing before a `for` header on its line, so its columns are those of the source).""" scopes = rebinding._scopes(tree) keys = {id(fn): q for q, fn in functions} wanted_scopes = {scopes.index(fn) for _, fn in functions} wanted = [a for a in rebinding.assignments(tree) if a.scope in wanted_scopes] - if not wanted: + if not wanted and not comp_sites and not loop_sites: return {} probed, probes = rebinding.probe(source, wanted) + placed: dict[tuple[int, str], tuple[int, int]] = {} + if comp_sites: + probed, probes, placed = comprehensions.probe(probed, probes, wanted, comp_sites) with tempfile.TemporaryDirectory(prefix="typedpython-frontend-") as work: copies = gate._mirror(Path(work), {str(path): probed}) [copy] = copies @@ -1294,6 +1350,14 @@ def _inferred_kinds( report = pyrefly.run([Path(copy)], [Path(work) / "0", Path(copy).parent, *roots]) types = report.expression_types.get(copy, {}) + if loop_types is not None: + for a in loop_sites or []: + if (a.lineno, a.col_offset + 1) in types: + loop_types[id(a)] = rebinding._base(types[(a.lineno, a.col_offset + 1)]) + if comp_types is not None: + for key, at in placed.items(): + if at in types: + comp_types[key] = rebinding._base(types[at]) found: dict[str, dict[str, list[tuple[int, str]]]] = {} for p in probes: a = p.assignment @@ -1551,8 +1615,10 @@ def __init__(self, sig: _Signature, env: dict[str, ir.Function], info: _ModuleIn self.list_cls: dict[str, str] = {} # AOT mode, tier S2a: the element class of an OBJ_LIST local self.loop_cls: dict[str, str] = {} # ... and of the variable of a loop over one self.dict_locals: dict[str, ir.DictKinds] = {} # AOT mode, tier S2b: the kinds of every DICT local - self.view_locals: dict[str, str] = {} # ... and the view ("keys", ...) of a DICT local that is a view + self.view_locals: dict[str, str] = {p.name: p.view for p in sig.params # ... and the view ("keys", ...) + if isinstance(p, ir.Param) and p.view} # of a DICT local that is one self.dict_want: ir.DictKinds | None = None # ... and what a dict display being lowered must hold + self.view_call_ok = False # ... a call of a function returning a view is lowered as the view's dict self.temps: dict[str, Type] = {} self.pre: list[ir.Stmt] = [] self.hoist_ok = True @@ -1636,7 +1702,7 @@ def run(self) -> ir.Function: dict_kinds={**{n: k for n, k in self.dict_locals.items() if n in locals_}, **{p.name: p.kinds for p in params if isinstance(p, ir.Param) and p.type in (Type.DICT, Type.DICT_LIST)}}, - return_kinds=self.sig.return_kinds) + return_kinds=self.sig.return_kinds, return_view=self.sig.return_view) if self.info.aot: return fn # nothing is redone in an interpreter, so there is no continuation to write # SPEC N-8 (#152): a snapshot holder gets a Python continuation per loop (OSR-style exit). @@ -2376,6 +2442,9 @@ def aot_subscript(self, node: ast.Subscript) -> ir.Expr: "str arrives with tier S1b)") return ir.ArgvStr(Type.STR, self.str_int(self.value(node.slice), node.slice, "the index")) value = self.sub(node.value) + if value.type is Type.DICT and getattr(node, "tp_indexed", False): # tier S2c: of zip(), reversed() + raise Skip(line, f"`{_src(node.value)}` is a dict or a set: zip() and reversed() read their operands by " + "index in an AOT program, so an operand is a list or a str") if value.type is Type.DICT: # tier S2b: `d[k]` if isinstance(node.slice, ast.Slice): raise Skip(line, f"`{_src(node)}` slices a dict") @@ -2545,27 +2614,61 @@ def view_dict(self, dnode: ast.expr) -> ir.Expr: if self.view_name(dnode) is not None: assert isinstance(dnode, ast.Name) return ir.Local(Type.DICT, dnode.id) + if self.view_call(dnode) is not None: + self.view_call_ok = True + try: + return self.value(dnode) + finally: + self.view_call_ok = False return self.value(dnode) + def view_call(self, node: ast.expr) -> ir.Function | None: + """The program function or method `node` calls when it returns a view (`-> KeysView[K]`, ...), else None. A + method is the one method_call calls directly: `obj.m(...)` of a local `obj` of a compiled class.""" + if not (self.info.aot and isinstance(node, ast.Call)): + return None + f: ir.Function | None = None + if isinstance(node.func, ast.Name) and not self.is_local(node.func.id): + f = self.env.get(node.func.id) + elif isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) \ + and self.is_local(node.func.value.id): + cls, _ = self.cls_of_name(node.func.value.id) + f = self.env.get(f"{cls}.{node.func.attr}") if cls is not None else None + if f is not None and f.owner != cls: + f = None + return f if f is not None and f.return_view is not None else None + + def view_arg(self, a: ast.expr, view: str, kinds: ir.DictKinds, what: str) -> ir.Expr: + """The view `a` passed to (or returned as) `what`, a view `view` of a dict of `kinds`: the view's dict.""" + found = self.view_of(a) + if found is None or found[0] != view or not _view_match(view, self.view_kinds(found[1]), kinds): + got = "not a view" if found is None else f"a {_view_type(found[0], self.view_kinds(found[1]))}" + raise Skip(getattr(a, "lineno", 0), f"`{_src(a)}` is {got}, but {what} is a view, a " + f"{_view_type(view, kinds)}") + return self.view_dict(found[1]) + def view_value(self, name: str, value_node: ast.expr, line: int) -> ir.Expr: """The value bound to the view local `name`: `d.keys()` (`values()`, `items()`) of a dict of its kinds, or another view local of the same view and kinds (the two then hold the same dict, as CPython's names hold one view object).""" - view, kinds = self.view_locals[name], self.dict_locals[name] + view, kinds = self.view_locals[name], self.name_kinds(name) found = self.view_of(value_node) if found is None: - raise Skip(line, f"`{name}` is a view ({_dict_name(kinds)}.{view}()) but is bound to `{_src(value_node)}`") - if found[0] != view or self.view_kinds(found[1]) != kinds: - got = f"{_dict_name(self.view_kinds(found[1]))}.{found[0]}()" - raise Skip(line, f"`{name}` is a view {_dict_name(kinds)}.{view}() but is bound to `{_src(value_node)}`, " - f"a view {got}") + raise Skip(line, f"`{name}` is a view, a {_view_type(view, kinds)}, but is bound to `{_src(value_node)}`") + if found[0] != view or not _view_match(view, self.view_kinds(found[1]), kinds): + got = _view_type(found[0], self.view_kinds(found[1])) + raise Skip(line, f"`{name}` is a view, a {_view_type(view, kinds)}, but is bound to `{_src(value_node)}`, " + f"a {got}") return ir.DictView(Type.DICT, view, self.view_dict(found[1])) def view_kinds(self, dnode: ast.expr) -> ir.DictKinds: """The kinds of the dict of a view (`dnode` as view_of gives it).""" if self.view_name(dnode) is not None: assert isinstance(dnode, ast.Name) - return self.dict_locals[dnode.id] + return self.name_kinds(dnode.id) + if (f := self.view_call(dnode)) is not None: + assert f.return_kinds is not None + return f.return_kinds # type: ignore[return-value] kinds = self.node_dict_kinds(dnode) assert kinds is not None return kinds @@ -2582,6 +2685,8 @@ def field_decl_of(self, node: ast.Attribute) -> ir.FieldDecl | None: def dict_arg(self, p: object, a: ast.expr, callee: str) -> ir.Expr: """The argument `a` for the parameter `p` of `callee` (a method or `__init__`): a dict takes the parameter's kinds (dicts are invariant), anything else is its value.""" + if isinstance(p, ir.Param) and p.view is not None and p.kinds is not None: + return self.view_arg(a, p.view, p.kinds, f"parameter `{p.name}` of `{callee}`") if isinstance(p, ir.Param) and p.type is Type.DICT and p.kinds is not None: return self.dict_coerce(self.dict_operand(a, p.kinds), p.kinds, a, f"parameter `{p.name}` of `{callee}`") if isinstance(p, ir.Param) and p.type is Type.DICT_LIST and p.kinds is not None: @@ -2603,7 +2708,7 @@ def is_dict_node(self, node: ast.expr) -> bool: if node.func.id in ("dict", "set") and self.builtin(node.func.id): return True f = self.env.get(node.func.id) - return f is not None and f.returns is Type.DICT + return f is not None and f.returns is Type.DICT and f.return_view is None return self.node_dict_kinds(node) is not None def node_dict_kinds(self, node: ast.expr) -> ir.DictKinds | None: @@ -2628,7 +2733,7 @@ def node_dict_kinds(self, node: ast.expr) -> ir.DictKinds | None: return self.dict_value_kinds(outer) if node.func.attr in ("get", "setdefault", "pop") else None if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and not self.is_local(node.func.id): f = self.env.get(node.func.id) - return f.return_kinds if f is not None and f.returns is Type.DICT else None + return f.return_kinds if f is not None and f.returns is Type.DICT and f.return_view is None else None return None def node_list_kinds(self, node: ast.expr) -> ir.DictKinds | None: @@ -2808,6 +2913,8 @@ def view_of(self, node: ast.expr) -> tuple[str, ast.expr] | None: (its view, the name itself, see view_dict); else None.""" if (view := self.view_name(node)) is not None: return view, node + if (f := self.view_call(node)) is not None: + return f.return_view, node # type: ignore[return-value] if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) \ and node.func.attr in ("keys", "values", "items") and not node.args and not node.keywords: kinds = self.node_dict_kinds(node.func.value) @@ -3015,9 +3122,7 @@ def dict_method_expr(self, func: ast.Attribute, node: ast.Call) -> ir.Expr: raise Skip(line, "copy() takes no argument") return ir.DictCopy(Type.DICT, (kt, vt), d) if m in ("keys", "values", "items"): - raise Skip(line, f"`{_src(node)}`: a view is used at once in an AOT program (the iterable of a `for` loop, " - "len(), `in`, its truth, print / str / repr / an f-string) or bound to a name; a view is " - "passed or returned not yet") + raise Skip(line, _view_misuse(f"`{_src(node)}`", m, (kt, vt))) if m in ("update", "clear"): raise Skip(line, f"uses the result of `{_src(node)}`, which returns None") if m == "popitem": @@ -3119,6 +3224,8 @@ def for_dict(self, node: ast.For) -> list[ir.Stmt] | None: view, it = it.func.attr, it.func.value elif (named := self.view_name(it)) is not None: view = named # tier S2b: `for k in ks` of a view local + elif (f := self.view_call(it)) is not None: + view = f.return_view or "keys" # ... and of a function that returns a view elif not self.is_dict_node(it): return None if view == "items": @@ -4069,6 +4176,10 @@ def return_(self, node: ast.Return) -> list[ir.Stmt]: if self.info.aot and returns is Type.DICT_LIST: # tier S2b: a list of dicts value = self.dict_list_value(node.value, self.sig.return_kinds, "the return value") return self.take() + [ir.Return(value)] + if self.info.aot and returns is Type.DICT and self.sig.return_view is not None: # tier S2b: a view + assert self.sig.return_kinds is not None + value = self.view_arg(node.value, self.sig.return_view, self.sig.return_kinds, "the return value") + return self.take() + [ir.Return(value)] if self.info.aot and returns is Type.DICT: # tier S2b kinds = self.sig.return_kinds value = self.dict_coerce(self.dict_operand(node.value, kinds), kinds, node.value, "the return value") @@ -4126,12 +4237,16 @@ def value(self, node: ast.expr) -> ir.Expr: return e def condition(self, node: ast.expr) -> ir.Expr: - if self.view_name(node) is not None: + if self.has_view_truth(node): return self.view_truth(node) return self.truth(self.sub(node, cond=2), node) + def has_view_truth(self, node: ast.expr) -> bool: + """`node` is a view local or a call of a function returning a view, whose truth is view_truth (tier S2b).""" + return self.view_name(node) is not None or self.view_call(node) is not None + def view_truth(self, node: ast.expr) -> ir.Expr: - """The truth of a view local: its dict is not empty (tier S2b).""" + """The truth of a view local or of a call returning a view: its dict is not empty (tier S2b).""" return ir.Compare(Type.BOOL, ir.CompareKind.NE, ir.DictLen(Type.I64, self.view_dict(node)), ir.Const(Type.I64, 0)) def truth(self, e: ir.Expr, node: ast.expr) -> ir.Expr: @@ -4268,6 +4383,9 @@ def expr(self, node: ast.expr, cond: int = 0) -> ir.Expr: return self.fstring(node) if isinstance(node, ast.IfExp) and self.info.aot: return self.aot_ifexp(node) + if isinstance(node, (ast.ListComp, ast.SetComp, ast.DictComp)) and self.info.aot: + raise Skip(line, f"`{_src(node)}`: an AOT program compiles a {UNSUPPORTED[type(node).__name__]} as the " + "value of an assignment to a name or of a `return` (tier S2c): bind it to a name first") raise _unsupported(node) def str_const(self, v: str, node: ast.AST) -> ir.Expr: @@ -4315,11 +4433,7 @@ def name(self, node: ast.Name) -> ir.Expr: raise Skip(node.lineno, f"`{name}` is read but never assigned") t = self.local_type(name, node.lineno) if name in self.view_locals: - raise Skip(node.lineno, f"`{name}` is a view of a dict ({_dict_name(self.dict_locals[name])}." - f"{self.view_locals[name]}()): an AOT program uses a view by a `for` loop, " - "len(), `in`, its truth, print / str / repr / an f-string, or binds it to " - "another view name; what a view has beyond that (set operators, comparison, " - "list() or dict() of it) and passing or returning it are not yet") + raise Skip(node.lineno, _view_misuse(f"`{name}`", self.view_locals[name], self.name_kinds(name))) if t is Type.STR_OPT and name in self.not_none: return ir.StrNarrow(Type.STR, ir.Local(t, name)) # tier S2a: proved not None here return ir.Local(t, name) @@ -4456,7 +4570,7 @@ def obj_binop(self, op: ir.BinOpKind, left: ir.Expr, right: ir.Expr, def unary(self, node: ast.UnaryOp) -> ir.Expr: if isinstance(node.op, ast.Not): - operand = self.view_truth(node.operand) if self.view_name(node.operand) is not None \ + operand = self.view_truth(node.operand) if self.has_view_truth(node.operand) \ else self.truth(self.sub(node.operand), node.operand) return ir.UnaryOp(Type.BOOL, ir.UnaryOpKind.NOT, operand) if not isinstance(node.op, (ast.USub, ast.UAdd, ast.Invert)): @@ -4618,7 +4732,7 @@ def boolop(self, node: ast.BoolOp, cond: int) -> ir.Expr: for i, v in enumerate(node.values): if i > 0: self.hoist_ok = False # evaluated only if the earlier operands did not decide - if cond and self.view_name(v) is not None: + if cond and self.has_view_truth(v): e = self.view_truth(v) # tier S2b: `k in ks and ks` else: e = self.sub(v, 1 if cond else 0) @@ -4858,7 +4972,7 @@ def aot_builtin_call(self, name: str, node: ast.Call) -> ir.Expr | None: raise Skip(line, "bool() takes one argument in an AOT program") if isinstance(args[0], ast.Name) and args[0].id in self.arrays: return ir.Compare(Type.BOOL, ir.CompareKind.NE, ir.Len(Type.I64, args[0].id), ir.Const(Type.I64, 0)) - if self.view_name(args[0]) is not None: + if self.has_view_truth(args[0]): return self.view_truth(args[0]) x = self.value(args[0]) return self.truth(x, args[0]) @@ -4960,9 +5074,17 @@ def aot_call(self, name: str, node: ast.Call, callee: ir.Function, tuple_ok: boo if name in self.info.aot_tuples and not tuple_ok: raise Skip(node.lineno, f"`{_src(node)}` returns a tuple, which an AOT program can only unpack into " f"names (`a, b = {name}(...)`)") + if callee.return_view is not None and not self.view_call_ok: + assert callee.return_kinds is not None + raise Skip(node.lineno, _view_misuse(f"`{_src(node)}`", callee.return_view, callee.return_kinds)) + self.view_call_ok = False # (an argument that calls a view function is its own use) self.hoist_ok = False args: list[ir.Expr] = [] for p, a in zip(callee.params, node.args): + if isinstance(p, ir.Param) and p.view is not None: # tier S2b: a view passed on + assert p.kinds is not None + args.append(self.view_arg(a, p.view, p.kinds, f"parameter `{p.name}` of `{name}`")) + continue if isinstance(p, ir.ArrayParam): if not (isinstance(a, ast.Name) and a.id in self.arrays): raise Skip(a.lineno, f"the argument `{_src(a)}` of `{name}` must be the name of a list (parameter " @@ -5035,6 +5157,10 @@ def method_call(self, func: ast.Attribute, node: ast.Call) -> ir.Expr | None: return None assert cls is not None if self.info.aot: + if callee.return_view is not None and not self.view_call_ok: # tier S2b: as aot_call + assert callee.return_kinds is not None + raise Skip(node.lineno, _view_misuse(f"`{_src(node)}`", callee.return_view, callee.return_kinds)) + self.view_call_ok = False self.check_not_none(func.value.id, cls, func.value) recv: ir.Expr = ir.Local(Type.OBJ, func.value.id) self.hoist_ok = False diff --git a/python-multiplatform-ksp/src/main/python/typedpython/ir.py b/python-multiplatform-ksp/src/main/python/typedpython/ir.py index fa9e6e55..2ef4e8ff 100644 --- a/python-multiplatform-ksp/src/main/python/typedpython/ir.py +++ b/python-multiplatform-ksp/src/main/python/typedpython/ir.py @@ -119,6 +119,13 @@ def is_set(k: object) -> bool: return isinstance(k, tuple) and len(k) == 2 and k[1] is Type.NONE +def view_match(view: str | None, a: "DictKinds", b: "DictKinds") -> bool: + """The views `view` ("keys", "values", "items"; None: the dicts themselves) of dicts of kinds `a` and `b` read the + same: the keys of a keys view, the values of a values view, both otherwise. A `KeysView[K]` does not say the + values of its dict, nor a `ValuesView[V]` its keys (tier S2b).""" + return a[0] == b[0] if view == "keys" else a[1] == b[1] if view == "values" else a == b + + def dict_has_float(k: "DictKinds") -> bool: """A float is among the values of `k` or of the dicts it holds.""" return k[1] is Type.F64 or (isinstance(k[1], tuple) and dict_has_float(k[1])) @@ -1699,6 +1706,7 @@ class Param: cls: str | None = None optional: bool = False kinds: DictKinds | None = None # AOT mode, tier S2b: the key and value types of a DICT parameter + view: str | None = None # ... and of a view parameter ("keys", "values", "items"): it holds the dict @dataclass(frozen=True) @@ -1825,6 +1833,7 @@ class Function: # AOT mode, tier S2b: the key and value types of every DICT local and parameter, and of a DICT return dict_kinds: dict[str, DictKinds] = field(default_factory=dict) return_kinds: DictKinds | None = None + return_view: str | None = None # a returned view ("keys", ...): the DICT returned is the view's dict @dataclass(frozen=True) diff --git a/python-multiplatform-ksp/src/main/python/typedpython/loops.py b/python-multiplatform-ksp/src/main/python/typedpython/loops.py new file mode 100644 index 00000000..4bf71330 --- /dev/null +++ b/python-multiplatform-ksp/src/main/python/typedpython/loops.py @@ -0,0 +1,217 @@ +"""AOT mode, tier S2c: `enumerate()` and `zip()` as the iterable of a loop (design 4.3.2, S2c). Agent proposal, not +owner-confirmed. + +A `for` statement (one the comprehension rewrite made included) over `enumerate(...)` or `zip(...)` is rewritten, on +the AST the lowering reads, into the loop it means (and so is one over `reversed(...)`, below): + + for i, x in enumerate(it, 1): n__e1: int = 1 + body for x in it: + i = n__e1 + n__e1 = n__e1 + 1 + body + + for a, b in zip(xs, ys): k__z1: int = 0 + body while k__z1 < len(xs) and k__z1 < len(ys): + a = xs[k__z1] + b = ys[k__z1] + k__z1 = k__z1 + 1 + body + +* enumerate: the iterable is any iterable a `for` loop takes; the counter is advanced before the body, so a + `continue` counts; `i` is bound each step, so after the loop it holds the last count (and keeps its old value when + the loop does not run), as in CPython. The start is an int constant (aot/program.py checks it), so evaluating it + before the iterable is not observable. +* zip: each operand is the name of a list or a str (aot/program.py checks it is a name the loop does not rebind; the + lowering refuses a dict or a set at the subscripts this pass marks, `tp_zip`). The length is read at every step, the + operands left to right: a list iterator reads its list's length at every `next`, and zip stops at the first operand + that is exhausted, so a list that grows or shrinks in the loop is seen doing so as CPython sees it. The elements are + read in the order zip reads them. + + for x in reversed(xs): k__r1: int = len(xs) - 1 + body while k__r1 >= 0 and k__r1 < len(xs): + x = xs[k__r1] + k__r1 = k__r1 - 1 + body + +* reversed: the operand is the name of a list or a str (or a str constant) the loop does not rebind, read by index + from its end; the index is checked against the length at every step, as CPython's reversed list iterator checks + it, so a list that shrinks in the loop ends it early and one that grows is not seen growing. + +Types: the hidden counter is an annotated int, and so is enumerate's count. zip's and reversed's names are assignments +now, typed as the elements of the operands: the type Pyrefly gives each operand's load in the `for` header (`sites` names them; +the probes insert nothing before a `for` header on its line), `list[T]` giving T and `str` giving str. In a loop the +comprehension rewrite made, the names are the comprehension's hidden variables, already typed at its probe. +""" +from __future__ import annotations + +import ast +import copy + +from typedpython import comprehensions + +Kinds = comprehensions.Kinds + + +def _indexed(f: ast.For) -> ast.Call | None: + """The zip() or reversed() call `f` reads by index: its iterable, or the iterable of its enumerate().""" + it = f.iter + if _counted(f) == "enumerate" and it.args: # type: ignore[attr-defined] + it = it.args[0] # type: ignore[attr-defined] + if isinstance(it, ast.Call) and isinstance(it.func, ast.Name) and it.func.id in ("zip", "reversed"): + return it + return None + + +def sites(functions: list[tuple[str, ast.FunctionDef]]) -> list[ast.Name]: + """The name operands of the zip() and reversed() loops of the functions, whose types `rewrite` needs (at their + load in the `for` header).""" + return [a for _, fn in functions for f in ast.walk(fn) if isinstance(f, ast.For) and (c := _indexed(f)) is not None + for a in c.args if isinstance(a, ast.Name)] + + +def _element(spelled: str | None, operand: ast.expr) -> str | None: + """The type of an element of the operand `operand` of zip() or reversed() typed `spelled`.""" + if isinstance(operand, ast.Constant) and isinstance(operand.value, str): + return "str" + if spelled is None: + return None + if spelled == "str": + return "str" + if spelled.startswith("list[") and spelled.endswith("]"): + return spelled[5:-1] + return None + + +def _counted(f: ast.For) -> str | None: + it = f.iter + if isinstance(it, ast.Call) and isinstance(it.func, ast.Name) and it.func.id in ("enumerate", "zip", "reversed") \ + and not it.keywords and not f.orelse: + return it.func.id + return None + + +def _start(e: ast.expr) -> int: + sign = 1 + if isinstance(e, ast.UnaryOp): + sign = -1 if isinstance(e.op, ast.USub) else 1 + e = e.operand + assert isinstance(e, ast.Constant) and type(e.value) is int + return sign * e.value + + +def _operand(a: ast.expr) -> bool: + return isinstance(a, ast.Name) or (isinstance(a, ast.Constant) and isinstance(a.value, str)) + + +def _name(n: str, ctx: ast.expr_context) -> ast.Name: + return ast.Name(id=n, ctx=ctx) + + +def _add_one(n: str, op: ast.operator | None = None) -> ast.stmt: + return ast.Assign(targets=[_name(n, ast.Store())], + value=ast.BinOp(left=_name(n, ast.Load()), op=op or ast.Add(), right=ast.Constant(1))) + + +def _len(a: ast.expr) -> ast.expr: + return ast.Call(func=_name("len", ast.Load()), args=[copy.deepcopy(a)], keywords=[]) + + +def _read(t: ast.expr, a: ast.expr, index: str) -> ast.stmt: + sub = ast.Subscript(value=copy.deepcopy(a), slice=_name(index, ast.Load()), ctx=ast.Load()) + sub.tp_indexed = True # type: ignore[attr-defined] (see the module docstring) + return ast.Assign(targets=[t], value=sub) + + +def _rewrite(f: ast.For, kind: str, fresh: str) -> list[ast.stmt] | None: + it = f.iter + assert isinstance(it, ast.Call) + if kind == "enumerate": + if not (1 <= len(it.args) <= 2 and isinstance(f.target, ast.Tuple) and len(f.target.elts) == 2 + and isinstance(f.target.elts[0], ast.Name)): + return None # (aot/program.py reports it) + start = _start(it.args[1]) if len(it.args) == 2 else 0 + init = ast.AnnAssign(target=_name(fresh, ast.Store()), annotation=_name("int", ast.Load()), + value=ast.Constant(start), simple=1) + step = [ast.Assign(targets=[f.target.elts[0]], value=_name(fresh, ast.Load())), _add_one(fresh)] + loop = ast.For(target=f.target.elts[1], iter=it.args[0], body=step + f.body, orelse=[], type_comment=None) + return [comprehensions._located(x, f) for x in (init, loop)] # type: ignore[misc] + if kind == "reversed": + if not (len(it.args) == 1 and _operand(it.args[0]) and isinstance(f.target, ast.Name)): + return None + a = it.args[0] + init = ast.AnnAssign(target=_name(fresh, ast.Store()), annotation=_name("int", ast.Load()), + value=ast.BinOp(left=_len(a), op=ast.Sub(), right=ast.Constant(1)), simple=1) + test = ast.BoolOp(op=ast.And(), values=[ + ast.Compare(left=_name(fresh, ast.Load()), ops=[ast.GtE()], comparators=[ast.Constant(0)]), + ast.Compare(left=_name(fresh, ast.Load()), ops=[ast.Lt()], comparators=[_len(a)])]) + loop = ast.While(test=test, body=[_read(f.target, a, fresh), _add_one(fresh, ast.Sub())] + f.body, orelse=[]) + return [comprehensions._located(x, f) for x in (init, loop)] # type: ignore[misc] + operands = it.args + if not (operands and all(_operand(a) for a in operands) and isinstance(f.target, ast.Tuple) + and len(f.target.elts) == len(operands) and all(isinstance(e, ast.Name) for e in f.target.elts)): + return None + init = ast.AnnAssign(target=_name(fresh, ast.Store()), annotation=_name("int", ast.Load()), + value=ast.Constant(0), simple=1) + tests = [ast.Compare(left=_name(fresh, ast.Load()), ops=[ast.Lt()], comparators=[_len(a)]) for a in operands] + test: ast.expr = tests[0] if len(tests) == 1 else ast.BoolOp(op=ast.And(), values=tests) + reads = [_read(t, a, fresh) for t, a in zip(f.target.elts, operands)] + loop = ast.While(test=test, body=reads + [_add_one(fresh)] + f.body, orelse=[]) + return [comprehensions._located(x, f) for x in (init, loop)] # type: ignore[misc] + + +def rewrite(functions: list[tuple[str, ast.FunctionDef]], kinds: Kinds, + types: dict[int, str]) -> tuple[Kinds, dict[str, str]]: + """Rewrite every such loop of the functions in place (see the module docstring): the kinds with the hidden counters + and the loops' names added, and the problems (IR function name -> "line N: ..."). `types`: id of an operand of + `sites` -> the type Pyrefly gives its load.""" + out = {q: {n: list(v) for n, v in d.items()} for q, d in kinds.items()} + problems: dict[str, str] = {} + for q, fn in functions: + taken = comprehensions._names(fn) + counter: dict[str, int] = {} + seen: set[int] = set() + while True: # (the loop an enumerate() makes may be over reversed(), rewritten in the next round) + loops = [n for n in ast.walk(fn) if isinstance(n, ast.For) and _counted(n) is not None and id(n) not in seen] + if not loops: + break + seen |= {id(n) for n in loops} + _round(q, fn, loops, out, problems, types, taken, counter) + return out, problems + + +def _round(q: str, fn: ast.FunctionDef, loops: list[ast.For], out: Kinds, problems: dict[str, str], + types: dict[int, str], taken: set[str], counter: dict[str, int]) -> None: + for f in loops: + kind = _counted(f) + assert kind is not None + base = "n" if kind == "enumerate" else "k" + letter = kind[0] + while True: + counter[q] = counter.get(q, 0) + 1 + fresh = f"{base}__{letter}{counter[q]}" + if fresh not in taken: + taken.add(fresh) + break + target, operands = f.target, f.iter.args # type: ignore[attr-defined] + new = _rewrite(f, kind, fresh) + if new is None: + continue + mine = out.setdefault(q, {}) + mine[fresh] = [(f.lineno, "int")] + if kind == "reversed": + names = [(target, operands[0])] + else: + assert isinstance(target, ast.Tuple) + names = list(zip(target.elts, operands)) if kind == "zip" else [(target.elts[0], None)] + for t, a in names: + assert isinstance(t, ast.Name) + if any(ln == f.lineno for ln, _ in mine.get(t.id, [])): + continue # (a comprehension's hidden variable, typed at its probe) + elem = "int" if a is None else _element(types.get(id(a)), a) + if elem is None: + problems.setdefault(q, f"line {f.lineno}: `{ast.unparse(a)}` is a {types.get(id(a), 'value of an ' + 'unknown type')}: {kind}() reads its operands by index in an AOT program, so " + "an operand is a list or a str") + break + mine.setdefault(t.id, []).append((f.lineno, elem)) + comprehensions._replace(fn, f, new) diff --git a/python-multiplatform-ksp/src/main/python/typedpython/ranges.py b/python-multiplatform-ksp/src/main/python/typedpython/ranges.py new file mode 100644 index 00000000..56d11fe2 --- /dev/null +++ b/python-multiplatform-ksp/src/main/python/typedpython/ranges.py @@ -0,0 +1,268 @@ +"""AOT mode, tier S2c: a range object held in a name (design 4.3.2, S2c). Agent proposal, not owner-confirmed. + +A local bound only to `range(...)` with an int constant step (`r = range(n)`, `r = range(a, b)`, `r = range(a, b, -2)`) +is held as two hidden int locals, its start and its stop; the step stays the constant. Each use is rewritten, on the +AST the lowering reads, into what CPython computes for a range object: + + r = range(a, b, 3) r__lo1 = a; r__hi1 = b (left to right, as CPython evaluates the arguments) + r__n3 = max(0, (r__hi1 - r__lo1 + 2) // 3) (the length, once per binding) + for x in r: for x in range(r__lo1, r__hi1, 3): + len(r) r__n3 + x in r r__lo1 <= x < r__hi1 and (x - r__lo1) % 3 == 0 + if r: / not r / bool(r) r__lo1 < r__hi1 (a negative step: r__hi1 < r__lo1) + print(r), str(r), repr(r) f"range({r__lo1}, {r__hi1}, 3)" (`range(a, b)` for a step of 1); in an f-string the same + parts, spliced in + +The loop a comprehension or an enumerate() makes over `r` is rewritten too (this pass runs after theirs). Anything +else is refused naming the reason: a range object passed, returned, indexed, sliced, in a list, compared, or given to +list(), zip(), reversed(); a name bound to a range and to anything else; a step that is not an int constant (the +lowering of a `for` over a range needs a constant step) or is 0 (CPython raises ValueError at run time; refused at +compile time here); a binding whose arguments read the name itself; `x in r` of an `x` that is not a name or a +constant (it is read twice). +""" +from __future__ import annotations + +import ast + +from typedpython import comprehensions + +Kinds = comprehensions.Kinds + +_USES = ("an AOT program uses a range object by a `for` loop, len(), `in`, its truth and print / str / repr / an " + "f-string") + + +class _Problem(Exception): + def __init__(self, line: int, message: str) -> None: + super().__init__(message) + self.line = line + + +def _is_range(e: ast.expr | None) -> bool: + return isinstance(e, ast.Call) and isinstance(e.func, ast.Name) and e.func.id == "range" + + +def _int_constant(e: ast.expr) -> int | None: + sign = 1 + if isinstance(e, ast.UnaryOp) and isinstance(e.op, (ast.USub, ast.UAdd)): + sign = -1 if isinstance(e.op, ast.USub) else 1 + e = e.operand + if isinstance(e, ast.Constant) and type(e.value) is int: + return sign * e.value + return None + + +def _load(n: str) -> ast.Name: + return ast.Name(id=n, ctx=ast.Load()) + + +class _Range: + def __init__(self, name: str, lo: str, hi: str, n: str, step: int) -> None: + self.name, self.lo, self.hi, self.n, self.step = name, lo, hi, n, step + + def is_me(self, e: ast.AST) -> bool: + return isinstance(e, ast.Name) and e.id == self.name and isinstance(e.ctx, ast.Load) + + def call(self) -> ast.expr: + args: list[ast.expr] = [_load(self.lo), _load(self.hi)] + if self.step != 1: + args.append(ast.Constant(self.step)) + return ast.Call(func=_load("range"), args=args, keywords=[]) + + def length(self) -> ast.expr: + return _load(self.n) + + def count(self) -> ast.expr: + """The length computed from the bounds (CPython's range length), in the binding's own statement.""" + m = abs(self.step) + first, second = (self.hi, self.lo) if self.step > 0 else (self.lo, self.hi) + span: ast.expr = ast.BinOp(left=_load(first), op=ast.Sub(), right=_load(second)) + if m != 1: + span = ast.BinOp(left=ast.BinOp(left=span, op=ast.Add(), right=ast.Constant(m - 1)), op=ast.FloorDiv(), + right=ast.Constant(m)) + return ast.Call(func=_load("max"), args=[ast.Constant(0), span], keywords=[]) + + def truth(self) -> ast.expr: + a, b = (self.lo, self.hi) if self.step > 0 else (self.hi, self.lo) + return ast.Compare(left=_load(a), ops=[ast.Lt()], comparators=[_load(b)]) + + def contains(self, x: ast.expr) -> ast.expr: + import copy + if self.step > 0: + bounds = ast.Compare(left=_load(self.lo), ops=[ast.LtE(), ast.Lt()], + comparators=[copy.deepcopy(x), _load(self.hi)]) + offset = ast.BinOp(left=copy.deepcopy(x), op=ast.Sub(), right=_load(self.lo)) + else: + bounds = ast.Compare(left=_load(self.hi), ops=[ast.Lt(), ast.LtE()], + comparators=[copy.deepcopy(x), _load(self.lo)]) + offset = ast.BinOp(left=_load(self.lo), op=ast.Sub(), right=copy.deepcopy(x)) + if abs(self.step) == 1: + return bounds + aligned = ast.Compare(left=ast.BinOp(left=offset, op=ast.Mod(), right=ast.Constant(abs(self.step))), + ops=[ast.Eq()], comparators=[ast.Constant(0)]) + return ast.BoolOp(op=ast.And(), values=[bounds, aligned]) + + def parts(self) -> list[ast.expr]: + tail = ")" if self.step == 1 else f", {self.step})" + return [ast.Constant("range("), ast.FormattedValue(value=_load(self.lo), conversion=-1, format_spec=None), + ast.Constant(", "), ast.FormattedValue(value=_load(self.hi), conversion=-1, format_spec=None), + ast.Constant(tail)] + + def text(self) -> ast.expr: + return ast.JoinedStr(values=self.parts()) + + +class _Uses(ast.NodeTransformer): + """Rewrite the uses of one range object (see the module docstring).""" + + def __init__(self, r: _Range) -> None: + self.r = r + + def visit_For(self, node: ast.For) -> ast.AST: + if self.r.is_me(node.iter): + node.iter = ast.copy_location(self.r.call(), node.iter) + return self.generic_visit(node) + + def _test(self, node: ast.If | ast.While | ast.IfExp) -> ast.AST: + if self.r.is_me(node.test): + node.test = ast.copy_location(self.r.truth(), node.test) + return self.generic_visit(node) + + visit_If = visit_While = visit_IfExp = _test + + def visit_UnaryOp(self, node: ast.UnaryOp) -> ast.AST: + if isinstance(node.op, ast.Not) and self.r.is_me(node.operand): + node.operand = ast.copy_location(self.r.truth(), node.operand) + return self.generic_visit(node) + + def visit_Compare(self, node: ast.Compare) -> ast.AST: + if len(node.ops) == 1 and isinstance(node.ops[0], (ast.In, ast.NotIn)) and self.r.is_me(node.comparators[0]) \ + and (isinstance(node.left, (ast.Name, ast.Constant)) or _int_constant(node.left) is not None) \ + and not self.r.is_me(node.left): + inside = ast.copy_location(self.r.contains(node.left), node) + if isinstance(node.ops[0], ast.NotIn): + return ast.copy_location(ast.UnaryOp(op=ast.Not(), operand=inside), node) + return inside + return self.generic_visit(node) + + def visit_Call(self, node: ast.Call) -> ast.AST: + f = node.func + if isinstance(f, ast.Name) and len(node.args) == 1 and not node.keywords and self.r.is_me(node.args[0]): + made = {"len": self.r.length, "bool": self.r.truth, "str": self.r.text, "repr": self.r.text}.get(f.id) + if made is not None: + return ast.copy_location(made(), node) + if isinstance(f, ast.Name) and f.id == "print": + node.args = [ast.copy_location(self.r.text(), a) if self.r.is_me(a) else a for a in node.args] + return self.generic_visit(node) + + def visit_JoinedStr(self, node: ast.JoinedStr) -> ast.AST: + values: list[ast.expr] = [] + for v in node.values: + if isinstance(v, ast.FormattedValue) and self.r.is_me(v.value) and v.format_spec is None \ + and v.conversion in (-1, ord("s"), ord("r")): + values += [ast.copy_location(p, v) for p in self.r.parts()] + else: + values.append(v) + node.values = values + return self.generic_visit(node) + + +def _bindings(fn: ast.FunctionDef, name: str) -> list[ast.AST]: + """Every node of `fn` that binds `name` (a statement, or a parameter).""" + out: list[ast.AST] = [a for a in ast.walk(fn.args) if isinstance(a, ast.arg) and a.arg == name] + for n in ast.walk(fn): + if isinstance(n, ast.Name) and n.id == name and isinstance(n.ctx, (ast.Store, ast.Del)): + out.append(n) + return out + + +def _one(fn: ast.FunctionDef, q: str, name: str, kinds: dict[str, list[tuple[int, str]]], taken: set[str], + counter: dict[str, int]) -> None: + sites = [s for s in ast.walk(fn) if isinstance(s, ast.Assign) and len(s.targets) == 1 + and isinstance(s.targets[0], ast.Name) and s.targets[0].id == name and _is_range(s.value)] + sites.sort(key=lambda s: (s.lineno, s.col_offset)) + targets = {id(s.targets[0]) for s in sites} + for b in _bindings(fn, name): + if id(b) not in targets: + line = getattr(b, "lineno", sites[0].lineno) + raise _Problem(line, f"`{name}` is bound to a range object at line {sites[0].lineno} and to something else " + f"at line {line}: an AOT range object is a name bound only to range(...)") + step: int | None = None + for s in sites: + call = s.value + assert isinstance(call, ast.Call) + if call.keywords or not 1 <= len(call.args) <= 3: + raise _Problem(s.lineno, "range() takes one to three positional arguments") + if any(isinstance(n, ast.Name) and n.id == name for a in call.args for n in ast.walk(a)): + raise _Problem(s.lineno, f"`{_src(s)}` reads `{name}` while binding it to a new range object, which an AOT " + "program does not do yet") + this = 1 + if len(call.args) == 3: + got = _int_constant(call.args[2]) + if got is None: + raise _Problem(s.lineno, f"the step `{_src(call.args[2])}` of the range object `{name}` is an int " + "constant in an AOT program") + if got == 0: + raise _Problem(s.lineno, f"`{_src(call)}`: range() arg 3 must not be zero (CPython raises ValueError; " + "an AOT program refuses it when it is compiled)") + this = got + if step is not None and this != step: + raise _Problem(s.lineno, f"the range object `{name}` is bound with the steps {step} and {this}: an AOT " + "range object has one constant step") + step = this + assert step is not None + lo, hi = _fresh(f"{name}__lo", taken, counter, q), _fresh(f"{name}__hi", taken, counter, q) + r = _Range(name, lo, hi, _fresh(f"{name}__n", taken, counter, q), step) + _Uses(r).visit(fn) + ast.fix_missing_locations(fn) # (a made node takes the location of the node it is in) + for n in ast.walk(fn): + if r.is_me(n): + raise _Problem(getattr(n, "lineno", sites[0].lineno), f"`{name}` is a range object: {_USES}") + for s in sites: + call = s.value + assert isinstance(call, ast.Call) + a = call.args + start: ast.expr = ast.Constant(0) if len(a) == 1 else a[0] + stop = a[0] if len(a) == 1 else a[1] + new = [ast.Assign(targets=[ast.Name(id=lo, ctx=ast.Store())], value=start), + ast.Assign(targets=[ast.Name(id=hi, ctx=ast.Store())], value=stop)] + if len(a) == 1: + new.reverse() # (`stop` is evaluated first either way; the constant start after it) + new.append(ast.Assign(targets=[ast.Name(id=r.n, ctx=ast.Store())], value=r.count())) + for hidden in (lo, hi, r.n): + kinds.setdefault(hidden, []).append((s.lineno, "int")) + comprehensions._replace(fn, s, [comprehensions._located(x, s) for x in new]) # type: ignore[misc] + + +def _src(node: ast.AST) -> str: + return ast.unparse(node) + + +def _fresh(base: str, taken: set[str], counter: dict[str, int], q: str) -> str: + while True: + counter[q] = counter.get(q, 0) + 1 + name = f"{base}{counter[q]}" + if name not in taken: + taken.add(name) + return name + + +def rewrite(functions: list[tuple[str, ast.FunctionDef]], kinds: Kinds) -> tuple[Kinds, dict[str, str]]: + """Rewrite every range object of the functions in place (see the module docstring): the kinds with the hidden + bounds added, and the problems (IR function name -> "line N: ...").""" + out = {q: {n: list(v) for n, v in d.items()} for q, d in kinds.items()} + problems: dict[str, str] = {} + for q, fn in functions: + names = sorted({s.targets[0].id for s in ast.walk(fn) if isinstance(s, ast.Assign) and len(s.targets) == 1 + and isinstance(s.targets[0], ast.Name) and _is_range(s.value)}) + if not names: + continue + taken = comprehensions._names(fn) + counter: dict[str, int] = {} + for name in names: + try: + _one(fn, q, name, out.setdefault(q, {}), taken, counter) + except _Problem as e: + problems.setdefault(q, f"line {e.line}: {e}") + break + return out, problems diff --git a/python-multiplatform-ksp/src/main/python/typedpython/verify.py b/python-multiplatform-ksp/src/main/python/typedpython/verify.py index 3d75d8b4..5ee0c98b 100644 --- a/python-multiplatform-ksp/src/main/python/typedpython/verify.py +++ b/python-multiplatform-ksp/src/main/python/typedpython/verify.py @@ -953,8 +953,9 @@ def bound_var(self, var: str, want: "Type | ir.DictKinds", what: str) -> None: self.error(TYPE, f"{what} target {var!r} must be a declared {ir.dict_vtype(want).value} local" + (f" of kinds {want!r}" if isinstance(want, tuple) else "")) - def dict_same(self, a: ir.DictKinds | None, b: ir.DictKinds | None, what: str) -> None: - if a is not None and b is not None and a != b: + def dict_same(self, a: ir.DictKinds | None, b: ir.DictKinds | None, what: str, view: str | None = None) -> None: + """`a` is `b`; of a view (`Param.view`, `Function.return_view`, a DictView value), the half the view reads.""" + if a is not None and b is not None and not ir.view_match(view, a, b): self.error(TYPE, f"{what}: a dict of {a!r} where a dict of {b!r} is wanted") def param_class(self, p: Param) -> None: @@ -1641,7 +1642,7 @@ def e_Call(self, e: Call, state: _State) -> ir.Expr: self.slot(a, p.type, f"argument {k + 1} of '{e.function}'") if self.aot and type(p) is Param and p.type in (Type.DICT, Type.DICT_LIST) \ and getattr(a, "type", None) is p.type: - self.dict_same(self.kinds_any(a), p.kinds, f"argument {k + 1} of '{e.function}'") + self.dict_same(self.kinds_any(a), p.kinds, f"argument {k + 1} of '{e.function}'", p.view) # SPEC N-13: a redo Call of an i64-returning callee gives an INT (the redone value is any int) int_result = (redo_ok and callee.returns is Type.I64 and e.type is Type.INT) if e.type is not callee.returns and not int_result: @@ -2819,7 +2820,8 @@ def s_Assign(self, s: Assign, state: _State): self.slot(value, self.scalars[target], f"assignment to '{target}'") if self.aot and self.scalars[target] in (Type.DICT, Type.DICT_LIST) \ and getattr(value, "type", None) is self.scalars[target]: - self.dict_same(self.kinds_any(value), self.fn.dict_kinds.get(target), f"assignment to '{target}'") + self.dict_same(self.kinds_any(value), self.fn.dict_kinds.get(target), f"assignment to '{target}'", + value.view if isinstance(value, DictView) else None) if getattr(value, "type", None) is Type.NONE: self.error(TYPE, f"None assigned to '{target}'") if target in self.entry: @@ -3549,7 +3551,7 @@ def s_Return(self, s: Return, state: _State): if isinstance(returns, Type): self.slot(value, returns, "return value") if self.aot and returns in (Type.DICT, Type.DICT_LIST) and getattr(value, "type", None) is returns: - self.dict_same(self.kinds_any(value), self.fn.return_kinds, "the return value") + self.dict_same(self.kinds_any(value), self.fn.return_kinds, "the return value", self.fn.return_view) if self.aot and getattr(value, "type", None) in ir.ARRAYS: self.error(TYPE, f"a list is returned from a function returning {getattr(returns, 'value', returns)}") return dataclasses.replace(s, value=value), None diff --git a/python-multiplatform-ksp/src/test/python/test_aot_check.py b/python-multiplatform-ksp/src/test/python/test_aot_check.py index f2b49ed7..112b02e1 100644 --- a/python-multiplatform-ksp/src/test/python/test_aot_check.py +++ b/python-multiplatform-ksp/src/test/python/test_aot_check.py @@ -39,6 +39,8 @@ def found(report, rule): ("aot/import", "def f() -> None:\n import math\n", (ERR, None, "math", 2)), ("aot/import", "from . import x\n", (ERR, None, ".", 1)), ("aot/import", "from math import *\n", (ERR, None, "math", 1)), + ("aot/import", "from collections.abc import Mapping\n", (ERR, None, "collections.abc", 1)), + ("aot/import", "from collections.abc import KeysView as K\n", (ERR, None, "collections.abc", 1)), # aot/identity ("aot/identity", "def f(x: int) -> int:\n return id(x)\n", (ERR, None, "id", 2)), ("aot/identity", "def f(x: int) -> int:\n return hash(x)\n", (ERR, None, "hash", 2)), @@ -180,6 +182,61 @@ def f(s: set[int]) -> int: assert report.findings == [], report.lines() +def test_a_comprehension_bound_to_a_name_or_returned_is_not_reported(tmp_path): + """Tier S2c: such a comprehension is the loop it means (typedpython/comprehensions.py); as an operand it is still + pending (the table row above).""" + path = write(tmp_path, """ + def f(xs: list[int]) -> list[int]: + ys = [x + 1 for x in xs if x] + s: set[int] = {x for x in ys} + d = {x: x * 2 for x in range(3)} + return [y for y in ys] + """) + report = aotcheck.check(path, front_end=False) + assert report.findings == [], report.lines() + + +def test_enumerate_and_zip_as_the_iterable_of_a_loop_are_not_reported(tmp_path): + """Tier S2c: `for i, x in enumerate(...)`, `for a, b in zip(...)` and `for x in reversed(...)`, in a `for` statement or a placed comprehension, + are the loops they mean (typedpython/loops.py); anywhere else they are still pending.""" + path = write(tmp_path, """ + def f(xs: list[int], ws: list[str]) -> list[int]: + for i, x in enumerate(xs, 1): + print(i, x) + for w, x in zip(ws, xs): + print(w, x) + for w in reversed(ws): + print(w) + for i, x in enumerate(reversed(xs)): + print(i, x) + return [i * x for i, x in enumerate(xs)] + """) + report = aotcheck.check(path, front_end=False) + assert report.findings == [], report.lines() + path = write(tmp_path, """ + def f(xs: list[int]) -> int: + return len(list(zip(xs, xs))) + sum(1 for _ in enumerate(xs)) + len(list(reversed(xs))) + """) + names = {f.name for f in aotcheck.check(path, front_end=False).findings} + assert {"zip", "enumerate", "reversed"} <= names, names + + +def test_the_view_types_of_collections_abc_are_not_reported(tmp_path): + """Tier S2b: `from collections.abc import KeysView, ValuesView, ItemsView` names the types of a view passed to or + returned from a function (the front end checks how the view is used).""" + path = write(tmp_path, """ + from collections.abc import ItemsView, KeysView, ValuesView + + def f(k: KeysView[str], v: ValuesView[int], i: ItemsView[str, int]) -> int: + return len(k) + len(v) + len(i) + + def g(d: dict[str, int]) -> KeysView[str]: + return d.keys() + """) + report = aotcheck.check(path, front_end=False) + assert report.findings == [], report.lines() + + # --- several findings in one function --------------------------------------------------------------- def test_every_finding_of_a_function_is_reported(tmp_path): diff --git a/python-multiplatform-ksp/src/test/python/test_aot_lib_dict.py b/python-multiplatform-ksp/src/test/python/test_aot_lib_dict.py index 12ea7502..c1a1ce85 100644 --- a/python-multiplatform-ksp/src/test/python/test_aot_lib_dict.py +++ b/python-multiplatform-ksp/src/test/python/test_aot_lib_dict.py @@ -499,6 +499,38 @@ def f(d: dict[int, int], k: int) -> int: assert [p["type"] for p in d["functions"][0]["params"]] == ["dict_i64_i64", "i64"] + +def test_a_view_passed_to_a_helper_is_not_a_write(tmp_path): + """A KeysView parameter of a helper holds the caller's dict, and a view is only read, so passing `d.keys()` on + keeps the export read-only.""" + src = write(tmp_path, ''' +from collections.abc import KeysView + + +def count(ks: KeysView[int]) -> int: + n = 0 + for k in ks: + n += k + return n + len(ks) + + +def f(d: dict[int, int]) -> int: + return count(d.keys()) +''') + _c, _h, d = aot.generate_library(src, exports=["f"], prefix="w") + assert [p["type"] for p in d["functions"][0]["params"]] == ["dict_i64_i64"] + + +@pytest.mark.parametrize("sig", ["k: KeysView[int]) -> int:\n return len(k)", + "d: dict[int, int]) -> KeysView[int]:\n return d.keys()"]) +def test_a_view_does_not_cross_the_library_boundary(tmp_path, sig): + """A view has no Kotlin type at the boundary: an export with a view parameter or result is refused.""" + src = write(tmp_path, f"from collections.abc import KeysView\n\n\ndef f({sig}\n") + with pytest.raises(aot.AotError) as e: + aot.generate_library(src, exports=["f"], prefix="o") + found = [aot.format_finding(f) for f in e.value.findings] + assert {f.rule for f in e.value.findings} == {"aot/export"} and "(KeysView[int]) is outside" in found[0], found + OUTSIDE = { "str_key": "d: dict[str, int]) -> int:\n return len(d)", "str_value": "d: dict[int, str]) -> int:\n return len(d)", diff --git a/python-multiplatform-ksp/src/test/python/test_aot_tier_s2b.py b/python-multiplatform-ksp/src/test/python/test_aot_tier_s2b.py index 467be12e..7f083c60 100644 --- a/python-multiplatform-ksp/src/test/python/test_aot_tier_s2b.py +++ b/python-multiplatform-ksp/src/test/python/test_aot_tier_s2b.py @@ -752,6 +752,145 @@ def test_a_loop_over_a_view_name_raises_where_cpython_raises(tmp_path: Path): _compare(tmp_path, VIEW_CHANGED, [["0"], ["1"]]) +VIEW_PASSED = """ +import sys +from collections.abc import ItemsView, KeysView, ValuesView + + +def count(ks: KeysView[str]) -> int: + n = 0 + for k in ks: + n += len(k) + return n + + +def show(vs: ValuesView[float], its: ItemsView[str, int]) -> str: + return f"{vs} {its} {len(vs)} {len(its)} {bool(vs)} {('zz', 1) not in its} {('a', 1) in its}" + + +def keys_of(d: dict[str, int]) -> KeysView[str]: + return d.keys() + + +def passed_on(ks: KeysView[str]) -> KeysView[str]: + return ks + + +def fresh(n: int) -> ValuesView[int]: + d = {"m": n, "n": n + 1} + return d.values() + + +def main() -> None: + d = {"a": 1, "b": 2} + f = {"x": 1.5} + ks = keys_of(d) + for w in sys.argv[1].split(","): + d[w] = len(w) + print(ks, len(ks), "a" in ks, count(ks), count(d.keys())) + g = {"q": 2.5, "rr": 0.5} + print(count(g.keys())) + print(show(f.values(), d.items())) + again = passed_on(ks) + d["new"] = 3 + print(again, len(passed_on(d.keys()))) + for k in keys_of(d): + print(k) + print(len(keys_of(d)), "zz" in keys_of(d), keys_of(d)) + vs = fresh(len(d)) + print(vs, 7 in vs, fresh(1)) + total = 0 + for v in fresh(2): + total += v + print(total) + e: dict[str, int] = {} + if keys_of(e) or not keys_of(d): + print("empty") + print(bool(keys_of(e)), not keys_of(e), bool(keys_of(d)) and "a" in keys_of(d)) + + +if __name__ == "__main__": + main() +""" + + +def test_a_view_is_passed_to_and_returned_from_a_function(tmp_path: Path): + """A KeysView[K], ValuesView[V] or ItemsView[K, V] parameter or result (imported from collections.abc) is the + live view: it holds its dict, a KeysView[str] takes the keys of a dict of any values, and the view of a dict made + in the callee keeps that dict alive, as in CPython.""" + _compare(tmp_path, VIEW_PASSED, [["c,a,dd"], ["b"]]) + + +VIEW_METHOD = """ +import sys +from collections.abc import ItemsView, KeysView, ValuesView + + +def count(ks: KeysView[str]) -> int: + n = 0 + for k in ks: + n += len(k) + return n + + +class Stock: + items: dict[str, int] + + def __init__(self) -> None: + self.items = {} + + def names(self) -> KeysView[str]: + return self.items.keys() + + def amounts(self) -> ValuesView[int]: + return self.items.values() + + def entries(self) -> ItemsView[str, int]: + return self.items.items() + + def total(self) -> int: + t = 0 + for v in self.amounts(): + t += v + return t + count(self.names()) + + +def names_of(s: Stock) -> KeysView[str]: + return s.names() + + +def main() -> None: + s = Stock() + ks = s.names() + print(ks, len(ks), bool(ks), not s.names()) + for w in sys.argv[1].split(","): + s.items[w] = len(w) + print(ks, s.amounts(), s.entries(), len(s.names()), "a" in s.names(), 3 in s.amounts()) + for k in s.names(): + print(k, end=";") + print() + for k, v in s.entries(): + print(k, v, end=";") + print() + print(s.total(), count(s.names()), names_of(s), ("a", 1) in s.entries()) + vs = s.amounts() + s.items["zz"] = 7 + print(vs, len(names_of(s))) + if s.names() and 7 in vs: + print("yes") + + +if __name__ == "__main__": + main() +""" + + +def test_a_method_returns_a_view(tmp_path: Path): + """A method `-> KeysView[K]` (ValuesView, ItemsView) returns the live view of its object's dict, used as a view + returned by a module function is (a local, a loop, len, in, truth, passed on, returned).""" + _compare(tmp_path, VIEW_METHOD, [["c,a,dd"], ["b"]]) + + WORDFREQ = Path(__file__).resolve().parents[4] / "benchmarks" / "typedpython" / "py" / "wordfreq.py" @@ -818,3 +957,35 @@ def _rules(tmp_path: Path, source: str) -> set[tuple[str, str]]: def test_what_a_dict_cannot_hold_yet_is_refused_with_the_reason(tmp_path: Path, body: str, reason: str): found = _rules(tmp_path, "def f() -> None:\n" + body + MAIN) assert any(reason in m for _, m in found), found + + +ABC = "from collections.abc import ItemsView, KeysView, ValuesView\n\n\n" + + +@pytest.mark.parametrize("source, reason", [ + # only the three view types, by their own names + ("from collections.abc import Mapping\n\n\ndef f(m: Mapping[str, int]) -> int:\n return len(m)\n", + "aot/import"), + ("from collections.abc import KeysView as K\n\n\ndef f(k: K[str]) -> int:\n return len(k)\n", "aot/import"), + ("import collections.abc\n\n\ndef f() -> None:\n pass\n", "aot/import"), + # a view parameter takes a view of that kind; a view result is a view of that kind + (ABC + "def f(k: KeysView[str]) -> int:\n return len(k)\n\n\ndef g() -> None:\n d = {'a': 1}\n" + " print(f(d.values()))\n", "a view"), + (ABC + "def f(k: KeysView[str]) -> int:\n return len(k)\n\n\ndef g() -> None:\n d = {1: 1}\n" + " print(f(d.keys()))\n", "a view"), + (ABC + "def f(k: KeysView[str]) -> int:\n return len(k)\n\n\ndef g() -> None:\n d = {'a': 1}\n" + " print(f(d))\n", "a view"), + (ABC + "def f(d: dict[str, int]) -> KeysView[str]:\n return d.values()\n", "a view"), + # a view parameter is used as a view + (ABC + "def f(k: KeysView[str]) -> bool:\n return k == {'a'}\n", "is a view"), + (ABC + "def f(k: ItemsView[str, int]) -> None:\n print(dict(k))\n", "is a view"), + (ABC + "def f(k: KeysView[float]) -> int:\n return len(k)\n", "outside the AOT mode"), + # a method's view is used as a view too + (ABC + "class C:\n d: dict[str, int]\n\n def __init__(self) -> None:\n self.d = {}\n\n def ks(self) -> KeysView[str]:\n return self.d.keys()\n\n\ndef g() -> None:\n c = C()\n print(c.ks() == {'a'})\n", "`c.ks()` is a view"), + (ABC + "class C:\n d: dict[str, int]\n\n def __init__(self) -> None:\n self.d = {}\n\n def ks(self) -> KeysView[str]:\n return self.d.keys()\n\n\ndef h(d: dict[str, int]) -> int:\n return len(d)\n\n\ndef g() -> None:\n c = C()\n print(h(c.ks()))\n", "`c.ks()` is a view"), + (ABC + "class C:\n d: dict[str, int]\n\n def __init__(self) -> None:\n self.d = {}\n\n" + " def ks(self) -> KeysView[str]:\n return self.d.values()\n", "but the return value is a view"), +]) +def test_what_a_view_parameter_or_result_cannot_do_is_refused(tmp_path: Path, source: str, reason: str): + found = _rules(tmp_path, source + "\n\n" + MAIN.replace("f()", "pass")) + assert any(reason in r or reason in m for r, m in found), found diff --git a/python-multiplatform-ksp/src/test/python/test_aot_tier_s2c.py b/python-multiplatform-ksp/src/test/python/test_aot_tier_s2c.py new file mode 100644 index 00000000..647a73e7 --- /dev/null +++ b/python-multiplatform-ksp/src/test/python/test_aot_tier_s2c.py @@ -0,0 +1,289 @@ +"""AOT mode, tier S2c (design 4.3.2): comprehensions, built without CPython and compared with CPython. + +A list, set or dict comprehension that is the value of an assignment to a name or of a `return` is lowered as the loop +it means (typedpython/comprehensions.py): a hidden local per comprehension variable (Python 3 scoping: the enclosing +name of the same spelling is not touched), the accumulator built in place, the first iterable evaluated before +anything else, CPython's exceptions where CPython raises them. Agent proposal, not owner-confirmed. +""" +from __future__ import annotations + +from pathlib import Path + +import pytest + +from test_aot_tier_s1 import _compare, _write +from typedpython import aot + + +COMPS = """ +import sys + + +def evens(xs: list[int]) -> list[int]: + return [x * 2 for x in xs if x % 2 == 0] + + +def lengths(words: list[str]) -> dict[str, int]: + out = {w: len(w) for w in words} + return out + + +def main() -> None: + words = sys.argv[1].split(",") + x = "outer" + lens = [len(x) for x in words] + print(lens, x) + upper = [w.upper() for w in words if w] + pairs = [i * j for i in range(4) for j in range(i) if j != 1] + halves: list[float] = [i / 2 for i in range(4)] + counts = lengths(words) + firsts = {w[0] for w in words if w} + print(upper, pairs, halves, counts, len(firsts), "a" in firsts, "q" in firsts) + d = {"a": 1, "b": 2} + inv = {v: k for k, v in d.items()} + vals = [v + 1 for v in d.values()] + four = [1, 2, 3, 4] + e4 = evens(four) + e0 = evens(lens) + print(inv, vals, e4, e0) + xs = [1, 2, 3] + xs = [x + 10 for x in xs] + print(xs) + chars = [c for c in "h\\u00e9llo" if c != "l"] + none = [c for c in ""] + print(chars, none, len(none)) + nested = [a + b for a in words for b in words if a < b] + print(nested) + nums = [int(t) for t in sys.argv[2].split(",")] + print(nums) + q = [100 // n for n in nums] + print(q) + + +if __name__ == "__main__": + main() +""" + + +def test_list_set_and_dict_comprehensions_are_the_loops_they_mean(tmp_path: Path): + """Filters, several `for` clauses, a tuple target over items(), a comprehension over its own target's old value, + Python 3 scoping (the outer `x` stays "outer") and the exception of an element (ZeroDivisionError) as in CPython.""" + _compare(tmp_path, COMPS, [["a,bb,ccc", "1,2,5"], ["b", "5"], ["x,y", "3,0"]]) + + +LOOPS = """ +import sys + + +def weigh(words: list[str], nums: list[int]) -> int: + t = 0 + for w, n in zip(words, nums): + t += len(w) * n + return t + + +def main() -> None: + words = sys.argv[1].split(",") + nums = [int(t) for t in sys.argv[2].split(",")] + i = 99 + for i, w in enumerate(words): + print(i, w) + print(i) + for i, w in enumerate(words, 1): + if i == 2: + continue + print(i, w, end=";") + print() + for i, c in enumerate("h\u00e9!", -1): + print(i, c) + d = {"a": 1, "b": 2} + for i, k in enumerate(d): + print(i, k) + for i, v in enumerate(d.values()): + print(i, v) + for i, (k, v) in enumerate(d.items()): + for j, w in enumerate(words): + print(i, k, v, j, w, end=";") + print() + for i, j in enumerate(range(3, 6)): + print(i * j) + for w, n in zip(words, nums): + print(w * n) + print(weigh(words, nums)) + for a, b, c in zip(words, nums, "xyz"): + print(a, b, c) + idx = [i * 10 for i, w in enumerate(words) if w] + both = {w: n for w, n in zip(words, nums)} + print(idx, both) + grow = [1, 2] + for x, y in zip(grow, nums): + grow.append(x + y) + print(x, y) + print(grow) + for i, n in enumerate(nums): + if i > 5: + break + print(100 // n) + + +if __name__ == "__main__": + main() +""" + + +def test_enumerate_and_zip_are_the_loops_they_mean(tmp_path: Path): + """`for i, x in enumerate(it, start)` counts beside the loop over `it` (a list, a str, a dict, a view, a range), the + counter left at its last value as in CPython; `for a, b in zip(xs, ys)` reads each list or str by index up to the + shortest, the length read at every step (a list that grows in the loop is seen growing, as CPython's iterator sees + it); both in a `for` statement and in a comprehension. Agent proposal, not owner-confirmed.""" + _compare(tmp_path, LOOPS, [["a,bb,ccc", "1,2,5"], ["b", "5,6"], ["x,y", "3,0"]]) + + +REVERSED = """ +import sys + + +def last_first(ws: list[str]) -> str: + out = "" + for w in reversed(ws): + out += w + return out + + +def main() -> None: + words = sys.argv[1].split(",") + nums = [int(t) for t in sys.argv[2].split(",")] + for w in reversed(words): + print(w) + for c in reversed("h\u00e9!"): + print(c, end="") + print() + print(last_first(words)) + back = [n * 2 for n in reversed(nums) if n != 2] + print(back) + for i, n in enumerate(reversed(nums)): + print(i, n) + for w, n in zip(words, nums): + for c in reversed(w): + print(c * n, end=";") + print() + shrink = [1, 2, 3, 4] + for x in reversed(shrink): + print(x) + if x == 4: + shrink.pop() + shrink.pop() + print(shrink) + grow = [1, 2] + for x in reversed(grow): + grow.append(x) + print(grow) + for n in reversed(nums): + print(10 // n) + + +if __name__ == "__main__": + main() +""" + + +def test_reversed_is_the_loop_it_means(tmp_path: Path): + """`for x in reversed(xs)` of a list or a str reads it by index from its 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. In a `for` statement, in a comprehension and inside enumerate(). Agent proposal, + not owner-confirmed.""" + _compare(tmp_path, REVERSED, [["a,bb,ccc", "1,2,5"], ["b", "5,6"], ["x,y", "3,0"]]) + + +RANGES = """ +import sys + + +def main() -> None: + n = int(sys.argv[1]) + r = range(n) + s = range(2, n + 3, 3) + t = range(n, -2, -2) + print(r, s, t, len(r), len(s), len(t)) + print(f"{r}|{s!r}|{t} end", str(s), repr(t)) + for x in s: + print(x, end=" ") + print() + total = 0 + for x in t: + total += x + print(total) + k = 4 + print(k in s, 5 in s, 3 in t, 2 in t, -1 not in t, n in r, 0 in r) + if r: + print("r has", len(r)) + if not t: + print("t is empty") + print(bool(s), not r) + sq = [x * x for x in s if x != 5] + print(sq) + for i, x in enumerate(t): + print(i, x, end=";") + print() + r = range(1, n) + print(r, len(r), 1 in r, bool(r)) + + +if __name__ == "__main__": + main() +""" + + +def test_a_range_object_is_its_bounds(tmp_path: Path): + """`r = range(a, b, STEP)` (a constant step) is held as its start and stop: a `for` loop over it, len(), `in`, its + truth and its repr (print, str, repr, an f-string) are CPython's, for a positive and a negative step and an empty + range. Agent proposal, not owner-confirmed.""" + _compare(tmp_path, RANGES, [["5"], ["0"], ["1"], ["-3"]]) + + +def _rules(tmp_path: Path, source: str) -> set[tuple[str, str]]: + with pytest.raises(aot.AotError) as raised: + aot.generate(_write(tmp_path, source)) + return {(f.rule, f.message) for f in raised.value.findings} + + +MAIN = '\n\ndef main() -> None:\n f()\n\n\nif __name__ == "__main__":\n main()\n' + + +@pytest.mark.parametrize("body, reason", [ + # a comprehension is the value of an assignment to a name or of a return + (" xs = [1, 2]\n print([x for x in xs])\n", "bind it to a name"), + (" xs = [1, 2]\n n = len([x for x in xs])\n print(n)\n", "bind it to a name"), + # a generator expression is not a comprehension (no generators in an AOT program) + (" xs = [1, 2]\n print(sum(x for x in xs))\n", "generator expression"), + # what the loop it means cannot hold is refused as that loop is + (" xs = [1, 2]\n ys = [x > 1 for x in xs]\n print(ys)\n", "list[bool]"), + # a name bound inside it (`:=`) leaks to the enclosing scope in CPython; `:=` is outside the AOT mode anyway + (" xs = [1, 2]\n ys = [(y := x) for x in xs]\n print(ys)\n", "NamedExpr"), + # enumerate and zip are the iterable of a loop, unpacked into names + (" xs = [1, 2]\n for t in enumerate(xs):\n print(t)\n", "unpacked into"), + (" xs = [1, 2]\n e = enumerate(xs)\n print(e)\n", "enumerate"), + (" xs = [1, 2]\n n = len(xs)\n for i, x in enumerate(xs, n):\n print(i, x)\n", "start"), + (" xs = [1, 2]\n for a, b in zip(xs, xs, strict=True):\n print(a, b)\n", "keyword"), + (" xs = [1, 2]\n for a, b in zip(xs, [3]):\n print(a, b)\n", "names"), + (" xs = [1, 2]\n for a in zip(xs, xs):\n print(a)\n", "unpacked into"), + (" xs = [1, 2]\n ys = [3]\n for a, b in zip(xs, ys):\n xs = ys\n print(a, b)\n", "rebinds"), + (" d = {1: 2}\n xs = [1, 2]\n for a, b in zip(d, xs):\n print(a, b)\n", "a list or a str"), + (" d = {1: 2}\n xs = [1, 2]\n ys = [a + b for a, b in zip(d, xs)]\n print(ys)\n", "a dict or a set"), + # reversed() is the iterable of a loop, of a list or a str name the loop does not rebind + (" d = {1: 2}\n for k in reversed(d):\n print(k)\n", "a list or a str"), + (" d = {1: 2}\n ks = [k for k in reversed(d)]\n print(ks)\n", "a dict or a set"), + (" xs = [1, 2]\n r = reversed(xs)\n print(r)\n", "reversed"), + (" xs = [1, 2]\n for x in reversed(xs):\n xs = [3]\n print(x)\n", "rebinds"), + (" xs = [1, 2]\n for x in reversed(xs + xs):\n print(x)\n", "names"), + # a range object is used by a loop, len(), `in`, its truth and its repr; its step is an int constant + (" r = range(3)\n print(list(r))\n", "a range object"), + (" r = range(3)\n print(r[0])\n", "a range object"), + (" r = range(3)\n r = 4\n print(r)\n", "a range object"), + (" n = 2\n r = range(0, 9, n)\n print(len(r))\n", "step"), + (" r = range(1, 5, 0)\n print(len(r))\n", "must not be zero"), + (" r = range(3)\n xs = [1, 2]\n for a, b in zip(r, xs):\n print(a, b)\n", "a list or a str"), +]) +def test_what_a_comprehension_cannot_do_yet_is_refused_with_the_reason(tmp_path: Path, body: str, reason: str): + found = _rules(tmp_path, "def f() -> None:\n" + body + MAIN) + assert any(reason in r or reason in m for r, m in found), found