From 8a39148cde1ea3953c09cfae1df0983cddc039b2 Mon Sep 17 00:00:00 2001 From: Taus Date: Tue, 15 Sep 2026 11:29:37 +0000 Subject: [PATCH] Python: Add yeast node type generator for Python extractor AST This uses `master.py` -- the file that describes the structure of Python ASTs -- and the internal Python extractor AST classes to generate a `node-types.yml` file that can be used by YEAST. On the rare occasion that this file needs to be regenerated, this can be done by invoking `make legacy-ast-types`, in the same way that `make ast` regenerates the QL files for the AST. In the process, we ended up needing to distinguish between AST leaves that carry values (like identifiers) and ones that are just structural (like `Break`). In the schema, the latter can now be given an explicit empty map `{}` as fields. This required a small change to `yeast-schema` and friends. --- python/extractor/Makefile | 6 + python/extractor/extending-the-parser.md | 12 + .../semmle/python/legacy_ast_types_gen.py | 353 +++++++++++ .../tests/test_legacy_ast_types_gen.py | 58 ++ .../yeast-python/legacy_ast_types.yml | 583 ++++++++++++++++++ shared/yeast-macros/src/ast.rs | 27 +- shared/yeast-schema/src/node_types_yaml.rs | 9 +- shared/yeast/doc/node-types-yaml.md | 16 +- 8 files changed, 1052 insertions(+), 12 deletions(-) create mode 100644 python/extractor/semmle/python/legacy_ast_types_gen.py create mode 100644 python/extractor/tests/test_legacy_ast_types_gen.py create mode 100644 python/extractor/yeast-python/legacy_ast_types.yml diff --git a/python/extractor/Makefile b/python/extractor/Makefile index 54095f6572be..12224a584643 100644 --- a/python/extractor/Makefile +++ b/python/extractor/Makefile @@ -35,6 +35,12 @@ ast: $(MASTER_FILE) python3 -m semmle.query_gen $(AST_GENERATED_DIR) codeql query format --in-place $(AST_GENERATED_FILE) +LEGACY_AST_TYPES_FILE = yeast-python/legacy_ast_types.yml + +.PHONY: legacy-ast-types +legacy-ast-types: $(MASTER_FILE) semmle/python/ast.py semmle/python/legacy_ast_types_gen.py + poetry run python -m semmle.python.legacy_ast_types_gen $(LEGACY_AST_TYPES_FILE) + ################################################################################ # Tests ################################################################################ diff --git a/python/extractor/extending-the-parser.md b/python/extractor/extending-the-parser.md index 54b11d4ff855..5cf152216180 100644 --- a/python/extractor/extending-the-parser.md +++ b/python/extractor/extending-the-parser.md @@ -88,6 +88,18 @@ If you added new node types, or added fields to known node types, then you'll ne New AST nodes should be added in two places: `master.py` and `semmle/python/ast.py`. The former of these is used to automatically generate the Python dbscheme and `AstGenerated.qll`. The latter is what the parser actually uses as its internal representation of the AST. +The yeast-compatible schema for this legacy AST is generated as +`yeast-python/legacy_ast_types.yml`. After changing either AST description, regenerate it with: + +```sh +make legacy-ast-types +``` + +The generator combines the field types and inheritance information in `master.py` with the runtime +field layout in `semmle/python/ast.py`. It fails when the two descriptions acquire an unexplained +difference, so parser-only fields or intentional exclusions must be recorded in +`semmle/python/legacy_ast_types_gen.py`. + ## Step 5: Rebuild the autogenerated AST and database scheme If you made changes to `master.py`, you'll need to regenerate a couple of files. This can be done from within the `extractor` directory using the `make dbscheme` and `make ast` commands. Note that for the latter, you need a copy of the CodeQL CLI present, as it is used to autoformat the `AstGenerated.qll` file. diff --git a/python/extractor/semmle/python/legacy_ast_types_gen.py b/python/extractor/semmle/python/legacy_ast_types_gen.py new file mode 100644 index 000000000000..22671e264ae3 --- /dev/null +++ b/python/extractor/semmle/python/legacy_ast_types_gen.py @@ -0,0 +1,353 @@ +"""Generate the yeast output schema for the legacy Python extractor AST.""" + +import argparse +from pathlib import Path + +import yaml + +from semmle.python import ast, master +from semmle.python.AstMeta import ClassNode, ListNode, PrimitiveNode, UnionNode + + +OUTPUT_PATH = Path(__file__).resolve().parents[2] / "yeast-python" / "legacy_ast_types.yml" + +LITERAL_KINDS = ( + "string_literal", + "bytes_literal", + "integer_literal", + "boolean_literal", + "number_literal", + "variable_literal", + "python_string_literal", + "none_literal", +) + +PRIMITIVE_LITERAL_KINDS = { + "str": "string_literal", + "bytes": "bytes_literal", + "int": "integer_literal", + "bool": "boolean_literal", + "number": "number_literal", + "variable": "variable_literal", +} + + +class _RepeatedType: + def __init__(self, item_type): + self.item_type = item_type + + +# These fields are populated after parsing or exist only in the extraction schema. +EXCLUDED_MASTER_FIELDS = { + "Module": {"name", "hash", "kind"}, + # master.py declares both `class` and `class_name`, but the runtime AST only has `class_name`, + # which is the field populated by both parsers. Since AST extraction walks runtime fields, + # the legacy `class` slot in the generated database schema is not populated. + "MatchClassPattern": {"class"}, + "TemplateStringPart": {"parenthesised"}, +} + +# These fields exist on the runtime AST but are intentionally absent from the extraction schema. +ADDITIONAL_FIELD_TYPES = { + ("comprehension", "is_async"): "boolean_literal", + ("DictComp", "key"): "expr", + ("DictComp", "value"): "expr", + ("DictComp", "generators"): _RepeatedType("comprehension"), + ("GeneratorExp", "elt"): "expr", + ("GeneratorExp", "generators"): _RepeatedType("comprehension"), + ("SetComp", "elt"): "expr", + ("SetComp", "generators"): _RepeatedType("comprehension"), + ("StringPart", "prefix"): "string_literal", + ("StringPart", "s"): "python_string_literal", + ("TemplateStringPart", "s"): "python_string_literal", +} + +# These fields have a parser representation that differs from their database primitive type. +FIELD_TYPE_OVERRIDES = { + ("Bytes", "prefix"): "string_literal", + ("Bytes", "s"): "python_string_literal", + ("Num", "text"): "string_literal", + ("Str", "s"): "python_string_literal", +} + +# The lists are aligned with parameter lists, so missing entries are explicit None values. +FIELDS_WITH_NONE_ELEMENTS = { + ("arguments", "annotations"), + ("arguments", "defaults"), + ("arguments", "kw_annotations"), + ("arguments", "kw_defaults"), +} + +MANUAL_RUNTIME_FIELDS = { + "Module": ("body",), +} + + +def _runtime_field_order(cls): + if cls.__name__ in MANUAL_RUNTIME_FIELDS: + return MANUAL_RUNTIME_FIELDS[cls.__name__] + + fields = [] + seen = set() + for base in cls.__mro__: + slots = base.__dict__.get("__slots__", ()) + if isinstance(slots, str): + slots = (slots,) + for field in slots: + if field not in ast.AstBase.__slots__ and field not in seen: + fields.append(field) + seen.add(field) + return tuple(fields) + + +def _runtime_fields(cls): + return set(_runtime_field_order(cls)) + + +def _class_nodes(nodes): + return { + node.__name__: node + for node in nodes.values() + if isinstance(node, ClassNode) + } + + +def _validate_runtime_field_overrides(class_nodes): + runtime_classes = { + name: cls + for name, cls in ast.__dict__.items() + if isinstance(cls, type) and cls is not ast.AstBase and ast.AstBase in cls.__mro__ + } + if set(runtime_classes) != set(class_nodes): + missing_from_master = sorted(set(runtime_classes) - set(class_nodes)) + missing_from_runtime = sorted(set(class_nodes) - set(runtime_classes)) + raise ValueError( + "Runtime and master AST classes differ: " + "runtime-only={}, master-only={}".format( + missing_from_master, missing_from_runtime + ) + ) + + configured_additions = {} + for (kind, field), _field_type in ADDITIONAL_FIELD_TYPES.items(): + configured_additions.setdefault(kind, set()).add(field) + + for kind, cls in runtime_classes.items(): + master_fields = { + field + for field, field_type, _description, _artificial, _parser_type + in class_nodes[kind].fields + if field_type is not master.location + } + runtime_fields = _runtime_fields(cls) + expected_runtime_only = configured_additions.get(kind, set()) + expected_master_only = EXCLUDED_MASTER_FIELDS.get(kind, set()) + runtime_only = runtime_fields - master_fields + master_only = master_fields - runtime_fields + if runtime_only != expected_runtime_only or master_only != expected_master_only: + raise ValueError( + "{} field metadata differs: runtime-only={} (expected {}), " + "master-only={} (expected {})".format( + kind, + sorted(runtime_only), + sorted(expected_runtime_only), + sorted(master_only), + sorted(expected_master_only), + ) + ) + + +def _type_name(field_type): + if isinstance(field_type, PrimitiveNode): + if field_type is master.location: + return None + try: + return PRIMITIVE_LITERAL_KINDS[field_type.__name__] + except KeyError: + raise ValueError( + "No literal kind configured for primitive '{}'".format( + field_type.__name__ + ) + ) + if isinstance(field_type, (ClassNode, UnionNode)): + return field_type.__name__ + if isinstance(field_type, str): + return field_type + raise TypeError("Unsupported field type {!r}".format(field_type)) + + +def _field_schema(kind, field, field_type): + multiple = isinstance(field_type, (ListNode, _RepeatedType)) + item_type = field_type.item_type if multiple else field_type + type_names = [_type_name(item_type)] + if (kind, field) in FIELDS_WITH_NONE_ELEMENTS: + type_names.append("none_literal") + value = type_names[0] if len(type_names) == 1 else type_names + suffix = "*" if multiple else "?" + return field + suffix, value + + +def _fields_for_class(node): + field_types = {} + excluded = EXCLUDED_MASTER_FIELDS.get(node.__name__, set()) + for field, field_type, _description, _artificial, _parser_type in node.fields: + if field in excluded or field_type is master.location: + continue + field_types[field] = FIELD_TYPE_OVERRIDES.get( + (node.__name__, field), field_type + ) + + for (kind, field), field_type in ADDITIONAL_FIELD_TYPES.items(): + if kind == node.__name__: + field_types[field] = field_type + + fields = {} + runtime_class = getattr(ast, node.__name__) + for field in _runtime_field_order(runtime_class): + field_type = field_types[field] + name, value = _field_schema(node.__name__, field, field_type) + fields[name] = value + return fields + + +def build_schema(): + nodes = master.all_nodes() + class_nodes = _class_nodes(nodes) + _validate_runtime_field_overrides(class_nodes) + + supertypes = {} + for node in sorted(class_nodes.values(), key=lambda n: n._index): + if node.subclasses: + subtypes = [ + subtype.__name__ + for subtype in sorted(node.subclasses, key=lambda n: n._index) + ] + fields = _fields_for_class(node) + supertypes[node.__name__] = ( + {"subtypes": subtypes, "fields": fields} + if fields + else subtypes + ) + + referenced_unions = set() + for node in class_nodes.values(): + for _field, field_type, _description, _artificial, _parser_type in node.fields: + item_type = field_type.item_type if isinstance(field_type, ListNode) else field_type + if isinstance(item_type, UnionNode): + referenced_unions.add(item_type) + for union in sorted(referenced_unions, key=lambda n: n.__name__): + supertypes[union.__name__] = [ + member.__name__ for member in sorted(union.types, key=lambda n: n._index) + ] + + supertypes["literal"] = list(LITERAL_KINDS) + + named = {} + for node in sorted(class_nodes.values(), key=lambda n: n._index): + if not node.subclasses: + named[node.__name__] = _fields_for_class(node) + for kind in LITERAL_KINDS: + named[kind] = None + + schema = { + "supertypes": supertypes, + "named": named, + } + _validate_type_references(schema) + return schema + + +def _validate_type_references(schema): + known_types = set(schema["supertypes"]) | set(schema["named"]) + for supertype, declaration in schema["supertypes"].items(): + members = ( + declaration["subtypes"] + if isinstance(declaration, dict) + else declaration + ) + unknown = set(members) - known_types + if unknown: + raise ValueError( + "Supertype '{}' refers to unknown types {}".format( + supertype, sorted(unknown) + ) + ) + if isinstance(declaration, dict): + _validate_field_type_references( + supertype, declaration["fields"], known_types + ) + for kind, fields in schema["named"].items(): + _validate_field_type_references(kind, fields, known_types) + + +def _validate_field_type_references(kind, fields, known_types): + for field, field_types in (fields or {}).items(): + if isinstance(field_types, str): + field_types = [field_types] + unknown = set(field_types) - known_types + if unknown: + raise ValueError( + "{}.{} refers to unknown types {}".format( + kind, field, sorted(unknown) + ) + ) + + +class _IndentedSafeDumper(yaml.SafeDumper): + def increase_indent(self, flow=False, indentless=False): + return super().increase_indent(flow, False) + + +def _represent_none(dumper, _value): + return dumper.represent_scalar("tag:yaml.org,2002:null", "") + + +_IndentedSafeDumper.add_representer(type(None), _represent_none) + + +def render_schema(): + header = ( + "# Generated by `python3 -m semmle.python.legacy_ast_types_gen`.\n" + "# Do not edit this file directly; update master.py, ast.py, or the generator instead.\n\n" + "# Primitive values are represented by typed leaf nodes whose content is a string.\n" + "# Singular fields are optional and list fields allow zero or more children because\n" + "# master.py does not record field requiredness.\n\n" + ) + return header + yaml.dump( + build_schema(), + Dumper=_IndentedSafeDumper, + sort_keys=False, + allow_unicode=True, + width=100, + ) + + +def main(argv=None): + parser = argparse.ArgumentParser( + description="Generate the yeast schema for the legacy Python AST" + ) + parser.add_argument( + "output", + nargs="?", + type=Path, + default=OUTPUT_PATH, + help="output path (default: %(default)s)", + ) + parser.add_argument( + "--check", + action="store_true", + help="fail if the output file is not up to date", + ) + args = parser.parse_args(argv) + + generated = render_schema() + if args.check: + if not args.output.exists() or args.output.read_text(encoding="utf-8") != generated: + parser.error("{} is not up to date".format(args.output)) + return + + args.output.write_text(generated, encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/python/extractor/tests/test_legacy_ast_types_gen.py b/python/extractor/tests/test_legacy_ast_types_gen.py new file mode 100644 index 000000000000..a94112dba60b --- /dev/null +++ b/python/extractor/tests/test_legacy_ast_types_gen.py @@ -0,0 +1,58 @@ +import yaml + +from semmle.python import legacy_ast_types_gen + + +def test_generated_legacy_ast_schema_is_up_to_date(): + generated = legacy_ast_types_gen.render_schema() + assert legacy_ast_types_gen.OUTPUT_PATH.read_text(encoding="utf-8") == generated + assert ": null" not in generated + + +def test_generated_legacy_ast_schema_structure(): + schema = yaml.safe_load(legacy_ast_types_gen.render_schema()) + + assert "BinOp" in schema["supertypes"]["expr"]["subtypes"] + assert schema["supertypes"]["expr"]["fields"] == { + "parenthesised?": "boolean_literal" + } + assert schema["supertypes"]["parameter"] == ["Name", "Tuple"] + assert "MatchClassPattern" in schema["supertypes"]["pattern"]["subtypes"] + assert schema["supertypes"]["pattern"]["fields"] == { + "parenthesised?": "boolean_literal" + } + assert "string_literal" in schema["supertypes"]["literal"] + + assert schema["named"]["BinOp"] == { + "left?": "expr", + "op?": "operator", + "right?": "expr", + "parenthesised?": "boolean_literal", + } + assert list(schema["named"]["Assign"]) == ["targets*", "value?"] + assert list(schema["named"]["DictComp"]) == [ + "key?", + "value?", + "generators*", + "function?", + "iterable?", + "parenthesised?", + ] + assert schema["named"]["Global"]["names*"] == "string_literal" + assert schema["named"]["arguments"]["annotations*"] == [ + "expr", + "none_literal", + ] + assert schema["named"]["StringPart"] == { + "text?": "string_literal", + "prefix?": "string_literal", + "s?": "python_string_literal", + } + assert schema["named"]["Module"] == {"body*": "stmt"} + assert schema["named"]["Add"] == {} + assert schema["named"]["Load"] == {} + assert schema["named"]["Pass"] == {} + assert "class?" not in schema["named"]["MatchClassPattern"] + assert schema["named"]["MatchClassPattern"]["class_name?"] == "expr" + assert "location" not in schema["named"]["Name"] + assert schema["named"]["none_literal"] is None diff --git a/python/extractor/yeast-python/legacy_ast_types.yml b/python/extractor/yeast-python/legacy_ast_types.yml new file mode 100644 index 000000000000..26e425681f3b --- /dev/null +++ b/python/extractor/yeast-python/legacy_ast_types.yml @@ -0,0 +1,583 @@ +# Generated by `python3 -m semmle.python.legacy_ast_types_gen`. +# Do not edit this file directly; update master.py, ast.py, or the generator instead. + +# Primitive values are represented by typed leaf nodes whose content is a string. +# Singular fields are optional and list fields allow zero or more children because +# master.py does not record field requiredness. + +supertypes: + boolop: + - And + - Or + cmpop: + - Eq + - Gt + - GtE + - In + - Is + - IsNot + - Lt + - LtE + - NotEq + - NotIn + expr: + subtypes: + - Attribute + - BinOp + - BoolOp + - Bytes + - Call + - ClassExpr + - Compare + - Dict + - DictComp + - Ellipsis + - FunctionExpr + - GeneratorExp + - IfExp + - ImportExpr + - ImportMember + - Lambda + - List + - ListComp + - Guard + - Name + - Num + - Repr + - Set + - SetComp + - Slice + - Starred + - Str + - Subscript + - Tuple + - UnaryOp + - Yield + - YieldFrom + - TemplateDottedNotation + - Filter + - PlaceHolder + - Await + - JoinedStr + - FormattedValue + - AssignExpr + - SpecialOperation + - TemplateString + - JoinedTemplateString + - TemplateStringPart + fields: + parenthesised?: boolean_literal + expr_context: + - AugLoad + - AugStore + - Del + - Load + - Param + - Store + operator: + - Add + - BitAnd + - BitOr + - BitXor + - Div + - FloorDiv + - LShift + - Mod + - Mult + - Pow + - RShift + - Sub + - MatMult + stmt: + - Assert + - Assign + - AugAssign + - Break + - Continue + - Delete + - ExceptStmt + - ExceptGroupStmt + - Exec + - Expr + - For + - Global + - If + - Import + - ImportFrom + - Match + - Case + - Nonlocal + - Pass + - Print + - Raise + - Return + - Try + - While + - With + - TemplateWrite + - AnnAssign + - TypeAlias + unaryop: + - Invert + - Not + - UAdd + - USub + pattern: + subtypes: + - MatchAsPattern + - MatchOrPattern + - MatchLiteralPattern + - MatchCapturePattern + - MatchWildcardPattern + - MatchValuePattern + - MatchSequencePattern + - MatchStarPattern + - MatchMappingPattern + - MatchDoubleStarPattern + - MatchKeyValuePattern + - MatchClassPattern + - MatchKeywordPattern + fields: + parenthesised?: boolean_literal + dict_item: + - DictUnpacking + - KeyValuePair + - keyword + type_parameter: + - ParamSpec + - TypeVar + - TypeVarTuple + parameter: + - Name + - Tuple + literal: + - string_literal + - bytes_literal + - integer_literal + - boolean_literal + - number_literal + - variable_literal + - python_string_literal + - none_literal +named: + Module: + body*: stmt + Class: + name?: string_literal + body*: stmt + Function: + is_async?: boolean_literal + name?: string_literal + type_parameters*: type_parameter + args*: parameter + vararg?: expr + kwonlyargs*: expr + kwarg?: expr + body*: stmt + alias: + value?: expr + asname?: expr + arguments: + defaults*: + - expr + - none_literal + kw_defaults*: + - expr + - none_literal + annotations*: + - expr + - none_literal + varargannotation?: expr + kwargannotation?: expr + kw_annotations*: + - expr + - none_literal + comprehension: + is_async?: boolean_literal + target?: expr + iter?: expr + ifs*: expr + Add: {} + And: {} + Assert: + test?: expr + msg?: expr + Assign: + targets*: expr + value?: expr + Attribute: + value?: expr + attr?: string_literal + ctx?: expr_context + parenthesised?: boolean_literal + AugAssign: + operation?: BinOp + AugLoad: {} + AugStore: {} + BinOp: + left?: expr + op?: operator + right?: expr + parenthesised?: boolean_literal + BitAnd: {} + BitOr: {} + BitXor: {} + BoolOp: + op?: boolop + values*: expr + parenthesised?: boolean_literal + Break: {} + Bytes: + s?: python_string_literal + prefix?: string_literal + implicitly_concatenated_parts*: StringPart + parenthesised?: boolean_literal + Call: + func?: expr + positional_args*: expr + named_args*: dict_item + parenthesised?: boolean_literal + ClassExpr: + name?: string_literal + type_parameters*: type_parameter + bases*: expr + keywords*: dict_item + inner_scope?: Class + parenthesised?: boolean_literal + Compare: + left?: expr + ops*: cmpop + comparators*: expr + parenthesised?: boolean_literal + Continue: {} + Del: {} + Delete: + targets*: expr + Dict: + items*: dict_item + parenthesised?: boolean_literal + DictComp: + key?: expr + value?: expr + generators*: comprehension + function?: Function + iterable?: expr + parenthesised?: boolean_literal + Div: {} + Ellipsis: + parenthesised?: boolean_literal + Eq: {} + ExceptStmt: + type?: expr + name?: expr + body*: stmt + ExceptGroupStmt: + type?: expr + name?: expr + body*: stmt + Exec: + body?: expr + globals?: expr + locals?: expr + Expr: + value?: expr + FloorDiv: {} + For: + is_async?: boolean_literal + target?: expr + iter?: expr + body*: stmt + orelse*: stmt + FunctionExpr: + name?: string_literal + args?: arguments + returns?: expr + inner_scope?: Function + parenthesised?: boolean_literal + GeneratorExp: + elt?: expr + generators*: comprehension + function?: Function + iterable?: expr + parenthesised?: boolean_literal + Global: + names*: string_literal + Gt: {} + GtE: {} + If: + test?: expr + body*: stmt + orelse*: stmt + IfExp: + test?: expr + body?: expr + orelse?: expr + parenthesised?: boolean_literal + Import: + is_lazy?: boolean_literal + names*: alias + ImportExpr: + level?: integer_literal + name?: string_literal + top?: boolean_literal + parenthesised?: boolean_literal + ImportMember: + module?: expr + name?: string_literal + parenthesised?: boolean_literal + ImportFrom: + is_lazy?: boolean_literal + module?: expr + In: {} + Invert: {} + Is: {} + IsNot: {} + LShift: {} + Lambda: + args?: arguments + inner_scope?: Function + parenthesised?: boolean_literal + List: + elts*: expr + ctx?: expr_context + parenthesised?: boolean_literal + ListComp: + elt?: expr + generators*: comprehension + function?: Function + iterable?: expr + parenthesised?: boolean_literal + Load: {} + Lt: {} + LtE: {} + Match: + subject?: expr + cases*: stmt + Case: + pattern?: pattern + guard?: expr + body*: stmt + Guard: + test?: expr + parenthesised?: boolean_literal + MatchAsPattern: + pattern?: pattern + alias?: expr + parenthesised?: boolean_literal + MatchOrPattern: + patterns*: pattern + parenthesised?: boolean_literal + MatchLiteralPattern: + literal?: expr + parenthesised?: boolean_literal + MatchCapturePattern: + variable?: expr + parenthesised?: boolean_literal + MatchWildcardPattern: + parenthesised?: boolean_literal + MatchValuePattern: + value?: expr + parenthesised?: boolean_literal + MatchSequencePattern: + patterns*: pattern + parenthesised?: boolean_literal + MatchStarPattern: + target?: pattern + parenthesised?: boolean_literal + MatchMappingPattern: + mappings*: pattern + parenthesised?: boolean_literal + MatchDoubleStarPattern: + target?: pattern + parenthesised?: boolean_literal + MatchKeyValuePattern: + key?: pattern + value?: pattern + parenthesised?: boolean_literal + MatchClassPattern: + class_name?: expr + positional*: pattern + keyword*: pattern + parenthesised?: boolean_literal + MatchKeywordPattern: + attribute?: expr + value?: pattern + parenthesised?: boolean_literal + Mod: {} + Mult: {} + Name: + variable?: variable_literal + ctx?: expr_context + parenthesised?: boolean_literal + Nonlocal: + names*: string_literal + Not: {} + NotEq: {} + NotIn: {} + Num: + n?: number_literal + text?: string_literal + parenthesised?: boolean_literal + Or: {} + Param: {} + Pass: {} + Pow: {} + Print: + dest?: expr + values*: expr + nl?: boolean_literal + RShift: {} + Raise: + exc?: expr + cause?: expr + type?: expr + inst?: expr + tback?: expr + Repr: + value?: expr + parenthesised?: boolean_literal + Return: + value?: expr + Set: + elts*: expr + parenthesised?: boolean_literal + SetComp: + elt?: expr + generators*: comprehension + function?: Function + iterable?: expr + parenthesised?: boolean_literal + Slice: + start?: expr + stop?: expr + step?: expr + parenthesised?: boolean_literal + Starred: + value?: expr + ctx?: expr_context + parenthesised?: boolean_literal + Store: {} + Str: + s?: python_string_literal + prefix?: string_literal + implicitly_concatenated_parts*: StringPart + parenthesised?: boolean_literal + Sub: {} + Subscript: + value?: expr + index?: expr + ctx?: expr_context + parenthesised?: boolean_literal + Try: + body*: stmt + orelse*: stmt + handlers*: stmt + finalbody*: stmt + Tuple: + elts*: expr + ctx?: expr_context + parenthesised?: boolean_literal + UAdd: {} + USub: {} + UnaryOp: + op?: unaryop + operand?: expr + parenthesised?: boolean_literal + While: + test?: expr + body*: stmt + orelse*: stmt + With: + is_async?: boolean_literal + context_expr?: expr + optional_vars?: expr + body*: stmt + Yield: + value?: expr + parenthesised?: boolean_literal + YieldFrom: + value?: expr + parenthesised?: boolean_literal + StringPart: + prefix?: string_literal + text?: string_literal + s?: python_string_literal + TemplateWrite: + value?: expr + TemplateDottedNotation: + value?: expr + attr?: string_literal + ctx?: expr_context + parenthesised?: boolean_literal + Filter: + value?: expr + filter?: expr + parenthesised?: boolean_literal + PlaceHolder: + variable?: variable_literal + ctx?: expr_context + parenthesised?: boolean_literal + Await: + value?: expr + parenthesised?: boolean_literal + MatMult: {} + DictUnpacking: + value?: expr + KeyValuePair: + key?: expr + value?: expr + keyword: + arg?: string_literal + value?: expr + JoinedStr: + values*: expr + parenthesised?: boolean_literal + FormattedValue: + value?: expr + conversion?: string_literal + format_spec?: JoinedStr + parenthesised?: boolean_literal + AnnAssign: + value?: expr + annotation?: expr + target?: expr + AssignExpr: + target?: expr + value?: expr + parenthesised?: boolean_literal + SpecialOperation: + name?: string_literal + arguments*: expr + parenthesised?: boolean_literal + TemplateString: + prefix?: string_literal + values*: expr + parenthesised?: boolean_literal + JoinedTemplateString: + strings*: TemplateString + parenthesised?: boolean_literal + TemplateStringPart: + text?: string_literal + s?: python_string_literal + TypeAlias: + name?: expr + type_parameters*: type_parameter + value?: expr + ParamSpec: + name?: expr + default?: expr + TypeVar: + name?: expr + bound?: expr + default?: expr + TypeVarTuple: + name?: expr + default?: expr + string_literal: + bytes_literal: + integer_literal: + boolean_literal: + number_literal: + variable_literal: + python_string_literal: + none_literal: diff --git a/shared/yeast-macros/src/ast.rs b/shared/yeast-macros/src/ast.rs index 0f341fcef29d..d8097ede5dc0 100644 --- a/shared/yeast-macros/src/ast.rs +++ b/shared/yeast-macros/src/ast.rs @@ -214,6 +214,7 @@ named: assignment: left: identifier identifier: + structural: {} ", ) .unwrap() @@ -251,7 +252,7 @@ named: #[test] fn leaves_fieldless_structural_nodes_unchanged() { - let mut rule = crate::rule_parse::parse_rule(quote!((source) => (assignment))).unwrap(); + let mut rule = crate::rule_parse::parse_rule(quote!((source) => (structural))).unwrap(); rule.resolve_bare_leaf_content(&output_leaf_kinds()) .unwrap(); @@ -263,4 +264,28 @@ named: }; assert!(node.content.is_none()); } + + #[test] + fn allows_nested_fieldless_structural_nodes() { + let mut rule = + crate::rule_parse::parse_rule(quote!((source) => (assignment left: (structural)))) + .unwrap(); + rule.resolve_bare_leaf_content(&output_leaf_kinds()) + .unwrap(); + + let Replacement::Templates(templates) = rule.replacement else { + panic!("expected template replacement"); + }; + let [Template::Node(assignment)] = templates.as_slice() else { + panic!("expected one output node"); + }; + let [Field::Named { + value: Template::Node(structural), + .. + }] = assignment.fields.as_slice() + else { + panic!("expected one structural child"); + }; + assert!(structural.content.is_none()); + } } diff --git a/shared/yeast-schema/src/node_types_yaml.rs b/shared/yeast-schema/src/node_types_yaml.rs index a8d353fc3320..c3ca7e4e671a 100644 --- a/shared/yeast-schema/src/node_types_yaml.rs +++ b/shared/yeast-schema/src/node_types_yaml.rs @@ -477,12 +477,7 @@ pub fn leaf_kinds_from_yaml(yaml_input: &str) -> Result, String Ok(yaml .named .into_iter() - .filter_map(|(name, fields)| { - fields - .as_ref() - .is_none_or(BTreeMap::is_empty) - .then_some(name) - }) + .filter_map(|(name, fields)| fields.is_none().then_some(name)) .collect()) } @@ -841,7 +836,7 @@ named: .unwrap(); assert!(leaf_kinds.contains("identifier")); - assert!(leaf_kinds.contains("empty_fields")); + assert!(!leaf_kinds.contains("empty_fields")); assert!(!leaf_kinds.contains("call")); } diff --git a/shared/yeast/doc/node-types-yaml.md b/shared/yeast/doc/node-types-yaml.md index b887f5a82bbf..5f5789e31380 100644 --- a/shared/yeast/doc/node-types-yaml.md +++ b/shared/yeast/doc/node-types-yaml.md @@ -56,20 +56,28 @@ Members are resolved as named or unnamed using the ## Named nodes Named nodes are concrete AST node types. Each entry is a node kind mapping to -its fields. A node with no fields (a leaf token like `identifier`) uses an -empty value: +its fields. A value-carrying leaf token like `identifier` uses an empty value. A +fieldless structural node uses an explicit empty map: ```yaml named: identifier: - constant: + pass_statement: {} ``` ```json {"type": "identifier", "named": true, "fields": {}}, -{"type": "constant", "named": true, "fields": {}} +{"type": "pass_statement", "named": true, "fields": {}} ``` +The generated JSON is identical, but the YAML distinction lets `rules!` +recognize when a bare rule result should inherit leaf content. + +JSON node-types files do not preserve this distinction. Converting YAML to +JSON and back renders both forms as empty values, so explicit `{}` mappings for +fieldless structural nodes must be restored before using the converted YAML +with `rules!`. + ### Fields Each field has a name, a multiplicity suffix, and a list of allowed types.