go / expert
Snippet
Static AST Analysis for Identifying Exported Identifier Names via go/parser and go/ast
Parsing source code into an Abstract Syntax Tree using go/parser and walking AST nodes via ast.Inspect enables build-time static verification, custom linter rule creation, and automated code analysis directly within standard Go programs.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package mainimport ("fmt""go/ast""go/parser""go/token")func InspectExports(src string) ([]string, error) {fset := token.NewFileSet()node, err := parser.ParseFile(fset, "src.go", src, parser.SkipObjectResolution)if err != nil {return nil, err}var exports []stringast.Inspect(node, func(n ast.Node) bool {fn, ok := n.(*ast.FuncDecl)if ok && fn.Name.IsExported() {exports = append(exports, fn.Name.Name)}return true})return exports, nil}func main() {code := `package sample; func Internal() {}; func CalculateTotal() {}`names, _ := InspectExports(code)fmt.Printf("Exported Functions: %v\n", names)}
Breakdown
1
node, err := parser.ParseFile(...)
Parses raw Go source string into a structured AST representation.
2
ast.Inspect(node, func(n ast.Node) bool {
Traverses AST nodes depth-first, passing each syntax node to the callback function.
3
fn, ok := n.(*ast.FuncDecl)
Type-asserts the generic syntax node into a function declaration node.
4
fn.Name.IsExported()
Checks if the identifier starts with an uppercase letter indicating exported visibility.