Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion mypyc/irbuild/expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -1417,7 +1417,7 @@ def translate_printf_style_formatting(
return join_formatted_bytes(builder, literals, substitutions, format_expr.line)
else:
substitutions = convert_format_expr_to_str(
builder, format_ops, exprs, format_expr.line
builder, format_ops, exprs, format_expr.line, use_format=False
)
if substitutions is not None:
return join_formatted_strings(builder, literals, substitutions, format_expr.line)
Expand Down
41 changes: 35 additions & 6 deletions mypyc/irbuild/format_str_tokenizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,18 @@
from mypy.options import Options
from mypyc.ir.ops import Integer, Value
from mypyc.ir.rtypes import (
RInstance,
RType,
c_pyssize_t_rprimitive,
is_bytes_rprimitive,
is_int_rprimitive,
is_short_int_rprimitive,
is_str_rprimitive,
)
from mypyc.irbuild.builder import IRBuilder
from mypyc.irbuild.constant_fold import constant_fold_expr
from mypyc.primitives.bytes_ops import bytes_build_op
from mypyc.primitives.int_ops import int_to_ascii_op, int_to_str_op
from mypyc.primitives.str_ops import str_build_op, str_op
from mypyc.primitives.str_ops import format_obj_op, str_build_op, str_op


@unique
Expand Down Expand Up @@ -133,10 +134,19 @@ def tokenizer_format_call(format_str: str) -> tuple[list[str], list[FormatOp]] |


def convert_format_expr_to_str(
builder: IRBuilder, format_ops: list[FormatOp], exprs: list[Expression], line: int
builder: IRBuilder,
format_ops: list[FormatOp],
exprs: list[Expression],
line: int,
*,
use_format: bool,
) -> list[Value] | None:
"""Convert expressions into string literal objects with the guidance
of FormatOps. Return None when fails."""
of FormatOps. Return None when fails.

If use_format is true, convert values like format(x) (str.format() and f-strings),
which calls __format__. Otherwise convert them like str(x) (printf-style formatting).
"""
if len(format_ops) != len(exprs):
return None

Expand All @@ -146,10 +156,11 @@ def convert_format_expr_to_str(
if format_op == FormatOp.STR:
if isinstance(folded := constant_fold_expr(builder, x), str):
var_str = builder.load_literal_value(folded)
elif is_str_rprimitive(node_type):
var_str = builder.accept(x)
elif is_int_rprimitive(node_type) or is_short_int_rprimitive(node_type):
var_str = builder.primitive_op(int_to_str_op, [builder.accept(x)], line)
elif use_format and not is_format_same_as_str(node_type):
# This also handles str subclasses, which may override __format__
var_str = builder.call_c(format_obj_op, [builder.accept(x)], line)
else:
var_str = builder.primitive_op(str_op, [builder.accept(x)], line)
elif format_op == FormatOp.INT:
Expand All @@ -165,6 +176,24 @@ def convert_format_expr_to_str(
return converted


def is_format_same_as_str(typ: RType) -> bool:
"""Is format(x) known to be the same as str(x) for all values of a type?

This is the case for instances of native classes that don't define __format__.
"""
if not isinstance(typ, RInstance):
return False
subs = typ.class_ir.subclasses()
if subs is None:
return False
for cl in (typ.class_ir, *subs):
if not cl.is_ext_class or cl.inherits_python:
return False
if any("__format__" in base.methods for base in cl.mro):
return False
return True


def join_formatted_strings(
builder: IRBuilder, literals: list[str] | None, substitutions: list[Value], line: int
) -> Value:
Expand Down
8 changes: 6 additions & 2 deletions mypyc/irbuild/specialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -1067,7 +1067,9 @@ def translate_str_format(builder: IRBuilder, expr: CallExpr, callee: RefExpr) ->
return None
literals, format_ops = tokens
# Convert variables to strings
substitutions = convert_format_expr_to_str(builder, format_ops, expr.args, expr.line)
substitutions = convert_format_expr_to_str(
builder, format_ops, expr.args, expr.line, use_format=True
)
if substitutions is None:
return None
return join_formatted_strings(builder, literals, substitutions, expr.line)
Expand Down Expand Up @@ -1134,7 +1136,9 @@ def get_literal_str(expr: Expression) -> str | None:
exprs = [*exprs[:i], StrExpr(first + second), *exprs[i + 2 :]]
format_ops = [*format_ops[:i], FormatOp.STR, *format_ops[i + 2 :]]

substitutions = convert_format_expr_to_str(builder, format_ops, exprs, expr.line)
substitutions = convert_format_expr_to_str(
builder, format_ops, exprs, expr.line, use_format=True
)
if substitutions is None:
return None

Expand Down
9 changes: 9 additions & 0 deletions mypyc/lib-rt/CPy.h
Original file line number Diff line number Diff line change
Expand Up @@ -1133,6 +1133,15 @@ static inline char CPyDict_CheckSize(PyObject *dict, Py_ssize_t size) {
char CPyStr_Equal(PyObject *str1, PyObject *str2);
char CPyStr_EqualLiteral(PyObject *str, PyObject *literal_str, Py_ssize_t literal_length);
PyObject *CPyStr_Build(Py_ssize_t len, ...);

// format(obj), i.e. format(obj, '')
static inline PyObject *CPyObject_Format(PyObject *obj) {
if (PyUnicode_CheckExact(obj)) {
Py_INCREF(obj);
return obj;
}
return PyObject_Format(obj, NULL);
}
PyObject *CPyStr_GetItem(PyObject *str, CPyTagged index);
PyObject *CPyStr_GetItemUnsafe(PyObject *str, Py_ssize_t index);
CPyTagged CPyStr_Find(PyObject *str, PyObject *substr, CPyTagged start, int direction);
Expand Down
8 changes: 8 additions & 0 deletions mypyc/primitives/str_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@
error_kind=ERR_MAGIC,
)

# format(obj)
format_obj_op = custom_op(
arg_types=[object_rprimitive],
return_type=str_rprimitive,
c_function_name="CPyObject_Format",
error_kind=ERR_MAGIC,
)

# repr(obj)
function_op(
name="builtins.repr",
Expand Down
1 change: 1 addition & 0 deletions mypyc/test-data/fixtures/ir.py
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,7 @@ def max(
) -> _T: ...
def repr(o: object) -> str: ...
def ascii(o: object) -> str: ...
def format(o: object, format_spec: str = '') -> str: ...
def ord(o: object) -> int: ...
def chr(i: int) -> str: ...

Expand Down
Loading
Loading