Skip to content

Commit b382cfe

Browse files
catalog: add Cpp struct inheritance example
fix ast-grep#675
1 parent a141039 commit b382cfe

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
## Find Struct Inheritance
2+
3+
* [Playground Link](/playground.html#eyJtb2RlIjoiUGF0Y2giLCJsYW5nIjoiY3BwIiwicXVlcnkiOiJzdHJ1Y3QgJFNPTUVUSElORzogICRJTkhFUklUU19GUk9NIHsgJCQkQk9EWTsgfSIsInJld3JpdGUiOiIiLCJzdHJpY3RuZXNzIjoic21hcnQiLCJzZWxlY3RvciI6IiIsImNvbmZpZyI6IiIsInNvdXJjZSI6InN0cnVjdCBGb286IEJhciB7fTtcblxuc3RydWN0IEJhcjogQmF6IHtcbiAgaW50IGEsIGI7XG59In0=)
4+
5+
### Description
6+
7+
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; }`.
8+
9+
Compare the ast structure below to see the difference, especially the `ERROR` node. You can also use the playground's pattern panel to debug.
10+
11+
:::code-group
12+
```shell [Wrong Pattern]
13+
ERROR
14+
$SOMETHING
15+
base_class_clause
16+
$INHERITS
17+
```
18+
19+
```shell [Correct Pattern]
20+
struct_specifier
21+
$SOMETHING
22+
base_class_clause
23+
$INHERITS
24+
field_declaration_list
25+
field_declaration
26+
$$$BODY
27+
```
28+
:::
29+
30+
If it is not possible to write a full pattern, [YAML rule](/guide/rule-config.html) is a better choice.
31+
32+
33+
### Pattern
34+
```shell
35+
ast-grep --lang cpp --pattern '
36+
struct $SOMETHING: $INHERITS { $$$BODY; }'
37+
```
38+
39+
### Example
40+
41+
<!-- highlight matched code in curly-brace {lineNum} -->
42+
```cpp {1-3}
43+
struct Bar: Baz {
44+
int a, b;
45+
}
46+
```
47+
48+
### Contributed by
49+
Inspired by this [tweet](https://x.com/techno_bog/status/1885421768384331871)

website/catalog/cpp/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,4 @@ Cpp is a superset of C, so you can reuse Cpp rules with C code. The [`languageGl
77
:::
88

99
<!--@include: ./fix-format-vuln.md-->
10+
<!--@include: ./find-struct-inheritance.md-->

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy