Match Function Call in C
Description
One of the common questions of ast-grep is to match function calls in C.
A plain pattern like test($A)
will not work. This is because tree-sitter-c parse the code snippet into macro_type_specifier
, see the pattern output.
To avoid this ambiguity, ast-grep lets us write a contextual pattern, which is a pattern inside a larger code snippet. We can use context
to write a pattern like this: test($A);
. Then, we can use the selector call_expression
to match only function calls.
YAML
id: match-function-call
language: c
rule:
pattern:
context: $M($$$);
selector: call_expression
Example
#define test(x) (2*x)
int a = test(2);
int main(){
int b = test(2);
}
Caveat
Note, tree-sitter-c parses code differently when it receives code fragment. For example,
test(a)
is parsed asmacro_type_specifier
test(a);
is parsed asexpression_statement -> call_expression
int b = test(a)
is parsed asdeclaration -> init_declarator -> call_expression
The behavior is controlled by how the tree-sitter parser is written. And tree-sitter-c behaves differently from tree-sitter-cpp.
Please file issues on tree-sitter-c repo if you want to change the behavior. ast-grep will respect changes and decision from upstream authors.