Skip to content

Find Struct Inheritance

Description

ast-grep's pattern is AST based. A code snippet like struct $SOMETHING: $INHERITS will not work because it does not have a correct AST structure. The correct pattern should spell out the full syntax like struct $SOMETHING: $INHERITS { $$$BODY; }.

Compare the ast structure below to see the difference, especially the ERROR node. You can also use the playground's pattern panel to debug.

shell
ERROR
  $SOMETHING
  base_class_clause
    $INHERITS
shell
struct_specifier
  $SOMETHING
  base_class_clause
    $INHERITS
  field_declaration_list
    field_declaration
      $$$BODY

If it is not possible to write a full pattern, YAML rule is a better choice.

Pattern

shell
ast-grep --lang cpp --pattern '
struct $SOMETHING: $INHERITS { $$$BODY; }'

Example

cpp
struct Bar: Baz {
  int a, b;
}

Contributed by

Inspired by this tweet

Made with ❤️ with Rust