Skip to content

Commit 2c786ab

Browse files
authored
Merge pull request #559 from thisisthepy/feat/tp-s2-land
TypedPython AOT S2c: tuple keys for sorted and list.sort
2 parents 7e0db77 + f488ae4 commit 2c786ab

11 files changed

Lines changed: 175 additions & 29 deletions

File tree

‎docs/design/typedpython-aot.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -578,7 +578,7 @@ is applied (its body binds nothing and makes no function). As `list_sort_impl` d
578578
then every key, left to right, into a hidden list (a key that raises stops the sort before any item moved), then
579579
CPython's listsort orders (key, position) pairs by key only (`TPA__DEF_KEYSORT`, the same `TPA__DEF_SORT`, so the
580580
pairs move as CPython moves its keys and values together) and each list is moved by the positions (one list, or
581-
every element list of a list of tuples). Keys are int (raw or big), float or str; a tuple key is not in yet. While
581+
every element list of a list of tuples). Keys are int (raw or big), float or str, or (sorted() and list.sort() only) a tuple of int and str elements: the hidden list of keys is then a list of tuples, its element lists are the sort's columns, and `tpa_tuple_keysort` compares them as CPython compares tuples, the first column whose items differ deciding (agent proposal, not owner-confirmed). A float element is refused (NaN is not equal to itself, which tuple comparison's equality step depends on), and so is a tuple key of min() / max(). While
582582
CPython computes the keys of `xs.sort` the list is empty, so a key that reaches `xs` sees `[]`: `xs.sort(key=k)` is
583583
refused unless its items are int, float, str, bool, bytes, `str | None` or tuples of them and every name the key
584584
reads that the function binds holds one of those (sort a copy with sorted() otherwise). Without a key it is in (agent proposal, not confirmed): `xs.sort(reverse=r)` of a list of int,

‎python-multiplatform-ksp/src/main/python/typedpython/aot/emit.py‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3167,25 +3167,38 @@ def st_ListSort(self, s: ir.ListSort) -> None:
31673167
self.emit(f"if ({self.lop(found[1], 'sort')}({found[0]}, {rev})) {self.fail()}")
31683168

31693169
def st_ListSortKeyed(self, s: ir.ListSortKeyed) -> None:
3170-
"""The keyed sort (tp_aot.h `TPA__DEF_KEYSORT`): every list as long as the keys (else CPython's ValueError),
3171-
the positions sorted by key, then every list moved by them."""
3170+
"""The keyed sort (tp_aot.h `TPA__DEF_KEYSORT`, `tpa_tuple_keysort` for a tuple key's columns): every list as
3171+
long as the keys (else CPython's ValueError), the positions sorted by key, then every list moved by them."""
31723172
rev = self.ev(s.reverse)
3173-
keys = self.grow_list(s.keys, "the keys of a sort")
3173+
keys = [self.grow_list(k, "the keys of a sort") for k in s.keys]
31743174
lists = [self.grow_list(a, "a keyed sort") for a in s.arrays]
3175-
if keys is None or any(x is None for x in lists):
3175+
if any(k is None for k in keys) or any(x is None for x in lists):
31763176
return
3177+
tuple_key = len(s.keys) > 1
31773178
fn = {"i64": "tpa_i64_keysort", "f64": "tpa_f64_keysort", "int": "tpa_int_keysort", "str": "tpa_str_keysort"}
3178-
if keys[1] not in fn or self.types.get(s.keys) is Type.STR_OPT_LIST:
3179-
self.bad("aot/ir-node", "ListSortKeyed", f"the keys `{s.keys}`: only int, float or str keys are sorted by")
3180-
return
3179+
col = {"i64": "tpa_i64_col_cmp", "int": "tpa_int_col_cmp", "str": "tpa_str_col_cmp"}
3180+
for k, (_, kind) in zip(s.keys, keys): # type: ignore[misc]
3181+
if kind not in (col if tuple_key else fn) or self.types.get(k) is Type.STR_OPT_LIST:
3182+
self.bad("aot/ir-node", "ListSortKeyed", f"the keys `{k}`: only int, float or str keys, or tuples of "
3183+
"int and str, are sorted by")
3184+
return
31813185
first = lists[0][0] # type: ignore[index]
31823186
self.emit("{")
31833187
self.emit(" tpa_perm tpa_pm;")
31843188
self.emit(f" size_t tpa_esz = sizeof {first}->d[0];")
31853189
for c, _ in lists[1:]: # type: ignore[misc]
31863190
self.emit(f" if (sizeof {c}->d[0] > tpa_esz) tpa_esz = sizeof {c}->d[0];")
31873191
self.emit(f" if (tpa_sort_len_check({c}->len, {first}->len)) {self.fail()}")
3188-
self.emit(f" if ({fn[keys[1]]}(&tpa_pm, {keys[0]}, {rev}, {first}->len, tpa_esz)) {self.fail()}")
3192+
if tuple_key:
3193+
cols = ", ".join(f"{{{col[kind]}, (const void *){c}}}" for c, kind in keys) # type: ignore[misc]
3194+
self.emit(f" const tpa_kcol tpa_kc[{len(keys)}] = {{{cols}}};")
3195+
for c, _ in keys: # type: ignore[misc]
3196+
self.emit(f" if (tpa_sort_len_check({c}->len, {first}->len)) {self.fail()}")
3197+
self.emit(f" if (tpa_tuple_keysort(&tpa_pm, tpa_kc, {len(keys)}, {rev}, {first}->len, tpa_esz)) "
3198+
f"{self.fail()}")
3199+
else:
3200+
self.emit(f" if ({fn[keys[0][1]]}(&tpa_pm, {keys[0][0]}, {rev}, {first}->len, tpa_esz)) " # type: ignore[index]
3201+
f"{self.fail()}")
31893202
for c, _ in lists: # type: ignore[misc]
31903203
self.emit(f" tpa_perm_apply(&tpa_pm, (void *){c}->d, sizeof {c}->d[0]);")
31913204
self.emit(" tpa_perm_free(&tpa_pm);")

