| 1 |
"""Tokenizers for three string formatting methods""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from enum import Enum, unique |
| 6 |
from typing import Final |
| 7 |
|
| 8 |
from mypy.checkstrformat import ( |
| 9 |
ConversionSpecifier, |
| 10 |
parse_conversion_specifiers, |
| 11 |
parse_format_value, |
| 12 |
) |
| 13 |
from mypy.errors import Errors |
| 14 |
from mypy.messages import MessageBuilder |
| 15 |
from mypy.nodes import Context, Expression |
| 16 |
from mypy.options import Options |
| 17 |
from mypyc.ir.ops import Integer, Value |
| 18 |
from mypyc.ir.rtypes import ( |
| 19 |
c_pyssize_t_rprimitive, |
| 20 |
is_bytes_rprimitive, |
| 21 |
is_int_rprimitive, |
| 22 |
is_short_int_rprimitive, |
| 23 |
is_str_rprimitive, |
| 24 |
) |
| 25 |
from mypyc.irbuild.builder import IRBuilder |
| 26 |
from mypyc.irbuild.constant_fold import constant_fold_expr |
| 27 |
from mypyc.primitives.bytes_ops import bytes_build_op |
| 28 |
from mypyc.primitives.int_ops import int_to_ascii_op, int_to_str_op |
| 29 |
from mypyc.primitives.str_ops import str_build_op, str_op |
| 30 |
|
| 31 |
|
| 32 |
@unique |
| 33 |
class FormatOp(Enum): |
| 34 |
"""FormatOp represents conversion operations of string formatting during |
| 35 |
compile time. |
| 36 |
|
| 37 |
Compare to ConversionSpecifier, FormatOp has fewer attributes. |
| 38 |
For example, to mark a conversion from any object to string, |
| 39 |
ConversionSpecifier may have several representations, like '%s', '{}' |
| 40 |
or '{:{}}'. However, there would only exist one corresponding FormatOp. |
| 41 |
""" |
| 42 |
|
| 43 |
STR = "s" |
| 44 |
INT = "d" |
| 45 |
BYTES = "b" |
| 46 |
|
| 47 |
|
| 48 |
def generate_format_ops(specifiers: list[ConversionSpecifier]) -> list[FormatOp] | None: |
| 49 |
"""Convert ConversionSpecifier to FormatOp. |
| 50 |
|
| 51 |
Different ConversionSpecifiers may share a same FormatOp. |
| 52 |
""" |
| 53 |
format_ops = [] |
| 54 |
for spec in specifiers: |
| 55 |
# TODO: Match specifiers instead of using whole_seq |
| 56 |
if spec.whole_seq == "%s" or spec.whole_seq == "{:{}}": |
| 57 |
format_op = FormatOp.STR |
| 58 |
elif spec.whole_seq == "%d": |
| 59 |
format_op = FormatOp.INT |
| 60 |
elif spec.whole_seq == "%b": |
| 61 |
format_op = FormatOp.BYTES |
| 62 |
elif spec.whole_seq: |
| 63 |
return None |
| 64 |
else: |
| 65 |
format_op = FormatOp.STR |
| 66 |
format_ops.append(format_op) |
| 67 |
return format_ops |
| 68 |
|
| 69 |
|
| 70 |
def tokenizer_printf_style(format_str: str) -> tuple[list[str], list[FormatOp]] | None: |
| 71 |
"""Tokenize a printf-style format string using regex. |
| 72 |
|
| 73 |
Return: |
| 74 |
A list of string literals and a list of FormatOps. |
| 75 |
""" |
| 76 |
literals: list[str] = [] |
| 77 |
specifiers: list[ConversionSpecifier] = parse_conversion_specifiers(format_str) |
| 78 |
format_ops = generate_format_ops(specifiers) |
| 79 |
if format_ops is None: |
| 80 |
return None |
| 81 |
|
| 82 |
last_end = 0 |
| 83 |
for spec in specifiers: |
| 84 |
cur_start = spec.start_pos |
| 85 |
literals.append(format_str[last_end:cur_start]) |
| 86 |
last_end = cur_start + len(spec.whole_seq) |
| 87 |
literals.append(format_str[last_end:]) |
| 88 |
|
| 89 |
return literals, format_ops |
| 90 |
|
| 91 |
|
| 92 |
# The empty Context as an argument for parse_format_value(). |
| 93 |
# It wouldn't be used since the code has passed the type-checking. |
| 94 |
EMPTY_CONTEXT: Final = Context() |
| 95 |
|
| 96 |
|
| 97 |
def tokenizer_format_call(format_str: str) -> tuple[list[str], list[FormatOp]] | None: |
| 98 |
"""Tokenize a str.format() format string. |
| 99 |
|
| 100 |
The core function parse_format_value() is shared with mypy. |
| 101 |
With these specifiers, we then parse the literal substrings |
| 102 |
of the original format string and convert `ConversionSpecifier` |
| 103 |
to `FormatOp`. |
| 104 |
|
| 105 |
Return: |
| 106 |
A list of string literals and a list of FormatOps. The literals |
| 107 |
are interleaved with FormatOps and the length of returned literals |
| 108 |
should be exactly one more than FormatOps. |
| 109 |
Return None if it cannot parse the string. |
| 110 |
""" |
| 111 |
# Creates an empty MessageBuilder here. |
| 112 |
# It wouldn't be used since the code has passed the type-checking. |
| 113 |
specifiers = parse_format_value( |
| 114 |
format_str, EMPTY_CONTEXT, MessageBuilder(Errors(Options()), {}) |
| 115 |
) |
| 116 |
if specifiers is None: |
| 117 |
return None |
| 118 |
format_ops = generate_format_ops(specifiers) |
| 119 |
if format_ops is None: |
| 120 |
return None |
| 121 |
|
| 122 |
literals: list[str] = [] |
| 123 |
last_end = 0 |
| 124 |
for spec in specifiers: |
| 125 |
# Skip { and } |
| 126 |
literals.append(format_str[last_end : spec.start_pos - 1]) |
| 127 |
last_end = spec.start_pos + len(spec.whole_seq) + 1 |
| 128 |
literals.append(format_str[last_end:]) |
| 129 |
# Deal with escaped {{ |
| 130 |
literals = [x.replace("{{", "{").replace("}}", "}") for x in literals] |
| 131 |
|
| 132 |
return literals, format_ops |
| 133 |
|
| 134 |
|
| 135 |
def convert_format_expr_to_str( |
| 136 |
builder: IRBuilder, format_ops: list[FormatOp], exprs: list[Expression], line: int |
| 137 |
) -> list[Value] | None: |
| 138 |
"""Convert expressions into string literal objects with the guidance |
| 139 |
of FormatOps. Return None when fails.""" |
| 140 |
if len(format_ops) != len(exprs): |
| 141 |
return None |
| 142 |
|
| 143 |
converted = [] |
| 144 |
for x, format_op in zip(exprs, format_ops): |
| 145 |
node_type = builder.node_type(x) |
| 146 |
if format_op == FormatOp.STR: |
| 147 |
if isinstance(folded := constant_fold_expr(builder, x), str): |
| 148 |
var_str = builder.load_literal_value(folded) |
| 149 |
elif is_str_rprimitive(node_type): |
| 150 |
var_str = builder.accept(x) |
| 151 |
elif is_int_rprimitive(node_type) or is_short_int_rprimitive(node_type): |
| 152 |
var_str = builder.primitive_op(int_to_str_op, [builder.accept(x)], line) |
| 153 |
else: |
| 154 |
var_str = builder.primitive_op(str_op, [builder.accept(x)], line) |
| 155 |
elif format_op == FormatOp.INT: |
| 156 |
if isinstance(folded := constant_fold_expr(builder, x), int): |
| 157 |
var_str = builder.load_literal_value(str(folded)) |
| 158 |
elif is_int_rprimitive(node_type) or is_short_int_rprimitive(node_type): |
| 159 |
var_str = builder.primitive_op(int_to_str_op, [builder.accept(x)], line) |
| 160 |
else: |
| 161 |
return None |
| 162 |
else: |
| 163 |
return None |
| 164 |
converted.append(var_str) |
| 165 |
return converted |
| 166 |
|
| 167 |
|
| 168 |
def join_formatted_strings( |
| 169 |
builder: IRBuilder, literals: list[str] | None, substitutions: list[Value], line: int |
| 170 |
) -> Value: |
| 171 |
"""Merge the list of literals and the list of substitutions |
| 172 |
alternatively using 'str_build_op'. |
| 173 |
|
| 174 |
`substitutions` is the result value of formatting conversions. |
| 175 |
|
| 176 |
If the `literals` is set to None, we simply join the substitutions; |
| 177 |
Otherwise, the `literals` is the literal substrings of the original |
| 178 |
format string and its length should be exactly one more than |
| 179 |
substitutions. |
| 180 |
|
| 181 |
For example: |
| 182 |
(1) 'This is a %s and the value is %d' |
| 183 |
-> literals: ['This is a ', ' and the value is', ''] |
| 184 |
(2) '{} and the value is {}' |
| 185 |
-> literals: ['', ' and the value is', ''] |
| 186 |
""" |
| 187 |
# The first parameter for str_build_op is the total size of |
| 188 |
# the following PyObject* |
| 189 |
result_list: list[Value] = [Integer(0, c_pyssize_t_rprimitive)] |
| 190 |
|
| 191 |
if literals is not None: |
| 192 |
for a, b in zip(literals, substitutions): |
| 193 |
if a: |
| 194 |
result_list.append(builder.load_str(a)) |
| 195 |
result_list.append(b) |
| 196 |
if literals[-1]: |
| 197 |
result_list.append(builder.load_str(literals[-1])) |
| 198 |
else: |
| 199 |
result_list.extend(substitutions) |
| 200 |
|
| 201 |
# Special case for empty string and literal string |
| 202 |
if len(result_list) == 1: |
| 203 |
return builder.load_str("") |
| 204 |
if not substitutions and len(result_list) == 2: |
| 205 |
return result_list[1] |
| 206 |
|
| 207 |
result_list[0] = Integer(len(result_list) - 1, c_pyssize_t_rprimitive) |
| 208 |
return builder.call_c(str_build_op, result_list, line) |
| 209 |
|
| 210 |
|
| 211 |
def convert_format_expr_to_bytes( |
| 212 |
builder: IRBuilder, format_ops: list[FormatOp], exprs: list[Expression], line: int |
| 213 |
) -> list[Value] | None: |
| 214 |
"""Convert expressions into bytes literal objects with the guidance |
| 215 |
of FormatOps. Return None when fails.""" |
| 216 |
if len(format_ops) != len(exprs): |
| 217 |
return None |
| 218 |
|
| 219 |
converted = [] |
| 220 |
for x, format_op in zip(exprs, format_ops): |
| 221 |
node_type = builder.node_type(x) |
| 222 |
# conversion type 's' is an alias of 'b' in bytes formatting |
| 223 |
if format_op == FormatOp.BYTES or format_op == FormatOp.STR: |
| 224 |
if is_bytes_rprimitive(node_type): |
| 225 |
var_bytes = builder.accept(x) |
| 226 |
else: |
| 227 |
return None |
| 228 |
elif format_op == FormatOp.INT: |
| 229 |
if isinstance(folded := constant_fold_expr(builder, x), int): |
| 230 |
var_bytes = builder.load_literal_value(str(folded).encode("ascii")) |
| 231 |
elif is_int_rprimitive(node_type) or is_short_int_rprimitive(node_type): |
| 232 |
var_bytes = builder.call_c(int_to_ascii_op, [builder.accept(x)], line) |
| 233 |
else: |
| 234 |
return None |
| 235 |
converted.append(var_bytes) |
| 236 |
return converted |
| 237 |
|
| 238 |
|
| 239 |
def join_formatted_bytes( |
| 240 |
builder: IRBuilder, literals: list[str], substitutions: list[Value], line: int |
| 241 |
) -> Value: |
| 242 |
"""Merge the list of literals and the list of substitutions |
| 243 |
alternatively using 'bytes_build_op'.""" |
| 244 |
result_list: list[Value] = [Integer(0, c_pyssize_t_rprimitive)] |
| 245 |
|
| 246 |
for a, b in zip(literals, substitutions): |
| 247 |
if a: |
| 248 |
result_list.append(builder.load_bytes_from_str_literal(a)) |
| 249 |
result_list.append(b) |
| 250 |
if literals[-1]: |
| 251 |
result_list.append(builder.load_bytes_from_str_literal(literals[-1])) |
| 252 |
|
| 253 |
# Special case for empty bytes and literal |
| 254 |
if len(result_list) == 1: |
| 255 |
return builder.load_bytes_from_str_literal("") |
| 256 |
if not substitutions and len(result_list) == 2: |
| 257 |
return result_list[1] |
| 258 |
|
| 259 |
result_list[0] = Integer(len(result_list) - 1, c_pyssize_t_rprimitive) |
| 260 |
return builder.call_c(bytes_build_op, result_list, line) |