From 25153a4b7a5918acfe9e052fdd650d550a1ee1bb Mon Sep 17 00:00:00 2001 From: hauntsaninja Date: Fri, 23 Oct 2026 02:34:10 -0700 Subject: [PATCH] [mypyc] fix indent tracking This reduces the size of the emitted C code for mypy in release configuration by like 8x Previously, mypyc failed to properly keep track of the indent in the module initialising code, and so added 8 spaces every time that were never dedented We have a lot of modules in mypy/c, so turns out this really adds up Codex claims this makes compilation like 5% faster Co-authored by Codex --- mypyc/codegen/emit.py | 5 +++-- mypyc/test/test_emit.py | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/mypyc/codegen/emit.py b/mypyc/codegen/emit.py index eb82fb6014280..459af4d0a49a4 100644 --- a/mypyc/codegen/emit.py +++ b/mypyc/codegen/emit.py @@ -258,11 +258,12 @@ def object_annotation(self, obj: object, line: str) -> str: return f" /* {formatted} */" def emit_line(self, line: str = "", *, ann: object = None) -> None: - if line.startswith("}"): + stripped = line.strip() + if stripped.startswith("}"): self.dedent() comment = self.object_annotation(ann, line) if ann is not None else "" self.fragments.append(self._indent * " " + line + comment + "\n") - if line.endswith("{"): + if stripped.endswith("{"): self.indent() def emit_lines(self, *lines: str) -> None: diff --git a/mypyc/test/test_emit.py b/mypyc/test/test_emit.py index 6c28fc3eb1123..0c536b5e7c2c9 100644 --- a/mypyc/test/test_emit.py +++ b/mypyc/test/test_emit.py @@ -116,6 +116,26 @@ def test_emit_line(self) -> None: assert emitter.fragments[0] == "CPyStatics[0]; /* 'hello, world' */\n" assert emitter.fragments[1] == "CPyStatics[1]; /* 42 */\n" + def test_emit_line_with_indented_braces(self) -> None: + self.emitter.emit_lines( + "if (outer)", + " if (inner) { ", + " f();", + " } else {", + " g();", + " }", + "h();", + ) + self.assert_output( + "if (outer)\n" + " if (inner) { \n" + " f();\n" + " } else {\n" + " g();\n" + " }\n" + "h();\n" + ) + def test_emit_undefined_value_for_simple_type(self) -> None: emitter = self.emitter assert emitter.c_undefined_value(int_rprimitive) == "CPY_INT_TAG"