Go
This page curates a list of example ast-grep rules to check and to rewrite Go code.
Find function declarations with names of certain pattern
Description
ast-grep can find function declarations by their names. But not all names can be matched by a meta variable pattern. For instance, you cannot use a meta variable pattern to find function declarations whose names start with a specific prefix, e.g. TestAbs
with the prefix Test
. Attempting Test$_
will fail because it is not a valid syntax.
Instead, you can use a YAML rule to use the regex
atomic rule.
YAML
id: test-functions
language: go
rule:
kind: function_declaration
has:
field: name
regex: Test.*
Example
package abs
import "testing"
func TestAbs(t *testing.T) {
got := Abs(-1)
if got != 1 {
t.Errorf("Abs(-1) = %d; want 1", got)
}
}
Contributed by
kevinkjt2000 on Discord.
Match Function Call in Golang
Description
One of the common questions of ast-grep is to match function calls in Golang.
A plain pattern like fmt.Println($A)
will not work. This is because Golang syntax also allows type conversions, e.g. int(3.14)
, that look like function calls.
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: func t() { fmt.Println($A) }
. Then, we can use the selector call_expression
to match only function calls.
YAML
id: match-function-call
language: go
rule:
pattern:
context: 'func t() { fmt.Println($A) }'
selector: call_expression
Example
func main() {
fmt.Println("OK")
}
Contributed by
Inspired by QuantumGhost from ast-grep/ast-grep#646