‎python-multiplatform-ksp/src/main/python/typedpython/comprehensions.py‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -543,18 +543,28 @@ def _zero_tuple(spelled: str) -> ast.expr | None:
543543

544544

545545
def _key_type(spelled: str | None, call: ast.Call, line: int) -> str:
546-
"""The type of a key's value (int, float or str; of min() / max() bool too), from its probe."""
546+
"""The type of a key's value (int, float or str; of min() / max() bool too; of a sort a tuple of int and str), from
547+
its probe."""
547548
import re
548549
name = call.func.attr if isinstance(call.func, ast.Attribute) else call.func.id # type: ignore[attr-defined]
549550
if spelled is None:
550551
raise _Problem(line, f"`{ast.unparse(call)}`: no type is known for the value of its key")
551552
parts = {"int" if re.fullmatch(r"(typing\.)?Literal\[-?\d+\]", p.strip()) else rebinding._base(p.strip())
552553
for p in spelled.split("|")}
553554
allowed = (*_KEY_TYPES, "bool") if name in ("min", "max") else _KEY_TYPES
555+
tup = re.fullmatch(r"(?:builtins\.)?tuple\[(.*)\]", spelled.strip())
556+
if tup is not None and "|" not in spelled:
557+
elts = [rebinding._base(e.strip()) for e in tup.group(1).split(",")]
558+
if name in ("min", "max"):
559+
raise _Problem(line, f"`{ast.unparse(call)}`: min() / max() with a tuple key is not in the AOT mode yet")
560+
if not elts or "..." in elts or any(e not in ("int", "str") for e in elts):
561+
raise _Problem(line, f"`{ast.unparse(call)}`: its key gives a {spelled}; a tuple key of an AOT sort holds "
562+
"int and str (a float element is refused: NaN breaks tuple comparison's equality step)")
563+
return f"tuple[{', '.join(elts)}]"
554564
if len(parts) != 1 or next(iter(parts)) not in allowed:
555565
raise _Problem(line, f"`{ast.unparse(call)}`: its key gives a {spelled}; an AOT program compares by an int, "
556-
f"float or str key{' or a bool one' if name in ('min', 'max') else ''} (a tuple key is "
557-
"not in the AOT mode yet)")
566+
f"float or str key{' or a bool one' if name in ('min', 'max') else ''} (a tuple key of "
567+
"int and str is taken by sorted() and list.sort())")
558568
return next(iter(parts))
559569

560570

