diff --git a/lib/core/Handles/HandlesMatch.py b/lib/core/Handles/HandlesMatch.py index 4deb20e..5658863 100644 --- a/lib/core/Handles/HandlesMatch.py +++ b/lib/core/Handles/HandlesMatch.py @@ -34,6 +34,46 @@ class MatchHandle(BaseHandle): Names.append(_rest) return Names + @staticmethod + def _ValueLabelKey(Value: ast.expr) -> str: + """MatchValue.value 的标签键:Constant / Name / Attribute 链""" + if isinstance(Value, ast.Constant): + Kind: str = Value.kind if Value.kind is not None else type(Value.value).__name__ + return f"{Kind}:{Value.value!r}" + if isinstance(Value, ast.Name): + return f"Name:{Value.id}" + if isinstance(Value, ast.Attribute): + return f"Attr:{MatchHandle._ValueLabelKey(Value.value)}.{Value.attr}" + return f"{type(Value).__name__}" + + @staticmethod + def _CaseLabelKey(Pattern: ast.pattern) -> str | None: + """case 的 switch 标签键(None = 不参与重名判定) + + - MatchValue → 'V:<值键>'(Constant 值 / Name / Attribute 链) + - MatchSingleton → 'S:<值>'(None/True/False) + - MatchClass → 'K:<变体名>'(cls 为 Name 用 id,Attribute 用链) + - MatchOr → 'O:<子模式键>'(子键任一不可比则整条不可比) + - MatchAs / MatchSequence 等 → None(通配/序列,不产出 switch 常量标签) + """ + if isinstance(Pattern, ast.MatchValue): + return f"V:{MatchHandle._ValueLabelKey(Pattern.value)}" + if isinstance(Pattern, ast.MatchSingleton): + return f"S:{Pattern.value!r}" + if isinstance(Pattern, ast.MatchClass): + Cls: ast.expr = Pattern.cls + if isinstance(Cls, ast.Name): + return f"K:{Cls.id}" + if isinstance(Cls, ast.Attribute): + return f"K:{MatchHandle._ValueLabelKey(Cls)}" + return None + if isinstance(Pattern, ast.MatchOr): + Parts: list[str | None] = [MatchHandle._CaseLabelKey(p) for p in Pattern.patterns] + if any(p is None for p in Parts): + return None + return "O:" + "|".join(Parts) + return None + def _HandleMatchLlvm(self, Node: ast.Match) -> None: Gen: "Translator.LlvmGen" = self.Trans.LlvmGen # 重名 case 检测(fail-fast):C 的 switch 不允许重复 case 标签——重复标签会让