You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@fory.apache.org by ch...@apache.org on 2026/10/13 05:40:57 UTC

(fory) branch main updated: fix(compiler): reject conflicting Python field names (#4175)

This is an automated email from the ASF dual-hosted git repository.

chaokunyang pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/fory.git


The following commit(s) were added to refs/heads/main by this push:
     new 9cc2a6ac0 fix(compiler): reject conflicting Python field names (#4175)
9cc2a6ac0 is described below

commit 9cc2a6ac07064529b099a1a4f96dec3f553461f3
Author: ooiuuii <al...@gmail.com>
AuthorDate: Mon Oct 12 22:40:53 2026 -0700

    fix(compiler): reject conflicting Python field names (#4175)
    
    ## Summary
    
    Fixes #4174. Python code generation previously allowed distinct schema
    fields such as `class` and `class_` to produce the same dataclass
    attribute, silently overwriting a field and its tag.
    
    Keep the existing keyword escape (`class` becomes `class_`) and preserve
    already-suffixed names (`class_` and `class__` stay unchanged). Reject
    fields in the same message that collide after snake_case conversion and
    escaping, including nested messages. The diagnostic identifies the
    original fields, generated attribute, and available source location, and
    asks the schema author to rename a field.
    
    Existing helper-name suffix conventions remain unchanged. Tests and the
    generated-code guide cover the collision errors and stable
    non-conflicting names. Numeric field tags and wire encoding are
    unchanged.
    
    ## Validation
    
    - Regression tests on the previous implementation: 44 failed, 21 passed.
    - `ENABLE_FORY_DEBUG_OUTPUT=1 python3 -m pytest
    fory_compiler/tests/test_python_generator.py -q`: 65 passed.
    - `ENABLE_FORY_DEBUG_OUTPUT=1 python3 -m pytest fory_compiler/tests -q`:
    580 passed, 1 existing unknown-option warning.
    - CLI check: conflicting `class` / `class_` fields exit with an error
    and source location; non-conflicting `class_` / `class__` fields retain
    their names and numeric tags.
    - Ruff formatting and lint, Prettier, and `git diff --check`: passed.
    
    Local validation used CPython 3.9.6 on macOS. The generated-class unit
    tests use a pyfory stub; no native serialization roundtrip is claimed.
    
    ---------
    
    Co-authored-by: chaokunyang <sh...@gmail.com>
---
 compiler/fory_compiler/generators/python.py        | 19 ++++++++
 .../fory_compiler/tests/test_python_generator.py   | 53 ++++++++++++++++++++++
 docs/compiler/generated-code/python.md             | 18 ++++++--
 3 files changed, 85 insertions(+), 5 deletions(-)

diff --git a/compiler/fory_compiler/generators/python.py b/compiler/fory_compiler/generators/python.py
index 212e8a553..357f4c50f 100644
--- a/compiler/fory_compiler/generators/python.py
+++ b/compiler/fory_compiler/generators/python.py
@@ -158,6 +158,8 @@ class PythonGenerator(PythonServiceGeneratorMixin, BaseGenerator):
         # distinct instead of overwriting a generated attribute and its tag.
         if name.rstrip("_") in self.FIELD_DEFAULT_HELPER_NAMES:
             return f"{name}_"
+        # Keep already-suffixed keywords stable. Message generation rejects actual
+        # collisions instead of renaming attributes in non-conflicting schemas.
         return self.safe_name(name)
 
     def is_imported_type(self, type_def: object) -> bool:
@@ -420,7 +422,24 @@ class PythonGenerator(PythonServiceGeneratorMixin, BaseGenerator):
             lines.append("")
 
         # Generate fields
+        field_names: Dict[str, Field] = {}
         for field in message.fields:
+            field_name = self.safe_field_name(self.to_snake_case(field.name))
+            if field_name in field_names:
+                previous = field_names[field_name]
+                message_name = ".".join(msg.name for msg in lineage)
+                location = field.location
+                source = (
+                    f"{location.file}:{location.line}:{location.column}: "
+                    if location and location.file
+                    else ""
+                )
+                raise ValueError(
+                    f"{source}Python field name collision in {message_name}: "
+                    f"{previous.name!r} and {field.name!r} both generate "
+                    f"{field_name!r}; rename one of the fields"
+                )
+            field_names[field_name] = field
             field_lines = self.generate_field(field, lineage)
             for line in field_lines:
                 lines.append(f"{ind}    {line}")
diff --git a/compiler/fory_compiler/tests/test_python_generator.py b/compiler/fory_compiler/tests/test_python_generator.py
index a1d94a4f2..65707cb9f 100644
--- a/compiler/fory_compiler/tests/test_python_generator.py
+++ b/compiler/fory_compiler/tests/test_python_generator.py
@@ -130,3 +130,56 @@ def test_helper_name_suffixes(name, reverse, field_type):
     for field_name, value in values.items():
         rendered = repr(value) if field_type == "string" else "any(...)"
         assert f"{field_name}={rendered}" in repr(instance)
+
+
+@pytest.mark.parametrize("name", ["class", "Class", "from", "async", "lambda"])
+@pytest.mark.parametrize("bare", [False, True])
+@pytest.mark.parametrize("field_type", ["string", "any"])
+def test_keyword_field_names(name, bare, field_type):
+    first = name if bare else name + "_"
+    output = generate_python(
+        f"message Tricky [id=100] {{ {field_type} {first} = 1; "
+        f"{field_type} {name}__ = 2; }}"
+    )
+    cls = exec_generated_module(output)["Tricky"]
+    names = [name.lower() + "_", name.lower() + "__"]
+    assert {f.name: f.metadata["id"] for f in dataclasses.fields(cls)} == {
+        names[0]: 1,
+        names[1]: 2,
+    }
+    values = {names[0]: "first", names[1]: "second"}
+    instance = cls(**values)
+    assert dataclasses.asdict(instance) == values
+    for field_name, value in values.items():
+        rendered = repr(value) if field_type == "string" else "any(...)"
+        assert f"{field_name}={rendered}" in repr(instance)
+
+
+@pytest.mark.parametrize(
+    "names, generated_name",
+    [
+        (("class", "class_"), "class_"),
+        (("Class", "class_"), "class_"),
+        (("from", "from_"), "from_"),
+        (("async", "async_"), "async_"),
+        (("lambda", "lambda_"), "lambda_"),
+        (("userName", "user_name"), "user_name"),
+    ],
+)
+@pytest.mark.parametrize("reverse", [False, True])
+@pytest.mark.parametrize("nested", [False, True])
+def test_field_name_collision(names, generated_name, reverse, nested):
+    fields = [f"string {name} = {i + 1};" for i, name in enumerate(names)]
+    if reverse:
+        fields.reverse()
+    source = "message Tricky [id=100] {" + "\n".join(fields) + "}"
+    if nested:
+        source = "message Outer [id=101] {" + source + "}"
+    with pytest.raises(ValueError) as exc:
+        generate_python(source)
+    message = str(exc.value)
+    assert "Python field name collision" in message
+    assert ("Outer.Tricky" if nested else "Tricky") in message
+    assert all(repr(name) in message for name in names)
+    assert f"both generate {generated_name!r}" in message
+    assert "rename" in message
diff --git a/docs/compiler/generated-code/python.md b/docs/compiler/generated-code/python.md
index d35a456b6..7aec40d40 100644
--- a/docs/compiler/generated-code/python.md
+++ b/docs/compiler/generated-code/python.md
@@ -73,11 +73,19 @@ class Person:
 ## Field Names
 
 Generated Python attributes use `snake_case`, with a trailing underscore for
-Python keywords. The names `field`, `pyfory`, `decimal`, `list`, and `dict` also
-receive a trailing underscore. Names consisting of one of these five names
-followed by underscores receive one additional underscore so fields remain
-distinct: `field`, `field_`, and `field__` become `field_`, `field__`, and
-`field___`. Field tag IDs remain unchanged.
+Python keywords: `class` becomes `class_`. Already-suffixed keyword names stay
+unchanged: `class_` remains `class_`, and `class__` remains `class__`.
+
+If two fields in the same message produce the same Python attribute name after
+conversion and escaping, compilation fails. For example, `class` and `class_`
+both produce `class_`, while `userName` and `user_name` both produce `user_name`.
+Rename one of the fields in the schema to resolve the conflict.
+
+The names `field`, `pyfory`, `decimal`, `list`, and `dict` also receive a trailing
+underscore. Names consisting of one of these five names followed by underscores
+receive one additional underscore so fields remain distinct: `field`, `field_`,
+and `field__` become `field_`, `field__`, and `field___`. Field tag IDs remain
+unchanged.
 
 ## Registration
 


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@fory.apache.org
For additional commands, e-mail: commits-help@fory.apache.org