Leverage Static Code Analysis Tools in Go
Static code analysis involves examining source code without executing it to find bugs, ensure coding standards, or extract meaningful information. Go provides robust packages for parsing and analyzing Go code, including go/parser, go/ast, and go/token.
By leveraging these packages, you can:
- Parse Go source code into an Abstract Syntax Tree (AST).
- Traverse the AST to identify code structures like functions, variables, and control flow statements.
- Map user queries to code structures using symbolic analysis.
Below is a comprehensive guide on how to implement static code analysis tools in Go, complete with code examples.
1. Parsing Go Code into an AST
The first step is to parse the source code into an AST using the go/parser package.
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"log"
"os"
)
func main() {
// Source code to parse (as a string)
src := `
package main
import "fmt"
// add returns the sum of two integers
func add(a int, b int) int {
return a + b
}
func main() {
sum := add(2, 3)
fmt.Println("Sum:", sum)
}
`
// Create a new token FileSet to hold position information
fset := token.NewFileSet()
// Parse the source code
f, err := parser.ParseFile(fset, "", src, parser.ParseComments)
if err != nil {
log.Fatal(err)
}
// You can now work with the AST 'f'
// For example, print the names of all functions
for _, decl := range f.Decls {
if fn, isFn := decl.(*ast.FuncDecl); isFn {
fmt.Printf("Found function: %s\n", fn.Name.Name)
}
}
}
Output:
Found function: add
Found function: main
In this example:
- We define a simple Go program as a string.
- Use
parser.ParseFile to parse the source code into an *ast.File.
- Iterate over
f.Decls to find all function declarations.
2. Traversing the AST
After parsing the code, traverse the AST to extract specific information using ast.Inspect.
// ... (continuation from the previous code)
// Traverse the AST to find all identifiers
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.BasicLit:
fmt.Printf("Found literal at %s: %s\n", fset.Position(x.Pos()), x.Value)
case *ast.CallExpr:
if fun, ok := x.Fun.(*ast.Ident); ok {
fmt.Printf("Found function call to '%s' at %s\n", fun.Name, fset.Position(x.Pos()))
}
}
return true
})
Output:
Found function: add
Found function: main
Found literal at /tmp/sandbox684196429/prog.go:14:17: 2
Found literal at /tmp/sandbox684196429/prog.go:14:20: 3
Found function call to 'add' at /tmp/sandbox684196429/prog.go:14:12
Found literal at /tmp/sandbox684196429/prog.go:15:24: "Sum:"
Found function call to 'Println' at /tmp/sandbox684196429/prog.go:15:12
In this snippet:
- Use
ast.Inspect to traverse all nodes.
- Check for types of interest (e.g.,
*ast.BasicLit for literals, *ast.CallExpr for function calls).
- Extract and print relevant information.
3. Identifying Functions, Variables, and Control Structures
You can extend the traversal to identify specific code structures.
3.1 Finding Function Declarations and Their Parameters
// Function to find functions and their parameters
func findFunctions(f *ast.File) {
ast.Inspect(f, func(n ast.Node) bool {
if fn, ok := n.(*ast.FuncDecl); ok {
fmt.Printf("Function: %s\n", fn.Name.Name)
if fn.Doc != nil {
fmt.Printf("Documentation: %s\n", fn.Doc.Text())
}
fmt.Println("Parameters:")
for _, param := range fn.Type.Params.List {
paramType := fmt.Sprintf("%s", param.Type)
for _, name := range param.Names {
fmt.Printf(" - %s %s\n", name.Name, paramType)
}
}
fmt.Println()
}
return true
})
}
// Call the function
findFunctions(f)
Output:
Function: add
Documentation: // add returns the sum of two integers
Parameters:
- a int
- b int
Function: main
Parameters:
3.2 Finding Variable Declarations
// Function to find variable declarations
func findVariables(f *ast.File) {
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.AssignStmt:
for _, lhs := range x.Lhs {
if ident, ok := lhs.(*ast.Ident); ok {
fmt.Printf("Variable assigned: %s\n", ident.Name)
}
}
case *ast.ValueSpec:
for _, name := range x.Names {
fmt.Printf("Variable declared: %s\n", name.Name)
}
}
return true
})
}
// Call the function
findVariables(f)
Output:
Variable assigned: sum
3.3 Identifying Control Structures
// Function to find control structures
func findControlStructures(f *ast.File) {
ast.Inspect(f, func(n ast.Node) bool {
switch n.(type) {
case *ast.IfStmt:
fmt.Printf("Found an if statement at %s\n", fset.Position(n.Pos()))
case *ast.ForStmt:
fmt.Printf("Found a for loop at %s\n", fset.Position(n.Pos()))
}
return true
})
}
// Call the function (no output in this example since there are no control structures)
findControlStructures(f)
4. Mapping User Queries to Code Structures Using Symbolic Analysis
To map user queries to code structures, you can:
- Define a set of query patterns or keywords (e.g., "Find all functions", "List variables").
- Traverse the AST and match the patterns.
Example: Simple Query System
// Function to process user queries
func processQuery(f *ast.File, query string) {
switch query {
case "functions":
findFunctions(f)
case "variables":
findVariables(f)
case "control structures":
findControlStructures(f)
default:
fmt.Println("Unknown query")
}
}
// Example usage
processQuery(f, os.Args[1])
Run the program with a query:
go run main.go functions
Output:
Function: add
Documentation: // add returns the sum of two integers
Parameters:
- a int
- b int
Function: main
Parameters:
5. Advanced Analysis with Symbol Tables and Type Information
For more in-depth analysis, you can use go/types to perform type checking and build symbol tables.
import (
"go/types"
"golang.org/x/tools/go/packages"
)
// Function to perform type checking and list variables with types
func listVariablesWithTypes(src string) {
cfg := &packages.Config{
Mode: packages.LoadSyntax,
Fset: token.NewFileSet(),
Tests: false,
}
pkgs, err := packages.Load(cfg, "command-line-arguments")
if err != nil {
log.Fatal(err)
}
for _, pkg := range pkgs {
scope := pkg.Types.Scope()
for _, name := range scope.Names() {
obj := scope.Lookup(name)
fmt.Printf("Name: %s, Type: %s\n", obj.Name(), obj.Type())
}
}
}
// Call the function
listVariablesWithTypes(src)
Note: The above code uses golang.org/x/tools/go/packages for loading and type checking packages. This allows you to perform more sophisticated analysis.
6. Using Third-Party Libraries
While Go's standard library is powerful, third-party libraries can simplify the process.
6.1 Using go-tools
go-tools is a collection of packages that provide enhanced utilities for code analysis.
import (
"golang.org/x/tools/go/ast/astutil"
)
// Example: Use astutil to manipulate ASTs
func manipulateAST(f *ast.File) {
// Example operation: rename a function
astutil.Apply(f, func(c *astutil.Cursor) bool {
if fn, ok := c.Node().(*ast.FuncDecl); ok {
if fn.Name.Name == "add" {
fn.Name.Name = "sum"
}
}
return true
}, nil)
}
7. Building a Static Analysis Tool
Combining all the above techniques, you can build a static analysis tool that:
- Accepts user queries.
- Parses and analyzes Go source code.
- Outputs information based on the analysis.
Example Tool Structure
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"log"
"os"
)
func main() {
if len(os.Args) < 3 {
fmt.Println("Usage: tool <query> <source_file.go>")
os.Exit(1)
}
query := os.Args[1]
filename := os.Args[2]
// Create a new token FileSet
fset := token.NewFileSet()
// Parse the source file
f, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)
if err != nil {
log.Fatal(err)
}
// Process the query
processQuery(f, fset, query)
}
func processQuery(f *ast.File, fset *token.FileSet, query string) {
switch query {
case "functions":
findFunctions(f)
case "variables":
findVariables(f)
case "control structures":
findControlStructures(f, fset)
default:
fmt.Println("Unknown query")
}
}
// ... include functions findFunctions, findVariables, findControlStructures
Usage:
go run tool.go functions example.go
Conclusion
By leveraging Go's go/parser, go/ast, and related packages, you can create powerful static code analysis tools. These tools can parse source code, extract ASTs, and perform symbolic analysis to map user queries to code structures.
This approach has many applications, including:
- Code inspections and linters.
- Automated code refactoring.
- Documentation generation.
- Code comprehension tools.
Further Resources