GeezerVison is showing github.com — [mypyc] Add native char type + codepoint fast paths for str ops · VaggelisD/sqlglot-mypy@b3fbc77
File treeExpand file treeCollapse file tree Open diff view settings typeshed/stubs/mypy-extensions
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: mypy/meet.py +3Lines changed: 3 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 17 | 17 | ) | 18 | 18 | from mypy.typeops import is_recursive_pair, make_simplified_union, tuple_fallback | 19 | 19 | from mypy.types import ( | | 20 | + MYPYC_NATIVE_CHAR_NAMES, | 20 | 21 | MYPYC_NATIVE_INT_NAMES, | 21 | 22 | TUPLE_LIKE_INSTANCE_NAMES, | 22 | 23 | AnyType, | @@ -592,6 +593,8 @@ def _type_object_overlap(left: Type, right: Type) -> bool: | 592 | 593 |
| 593 | 594 | if right.type.fullname == "builtins.int" and left.type.fullname in MYPYC_NATIVE_INT_NAMES: | 594 | 595 | return True | | 596 | + if right.type.fullname == "builtins.str" and left.type.fullname in MYPYC_NATIVE_CHAR_NAMES: | | 597 | + return True | 595 | 598 |
| 596 | 599 | # Two unrelated types cannot be partially overlapping: they're disjoint. | 597 | 600 | if left.type.has_base(right.type.fullname): | |
Collapse file Copy file name to clipboardExpand all lines: mypy/semanal_classprop.py +7-1Lines changed: 7 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
| 22 | 22 | Var, | 23 | 23 | ) | 24 | 24 | from mypy.options import Options | 25 | | -from mypy.types import MYPYC_NATIVE_INT_NAMES, Instance, ProperType | | 25 | +from mypy.types import MYPYC_NATIVE_CHAR_NAMES, MYPYC_NATIVE_INT_NAMES, Instance, ProperType | 26 | 26 |
| 27 | 27 | # Hard coded type promotions (shared between all Python versions). | 28 | 28 | # These add extra ad-hoc edges to the subtyping relation. For example, | @@ -184,5 +184,11 @@ def add_type_promotion( | 184 | 184 | assert isinstance(int_sym.node, TypeInfo) | 185 | 185 | int_sym.node._promote.append(Instance(defn.info, [])) | 186 | 186 | defn.info.alt_promote = Instance(int_sym.node, []) | | 187 | + # Same pattern for str <-> char (mypyc native char type). | | 188 | + if defn.fullname in MYPYC_NATIVE_CHAR_NAMES: | | 189 | + str_sym = builtin_names["str"] | | 190 | + assert isinstance(str_sym.node, TypeInfo) | | 191 | + str_sym.node._promote.append(Instance(defn.info, [])) | | 192 | + defn.info.alt_promote = Instance(str_sym.node, []) | 187 | 193 | if promote_targets: | 188 | 194 | defn.info._promote.extend(promote_targets) |
Collapse file Copy file name to clipboardExpand all lines: mypy/subtypes.py +5Lines changed: 5 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 36 | 36 | from mypy.options import Options | 37 | 37 | from mypy.state import state | 38 | 38 | from mypy.types import ( | | 39 | + MYPYC_NATIVE_CHAR_NAMES, | 39 | 40 | MYPYC_NATIVE_INT_NAMES, | 40 | 41 | TUPLE_LIKE_INSTANCE_NAMES, | 41 | 42 | TYPED_NAMEDTUPLE_NAMES, | @@ -2166,6 +2167,10 @@ def covers_at_runtime(item: Type, supertype: Type) -> bool: | 2166 | 2167 | # "int" covers all native int types | 2167 | 2168 | if item.type.fullname in MYPYC_NATIVE_INT_NAMES: | 2168 | 2169 | return True | | 2170 | + elif isinstance(item, Instance) and supertype.type.fullname == "builtins.str": | | 2171 | + # "str" covers the native char type | | 2172 | + if item.type.fullname in MYPYC_NATIVE_CHAR_NAMES: | | 2173 | + return True | 2169 | 2174 | # TODO: Add more special cases. | 2170 | 2175 | return False | 2171 | 2176 |
| |
Collapse file Copy file name to clipboardExpand all lines: mypy/types.py +4Lines changed: 4 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 190 | 190 | "mypy_extensions.u8", | 191 | 191 | ) | 192 | 192 |
| | 193 | +# Mypyc native char type (compatible with builtins.str, bidirectionally; | | 194 | +# stored unboxed as an int32 codepoint with -1 as the empty sentinel). | | 195 | +MYPYC_NATIVE_CHAR_NAMES: Final = ("mypy_extensions.char",) | | 196 | + | 193 | 197 | DATACLASS_TRANSFORM_NAMES: Final = ( | 194 | 198 | "typing.dataclass_transform", | 195 | 199 | "typing_extensions.dataclass_transform", | |
Collapse file Copy file name to clipboardExpand all lines: mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi +24Lines changed: 24 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -220,3 +220,27 @@ class u8: | 220 | 220 | def __gt__(self, x: u8) -> bool: ... | 221 | 221 | def __index__(self) -> int: ... | 222 | 222 | def __eq__(self, x: object) -> bool: ... | | 223 | + | | 224 | +# char represents at most one Unicode codepoint. At the type-check level it's | | 225 | +# bidirectionally compatible with str via the mypyc native-string promotion | | 226 | +# mechanism. Under mypyc a char is stored unboxed as an int32 codepoint | | 227 | +# (with -1 for the empty sentinel). | | 228 | +class char: | | 229 | + def __new__(cls, __x: str = ...) -> char: ... | | 230 | + def __eq__(self, x: object) -> bool: ... | | 231 | + def __ne__(self, x: object) -> bool: ... | | 232 | + def __hash__(self) -> int: ... | | 233 | + # Mixed char/str concat. Result is str. | | 234 | + def __add__(self, x: str) -> str: ... | | 235 | + def __radd__(self, x: str) -> str: ... | | 236 | + def isspace(self) -> bool: ... | | 237 | + def isdigit(self) -> bool: ... | | 238 | + def isalnum(self) -> bool: ... | | 239 | + def isalpha(self) -> bool: ... | | 240 | + def isidentifier(self) -> bool: ... | | 241 | + # Case conversion. Returns the original codepoint if the Unicode | | 242 | + # result is multi-char (e.g. ß.upper() = "SS") since char holds one | | 243 | + # codepoint. | | 244 | + def upper(self) -> char: ... | | 245 | + def lower(self) -> char: ... | | 246 | + def strip(self, __chars: str | None = ...) -> str: ... |
Collapse file Copy file name to clipboardExpand all lines: mypyc/codegen/emit.py +10Lines changed: 10 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 44 | 44 | is_bool_or_bit_rprimitive, | 45 | 45 | is_bytearray_rprimitive, | 46 | 46 | is_bytes_rprimitive, | | 47 | + is_char_rprimitive, | 47 | 48 | is_dict_rprimitive, | 48 | 49 | is_fixed_width_rtype, | 49 | 50 | is_float_rprimitive, | @@ -1045,6 +1046,13 @@ def emit_unbox( | 1045 | 1046 | self.emit_line(f"{dest} = CPyLong_AsInt16({src});") | 1046 | 1047 | if not isinstance(error, AssignHandler): | 1047 | 1048 | self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure) | | 1049 | + elif is_char_rprimitive(typ): | | 1050 | + assert not optional | | 1051 | + if declare_dest: | | 1052 | + self.emit_line(f"int32_t {dest};") | | 1053 | + self.emit_line(f"{dest} = CPyChar_FromObject({src});") | | 1054 | + if not isinstance(error, AssignHandler): | | 1055 | + self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure) | 1048 | 1056 | elif is_uint8_rprimitive(typ): | 1049 | 1057 | # Whether we are borrowing or not makes no difference. | 1050 | 1058 | assert not optional # Not supported for overlapping error values | @@ -1192,6 +1200,8 @@ def emit_box( | 1192 | 1200 | self.emit_inc_ref(dest, object_rprimitive) | 1193 | 1201 | elif is_int32_rprimitive(typ) or is_int16_rprimitive(typ) or is_uint8_rprimitive(typ): | 1194 | 1202 | self.emit_line(f"{declaration}{dest} = PyLong_FromLong({src});") | | 1203 | + elif is_char_rprimitive(typ): | | 1204 | + self.emit_line(f"{declaration}{dest} = CPyChar_ToStr({src});") | 1195 | 1205 | elif is_int64_rprimitive(typ): | 1196 | 1206 | self.emit_line(f"{declaration}{dest} = PyLong_FromLongLong({src});") | 1197 | 1207 | elif is_float_rprimitive(typ): | |
Collapse file Copy file name to clipboardExpand all lines: mypyc/codegen/emitmodule.py +5-1Lines changed: 5 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
| 66 | 66 | from mypyc.irbuild.prepare import load_type_map | 67 | 67 | from mypyc.namegen import NameGenerator, exported_name | 68 | 68 | from mypyc.options import CompilerOptions | | 69 | +from mypyc.transform.char_str_index_fold import do_char_str_index_fold | 69 | 70 | from mypyc.transform.copy_propagation import do_copy_propagation | 70 | 71 | from mypyc.transform.exceptions import insert_exception_handling | 71 | 72 | from mypyc.transform.flag_elimination import do_flag_elimination | @@ -265,11 +266,14 @@ def compile_scc_to_ir( | 265 | 266 |
| 266 | 267 | # Switch to lower abstraction level IR. | 267 | 268 | lower_ir(fn, compiler_options) | | 269 | + # Run char_str_index_fold before dependency collection so the new | | 270 | + # str_extra_ops.h primitives it introduces are picked up. | | 271 | + do_char_str_index_fold(fn, compiler_options) | 268 | 272 | # Calculate implicit module dependencies (needed for librt) | 269 | 273 | deps = find_implicit_op_dependencies(fn) | 270 | 274 | if deps is not None: | 271 | 275 | module.dependencies.update(deps) | 272 | | - # Perform optimizations. | | 276 | + # Remaining optimizations. | 273 | 277 | do_copy_propagation(fn, compiler_options) | 274 | 278 | do_flag_elimination(fn, compiler_options) | 275 | 279 |
| |
Collapse file Copy file name to clipboardExpand all lines: mypyc/ir/rtypes.py +19Lines changed: 19 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -394,6 +394,20 @@ def __hash__(self) -> int: | 394 | 394 | error_overlap=True, | 395 | 395 | ) | 396 | 396 |
| | 397 | +# char: single Unicode codepoint stored as int32; -1 empty sentinel, -113 | | 398 | +# error sentinel. Distinct from int32_rprimitive so specializers can route | | 399 | +# char-typed operations through codepoint primitives. | | 400 | +char_rprimitive: Final = RPrimitive( | | 401 | + "char", | | 402 | + is_unboxed=True, | | 403 | + is_refcounted=False, | | 404 | + is_native_int=True, | | 405 | + is_signed=True, | | 406 | + ctype="int32_t", | | 407 | + size=4, | | 408 | + error_overlap=False, | | 409 | +) | | 410 | + | 397 | 411 | # The following unsigned native int types (u16, u32, u64) are not | 398 | 412 | # exposed to the user. They are for internal use within mypyc only. | 399 | 413 |
| @@ -592,13 +606,18 @@ def is_fixed_width_rtype(rtype: RType) -> TypeGuard[RPrimitive]: | 592 | 606 | or is_int32_rprimitive(rtype) | 593 | 607 | or is_int16_rprimitive(rtype) | 594 | 608 | or is_uint8_rprimitive(rtype) | | 609 | + or is_char_rprimitive(rtype) | 595 | 610 | ) | 596 | 611 |
| 597 | 612 |
| 598 | 613 | def is_uint8_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]: | 599 | 614 | return rtype is uint8_rprimitive | 600 | 615 |
| 601 | 616 |
| | 617 | +def is_char_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]: | | 618 | + return rtype is char_rprimitive | | 619 | + | | 620 | + | 602 | 621 | def is_uint32_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]: | 603 | 622 | return rtype is uint32_rprimitive | 604 | 623 |
| |
Collapse file Copy file name to clipboardExpand all lines: mypyc/irbuild/expression.py +76Lines changed: 76 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 79 | 79 | from mypyc.ir.rtypes import ( | 80 | 80 | RInstance, | 81 | 81 | RTuple, | | 82 | + RType, | 82 | 83 | RVec, | 83 | 84 | bool_rprimitive, | | 85 | + char_rprimitive, | 84 | 86 | int_rprimitive, | 85 | 87 | is_any_int, | | 88 | + is_char_rprimitive, | 86 | 89 | is_fixed_width_rtype, | 87 | 90 | is_int64_rprimitive, | 88 | 91 | is_int_rprimitive, | 89 | 92 | is_list_rprimitive, | 90 | 93 | is_none_rprimitive, | 91 | 94 | is_object_rprimitive, | | 95 | + is_str_rprimitive, | | 96 | + is_tagged, | 92 | 97 | object_rprimitive, | 93 | 98 | set_rprimitive, | | 99 | + short_int_rprimitive, | 94 | 100 | ) | 95 | 101 | from mypyc.irbuild.ast_helpers import is_borrow_friendly_expr, process_conditional | 96 | 102 | from mypyc.irbuild.builder import IRBuilder, int_borrow_friendly_op | | 115 | 121 | apply_method_specialization, | 116 | 122 | translate_object_new, | 117 | 123 | translate_object_setattr, | | 124 | + try_emit_str_index_as_int, | 118 | 125 | ) | 119 | 126 | from mypyc.irbuild.vec import ( | 120 | 127 | vec_append, | @@ -843,6 +850,66 @@ def precompute_set_literal(builder: IRBuilder, s: SetExpr) -> Value | None: | 843 | 850 | return None | 844 | 851 |
| 845 | 852 |
| | 853 | +def _codepoint_kind(builder: IRBuilder, expr: Expression, expr_type: RType) -> str | None: | | 854 | + """Classify expr as a codepoint candidate without emitting IR. | | 855 | +
| | 856 | + Returns "char", "index" (for ``s[i]`` with int-like index), or None. | | 857 | + """ | | 858 | + if is_char_rprimitive(expr_type): | | 859 | + return "char" | | 860 | + if isinstance(expr, IndexExpr) and is_str_rprimitive(builder.node_type(expr.base)): | | 861 | + idx_type = builder.node_type(expr.index) | | 862 | + if is_tagged(idx_type) or is_fixed_width_rtype(idx_type): | | 863 | + return "index" | | 864 | + return None | | 865 | + | | 866 | + | | 867 | +def _emit_codepoint_value( | | 868 | + builder: IRBuilder, expr: Expression, kind: str | | 869 | +) -> tuple[Value, RType]: | | 870 | + """Emit the codepoint read. ``kind`` must come from _codepoint_kind.""" | | 871 | + if kind == "char": | | 872 | + return builder.accept(expr), char_rprimitive | | 873 | + assert isinstance(expr, IndexExpr) | | 874 | + val = try_emit_str_index_as_int(builder, expr) | | 875 | + assert val is not None # _codepoint_kind guarantees this | | 876 | + return val, short_int_rprimitive | | 877 | + | | 878 | + | | 879 | +def try_specialize_codepoint_compare( | | 880 | + builder: IRBuilder, op: str, lhs: Expression, rhs: Expression, line: int | | 881 | +) -> Value | None: | | 882 | + """Rewrite ``x == y`` / ``x != y`` to an int compare of codepoints when at | | 883 | + least one side is a codepoint (``char`` value or ``s[i]`` on a str) and the | | 884 | + other is either another codepoint or a 0/1-char str literal. Avoids the | | 885 | + 1-char PyObject alloc + PyUnicode_Compare. | | 886 | + """ | | 887 | + if op not in ("==", "!="): | | 888 | + return None | | 889 | + lhs_kind = _codepoint_kind(builder, lhs, builder.node_type(lhs)) | | 890 | + rhs_kind = _codepoint_kind(builder, rhs, builder.node_type(rhs)) | | 891 | + if lhs_kind is None and rhs_kind is None: | | 892 | + return None | | 893 | + # Codepoint on both sides: direct int compare. | | 894 | + if lhs_kind is not None and rhs_kind is not None: | | 895 | + l_val, _ = _emit_codepoint_value(builder, lhs, lhs_kind) | | 896 | + r_val, _ = _emit_codepoint_value(builder, rhs, rhs_kind) | | 897 | + return builder.binary_op(l_val, r_val, op, line) | | 898 | + # One side codepoint, other side must fold to a 0/1-char str literal. | | 899 | + if lhs_kind is not None: | | 900 | + cp_expr, cp_kind, lit_expr = lhs, lhs_kind, rhs | | 901 | + else: | | 902 | + assert rhs_kind is not None | | 903 | + cp_expr, cp_kind, lit_expr = rhs, rhs_kind, lhs | | 904 | + folded = constant_fold_expr(builder, lit_expr) | | 905 | + if not isinstance(folded, str) or len(folded) > 1: | | 906 | + return None # No IR emitted yet — safe to bail. | | 907 | + val, rtype = _emit_codepoint_value(builder, cp_expr, cp_kind) | | 908 | + # Empty string encodes as -1 (char empty sentinel). | | 909 | + codepoint = -1 if len(folded) == 0 else ord(folded) | | 910 | + return builder.binary_op(val, Integer(codepoint, rtype, line), op, line) | | 911 | + | | 912 | + | 846 | 913 | def transform_comparison_expr(builder: IRBuilder, e: ComparisonExpr) -> Value: | 847 | 914 | # x in (...)/[...] | 848 | 915 | # x not in (...)/[...] | @@ -853,6 +920,15 @@ def transform_comparison_expr(builder: IRBuilder, e: ComparisonExpr) -> Value: | 853 | 920 | return result | 854 | 921 |
| 855 | 922 | if len(e.operators) == 1: | | 923 | + # Codepoint fast path: char/char, char/s[i], or codepoint/1-char-literal | | 924 | + # -> int compare instead of PyUnicode_Compare. | | 925 | + if first_op in ("==", "!="): | | 926 | + result = try_specialize_codepoint_compare( | | 927 | + builder, first_op, e.operands[0], e.operands[1], e.line | | 928 | + ) | | 929 | + if result is not None: | | 930 | + return result | | 931 | + | 856 | 932 | # Special some common simple cases | 857 | 933 | if first_op in ("is", "is not"): | 858 | 934 | right_expr = e.operands[1] | |
Collapse file Copy file name to clipboardExpand all lines: mypyc/irbuild/ll_builder.py +9-1Lines changed: 9 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
| 104 | 104 | is_bool_or_bit_rprimitive, | 105 | 105 | is_bytes_rprimitive, | 106 | 106 | is_c_py_ssize_t_rprimitive, | | 107 | + is_char_rprimitive, | 107 | 108 | is_dict_rprimitive, | 108 | 109 | is_fixed_width_rtype, | 109 | 110 | is_float_rprimitive, | @@ -685,6 +686,7 @@ def coerce_short_int_to_fixed_width(self, src: Value, target_type: RType, line: | 685 | 686 | def coerce_fixed_width_to_int(self, src: Value, line: int) -> Value: | 686 | 687 | if ( | 687 | 688 | (is_int32_rprimitive(src.type) and PLATFORM_SIZE == 8) | | 689 | + or (is_char_rprimitive(src.type) and PLATFORM_SIZE == 8) | 688 | 690 | or is_int16_rprimitive(src.type) | 689 | 691 | or is_uint8_rprimitive(src.type) | 690 | 692 | ): | @@ -717,7 +719,7 @@ def coerce_fixed_width_to_int(self, src: Value, line: int) -> Value: | 717 | 719 | self.activate_block(slow) | 718 | 720 | if is_int64_rprimitive(src_type): | 719 | 721 | conv_op = int64_to_int_op | 720 | | - elif is_int32_rprimitive(src_type): | | 722 | + elif is_int32_rprimitive(src_type) or is_char_rprimitive(src_type): | 721 | 723 | assert PLATFORM_SIZE == 4 | 722 | 724 | conv_op = ssize_t_to_int_op | 723 | 725 | else: | @@ -2126,6 +2128,12 @@ def bool_value(self, value: Value) -> Value: | 2126 | 2128 | elif is_runtime_subtype(value.type, int_rprimitive): | 2127 | 2129 | zero = Integer(0, short_int_rprimitive) | 2128 | 2130 | result = self.comparison_op(value, zero, ComparisonOp.NEQ, value.line) | | 2131 | + elif is_char_rprimitive(value.type): | | 2132 | + # char is falsy only for the empty sentinel (-1). A codepoint of | | 2133 | + # 0 (NUL) is a valid non-empty char and must be truthy, matching | | 2134 | + # str bool semantics where ``"\0"`` is truthy. | | 2135 | + empty = Integer(-1, value.type) | | 2136 | + result = self.add(ComparisonOp(value, empty, ComparisonOp.NEQ)) | 2129 | 2137 | elif is_fixed_width_rtype(value.type): | 2130 | 2138 | zero = Integer(0, value.type) | 2131 | 2139 | result = self.add(ComparisonOp(value, zero, ComparisonOp.NEQ)) | |
|