‎python-multiplatform-ksp/src/main/python/typedpython/frontend.py‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3611,11 +3611,15 @@ def keyed_sort_stmt(self, node: ast.Call) -> list[ir.Stmt]:
36113611
sorted by them (one list, or the element lists of a list of tuples)."""
36123612
line = node.lineno
36133613
keys, rev, *lists = node.args
3614-
assert isinstance(keys, ast.Name) and lists and all(isinstance(a, ast.Name) for a in lists)
3615-
kt = self.list_type(keys.id)
3616-
if kt not in (Type.I64_ARRAY, Type.F64_ARRAY, Type.STR_LIST):
3617-
raise Skip(line, f"the keys of a sort are {TYPE_NAME.get(kt, kt.value)}; an AOT program sorts by int, float "
3618-
"or str keys")
3614+
kn = keys.elts if isinstance(keys, ast.Tuple) else [keys]
3615+
assert kn and all(isinstance(k, ast.Name) for k in kn) and lists and all(isinstance(a, ast.Name) for a in lists)
3616+
allowed = (Type.I64_ARRAY, Type.STR_LIST) if len(kn) > 1 or isinstance(keys, ast.Tuple) \
3617+
else (Type.I64_ARRAY, Type.F64_ARRAY, Type.STR_LIST)
3618+
for k in kn:
3619+
kt = self.list_type(k.id) # type: ignore[attr-defined]
3620+
if kt not in allowed:
3621+
raise Skip(line, f"the keys of a sort are {TYPE_NAME.get(kt, kt.value)}; an AOT program sorts by int, "
3622+
"float or str keys, or tuples of int and str")
36193623
reverse = self.value(rev)
36203624
if reverse.type is not Type.BOOL:
36213625
raise Skip(line, f"reverse= is a bool in an AOT program, not {TYPE_NAME.get(reverse.type, reverse.type.value)}")
@@ -3626,7 +3630,7 @@ def keyed_sort_stmt(self, node: ast.Call) -> list[ir.Stmt]:
36263630
self.hoist_ok = False
36273631
for a in names:
36283632
self.list_effect(a)
3629-
return self.take() + [ir.ListSortKeyed(keys.id, reverse, names)]
3633+
return self.take() + [ir.ListSortKeyed(tuple(k.id for k in kn), reverse, names)] # type: ignore[attr-defined]
36303634

36313635
def list_method_stmt(self, node: ast.Call) -> list[ir.Stmt]:
36323636
"""`a.append(v)`, `a.insert(i, v)`, `a.extend(b)`, `a.clear()`, `a.reverse()`, `a.remove(v)` as statements."""

‎python-multiplatform-ksp/src/main/python/typedpython/ir.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -756,13 +756,14 @@ class ListSort(Stmt):
756756
@dataclass(frozen=True)
757757
class ListSortKeyed(Stmt):
758758
"""The keyed sort of tier S2c (comprehensions.py `KEYSORT`): `keys` (a list of int, float or str, one key per item,
759-
computed before) gives the order; CPython's listsort sorts the (key, position) pairs by key only (tp_aot.h
759+
computed before, or the element lists of a list of tuples of int and str, compared element by element as CPython
760+
compares tuples) gives the order; CPython's listsort sorts the (key, position) pairs by key only (tp_aot.h
760761
`tpa_keysort_*`), reversed before and after when `reverse` (BOOL, evaluated first) is true, and every list of
761762
`arrays` (one list, or the element lists of a list of tuples, each as long as `keys`) is permuted by the result:
762763
what list_sort_impl does moving the keys and the items together. A list whose length is no longer the keys'
763764
raises CPython's ValueError("list modified during sort")."""
764765

765-
keys: str
766+
keys: tuple[str, ...]
766767
reverse: Expr
767768
arrays: tuple[str, ...]
768769

‎python-multiplatform-ksp/src/main/python/typedpython/runtime/tp_aot.h‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2173,6 +2173,71 @@ static TPA_UNUSED void tpa_perm_apply(tpa_perm *p, void *d, size_t esz)
21732173
TPA__DEF_KEYSORT(tpa_i64_keysort, int64_t, tpa_i64_list, TPA__LT_KNUM)
21742174
TPA__DEF_KEYSORT(tpa_f64_keysort, double, tpa_f64_list, TPA__LT_KNUM)
21752175

