[mypyc] Fix bad C for attribute names that are C keywords when mangled (#22526)
Fixes mypyc/mypyc#1217. Fixes mypyc/mypyc#1187.
The C struct field name of a native attribute is the attribute name with
a "_" prefix, which can produce a C keyword or some other name reserved
by C compilers, resulting in confusing C compilation errors:
```python
class C:
def __init__(self) -> None:
self._restrict = 0 # Field "__restrict" is a keyword in gcc/clang
```
Many names names were affected.
Now if the prefixed name is reserved by the C standard (it starts with
two underscores or an underscore followed by an uppercase letter) or is
a known MSVC keyword, an additional "m" prefix is used. This can't
collide with other field names, since they all start with "_".
diff --git a/mypyc/codegen/emit.py b/mypyc/codegen/emit.py
index c018307..4ab9b77 100644
--- a/mypyc/codegen/emit.py
+++ b/mypyc/codegen/emit.py
@@ -214,6 +214,58 @@
self.value = value
+# Keywords of some C compilers (MSVC) that aren't reserved by the C standard.
+NONSTANDARD_C_KEYWORDS: Final = frozenset(
+ {
+ "_alignof",
+ "_asm",
+ "_assume",
+ "_based",
+ "_cdecl",
+ "_declspec",
+ "_except",
+ "_fastcall",
+ "_finally",
+ "_forceinline",
+ "_inline",
+ "_int8",
+ "_int16",
+ "_int32",
+ "_int64",
+ "_leave",
+ "_multiple_inheritance",
+ "_pascal",
+ "_ptr32",
+ "_ptr64",
+ "_restrict",
+ "_single_inheritance",
+ "_sptr",
+ "_stdcall",
+ "_thiscall",
+ "_try",
+ "_unaligned",
+ "_uptr",
+ "_uuidof",
+ "_vectorcall",
+ "_virtual_inheritance",
+ "_w64",
+ }
+)
+
+
+def is_reserved_c_name(name: str) -> bool:
+ """Can name conflict with a keyword or macro of a C compiler or system headers?
+
+ Names starting with two underscores or an underscore and an uppercase letter are
+ reserved by the C standard (e.g. "__restrict", "_Bool").
+ """
+ return (
+ name.startswith("__")
+ or (len(name) > 1 and name[0] == "_" and name[1].isupper())
+ or name in NONSTANDARD_C_KEYWORDS
+ )
+
+
class Emitter:
"""Helper for C code generation."""
@@ -251,7 +303,13 @@
return REG_PREFIX + self.value_names[reg]
def attr(self, name: str) -> str:
- return ATTR_PREFIX + name
+ """Return the C struct field name for a native attribute."""
+ result = ATTR_PREFIX + name
+ if is_reserved_c_name(result):
+ # Avoid C keywords and macros (e.g. "_restrict" -> "__restrict"). This is
+ # unambiguous, since other field names start with ATTR_PREFIX.
+ result = "m" + result
+ return result
def object_annotation(self, obj: object, line: str) -> str:
"""Build a C comment with a literal value's string representation.
diff --git a/mypyc/test-data/run-classes.test b/mypyc/test-data/run-classes.test
index ee562ee..1304837 100644
--- a/mypyc/test-data/run-classes.test
+++ b/mypyc/test-data/run-classes.test
@@ -10178,3 +10178,39 @@
assert owned_child(child) == (item, (item, number))
assert borrowed_child(child) is item
assert read_numbers(child, 100) == 300.0
+
+[case testAttributeNamesThatAreCKeywords]
+from typing import Any
+
+class C:
+ restrict: str = "eggs"
+
+ def __init__(self) -> None:
+ # With the "_" prefix of attribute names in C, these become C keywords or
+ # other names reserved by C compilers (e.g. "__restrict", "_Bool")
+ self._restrict: int = 0
+ self._inline = 1
+ self._asm = 2
+ self.Bool = 3
+ self._unix__ = 4
+ self._x = 5
+ self.m__x = 6
+ self.vectorcall = 7
+ self.unaligned = 8
+
+def test_attribute_names() -> None:
+ c = C()
+ assert c.restrict == "eggs"
+ assert c._restrict == 0
+ assert c._inline == 1
+ assert c._asm == 2
+ assert c.Bool == 3
+ assert c._unix__ == 4
+ assert c._x == 5
+ assert c.m__x == 6
+ assert c.vectorcall == 7
+ assert c.unaligned == 8
+ a: Any = c
+ a._restrict = 7
+ assert c._restrict == 7
+ assert a.m__x == 6