2176+
/* Tier S2c: sorting by a tuple key of int and str elements. The keys are the element lists of the hidden list of
2177+
* tuples, one column per element; CPython's tuple comparison finds the first element that is not equal and compares
2178+
* that one, which for int and str (total orders) is the first column whose comparison is not 0. A float element is
2179+
* refused by the compiler (NaN is not equal to itself). Each pair carries the columns, so the comparison needs no
2180+
* global state (free-threaded safe). `int tpa_tuple_keysort(tpa_perm *p, const tpa_kcol *cols, int ncol, int reverse,
2181+
* int64_t n, size_t esz)`: every column's length is checked by the caller. */
2182+
typedef int (*tpa_kcol_cmp)(const void *list, int64_t i, int64_t j);
2183+
typedef struct { tpa_kcol_cmp cmp; const void *list; } tpa_kcol;
2184+
typedef struct { const tpa_kcol *c; int n; } tpa_kcols;
2185+
typedef struct { int64_t i; const tpa_kcols *c; } tpa__tkpair;
2186+
static inline int tpa__tk_lt(const tpa__tkpair *a, const tpa__tkpair *b)
2187+
{
2188+
int j, r;
2189+
for (j = 0; j < a->c->n; j++) {
2190+
r = a->c->c[j].cmp(a->c->c[j].list, a->i, b->i);
2191+
if (r != 0) {
2192+
return r < 0;
2193+
}
2194+
}
2195+
return 0;
2196+
}
2197+
#define TPA__LT_TK(a, b) tpa__tk_lt(&(a), &(b))
2198+
TPA__DEF_SORT(tpa__tk_s, tpa__tkpair, TPA__LT_TK)
2199+
static TPA_UNUSED int tpa_tuple_keysort(tpa_perm *p, const tpa_kcol *cols, int ncol, int reverse, int64_t n, size_t esz)
2200+
{
2201+
tpa__tkpair *pr;
2202+
tpa_kcols kc;
2203+
int64_t j;
2204+
p->n = 0;
2205+
p->idx = NULL;
2206+
p->tmp = NULL;
2207+
if (tpa_perm__alloc(p, n, esz)) {
2208+
return -1;
2209+
}
2210+
if (n == 0) {
2211+
return 0;
2212+
}
2213+
pr = (tpa__tkpair *)malloc((size_t)n * sizeof(tpa__tkpair));
2214+
if (pr == NULL) {
2215+
tpa_perm_free(p);
2216+
return tpa_raise(TPA_MemoryError, "");
2217+
}
2218+
kc.c = cols;
2219+
kc.n = ncol;
2220+
for (j = 0; j < n; j++) {
2221+
pr[j].i = j;
2222+
pr[j].c = &kc;
2223+
}
2224+
if (tpa__tk_s__listsort(pr, n, reverse)) {
2225+
free(pr);
2226+
tpa_perm_free(p);
2227+
return -1;
2228+
}
2229+
for (j = 0; j < n; j++) {
2230+
p->idx[j] = pr[j].i;
2231+
}
2232+
free(pr);
2233+
return 0;
2234+
}
2235+
static TPA_UNUSED int tpa_i64_col_cmp(const void *l, int64_t i, int64_t j)
2236+
{
2237+
const int64_t a = ((const tpa_i64_list *)l)->d[i], b = ((const tpa_i64_list *)l)->d[j];
2238+
return a < b ? -1 : a > b;
2239+
}
2240+
21762241
/* Tier S2a: searching a list[int] of the RAW kind (a list of float is never searched: NaN's identity, design 4.3.2).
21772242
* list.index(v): the first position, else ValueError("list.index(x): x not in list") (Objects/listobject.c
21782243
* list_index_impl since CPython 3.14, the baseline; the value is not formatted); list.count(v); `v in l`. */

‎python-multiplatform-ksp/src/main/python/typedpython/runtime/tp_aot_int.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2611,6 +2611,10 @@ static TPA_UNUSED int tpa_int_list_sort(tpa_int_list *l, int reverse)
26112611
/* Tier S2c: sorting by big-capable int keys (TPA__DEF_KEYSORT in tp_aot.h) */
26122612
#define TPA__LT_KINT(a, b) (tpa_int_cmp((a).k, (b).k) < 0)
26132613
TPA__DEF_KEYSORT(tpa_int_keysort, tpa_int, tpa_int_list, TPA__LT_KINT)
2614+
static TPA_UNUSED int tpa_int_col_cmp(const void *l, int64_t i, int64_t j)
2615+
{
2616+
return tpa_int_cmp(((const tpa_int_list *)l)->d[i], ((const tpa_int_list *)l)->d[j]);
2617+
}
26142618

26152619
/* list.pop: the element's reference moves to `*out` (which gives up the one it held) */
26162620
static TPA_UNUSED int tpa_int_list_pop(tpa_int_list *l, int has_index, int64_t i, tpa_int *out)

‎python-multiplatform-ksp/src/main/python/typedpython/runtime/tp_aot_str.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1219,6 +1219,10 @@ static TPA_UNUSED int tpa_str_list_sort(tpa_str_list *l, int reverse)
12191219
/* Tier S2c: sorting by str keys (TPA__DEF_KEYSORT in tp_aot.h), in code point order */
12201220
#define TPA__LT_KSTR(a, b) (tpa_str_cmp((a).k, (b).k) < 0)
12211221
TPA__DEF_KEYSORT(tpa_str_keysort, tpa_str *, tpa_str_list, TPA__LT_KSTR)
1222+
static TPA_UNUSED int tpa_str_col_cmp(const void *l, int64_t i, int64_t j)
1223+
{
1224+
return tpa_str_cmp(((const tpa_str_list *)l)->d[i], ((const tpa_str_list *)l)->d[j]);
1225+
}
12221226

12231227
/* A growing list while split builds its result (a private buffer, not a value). */
12241228
typedef struct {

‎python-multiplatform-ksp/src/main/python/typedpython/tuples.py‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1007,11 +1007,15 @@ def list_stmt(self, s: ast.stmt) -> list[ast.stmt] | None:
10071007
for c in self.comps(name)]
10081008
if isinstance(s, ast.Expr) and isinstance(s.value, ast.Call) and isinstance(s.value.func, ast.Name) \
10091009
and s.value.func.id == KEYSORT and len(s.value.args) == 3 and isinstance(s.value.args[2], ast.Name) \
1010-
and s.value.args[2].id in self.lists:
1011-
# tier S2c: the keyed sort of a list of tuples moves every element list by the one order of the keys
1010+
and (s.value.args[2].id in self.lists
1011+
or isinstance(s.value.args[0], ast.Name) and s.value.args[0].id in self.lists):
1012+
# tier S2c: the keyed sort of a list of tuples moves every element list by the one order of the keys;
1013+
# keys that are tuples are their element lists, compared element by element (`KEYSORT((k0, k1), r, ...)`)
10121014
keys, rev, lst = s.value.args
1013-
return [ast.Expr(value=ast.Call(func=_name(KEYSORT), args=[keys, rev, *self.comps(lst.id)], # type: ignore[attr-defined]
1014-
keywords=[]))]
1015+
if isinstance(keys, ast.Name) and keys.id in self.lists:
1016+
keys = ast.Tuple(elts=self.comps(keys.id), ctx=ast.Load())
1017+
arrays = self.comps(lst.id) if lst.id in self.lists else [lst] # type: ignore[attr-defined]
1018+
return [ast.Expr(value=ast.Call(func=_name(KEYSORT), args=[keys, rev, *arrays], keywords=[]))]
10151019
if isinstance(s, ast.Expr) and isinstance(s.value, ast.Call) and isinstance(s.value.func, ast.Attribute) \
10161020
and isinstance(s.value.func.value, ast.Name) and s.value.func.value.id in self.lists:
10171021
call = s.value

‎python-multiplatform-ksp/src/main/python/typedpython/verify.py‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3029,10 +3029,15 @@ def s_ListSort(self, s: ListSort, state: _State):
30293029

30303030
def s_ListSortKeyed(self, s: ListSortKeyed, state: _State):
30313031
reverse = self.expr(s.reverse, state)
3032-
self.slot(reverse, Type.BOOL, f"reverse of the keyed sort of '{s.keys}'")
3033-
kt = self.list_of(s.keys, "keyed sort", state)
3034-
if kt not in (Type.I64_ARRAY, Type.F64_ARRAY, Type.STR_LIST) and kt is not None:
3035-
self.error(TYPE, f"keys '{s.keys}' of a sort ({kt.value}): only int, float or str keys are sorted by")
3032+
self.slot(reverse, Type.BOOL, f"reverse of the keyed sort of '{s.keys[0] if s.keys else ''}'")
3033+
if not s.keys:
3034+
self.error(TYPE, "keyed sort with no keys")
3035+
allowed = (Type.I64_ARRAY, Type.STR_LIST) if len(s.keys) > 1 else (Type.I64_ARRAY, Type.F64_ARRAY, Type.STR_LIST)
3036+
for k in s.keys:
3037+
kt = self.list_of(k, "keyed sort", state)
3038+
if kt not in allowed and kt is not None:
3039+
self.error(TYPE, f"keys '{k}' of a sort ({kt.value}): only int, float or str keys, or tuples of int "
3040+
"and str, are sorted by")
30363041
if not s.arrays:
30373042
self.error(TYPE, f"keyed sort by '{s.keys}' of no list")
30383043
for a in s.arrays:

0 commit comments

Comments
 (0)