Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

go
ast
communitycreator

How to use the Golang FileExports function in the ast package

Parmeshwar Patidar

The abstract syntax tree

The abstract syntax tree (AST) is an abstract representation of the source code. Here “abstract” means this representation discards all the information that does not change the semantic of the source code (braces, semicolons, parentheses, etc.).

Many code editors, linters, and formatters use AST to inspect or analyze the source code.

Listing all the exported function names with the ast package

In Go, a name is exported if it begins with a capital letter. Let’s use the ast package to get all the exported function names in the source code. The ast package provides the following function:

func FileExports(src *File) bool

FileExports trims the AST for a Go source file in place, such that only exported nodes/names remain. We can use this function and filter function declaration nodes that are exported.

The following function takes a source filename and mode exportOnly. if exportOnly is set to true, it returns exported functions names only. When set to false, all the function names are returned.

func funcNames(filename string, exportOnly bool) []string {
	fset := token.NewFileSet()
	file , _ := parser.ParseFile(fset, filename, nil, 0)
	if exportOnly {
		ast.FileExports(ast) // trim AST
	}

	funcNames := []string{}
	for _, decl := range ast.Decls {
		fn, ok := decl.(*ast.FuncDecl) // assert type of declaration
		if !ok {
			continue
		}
		funcNames = append(funcNames, fn.Name.Name)
	}
	return funcNames
}

The function does the following:

  • Creates a FileSet to store source file.
  • Parses the source file using ParseFile that returns *ast.File node.
  • Trims the AST based on exportedOnly mode.
  • Loops over all Declaration in the file.
  • Asserts if the node is of type function declaration. If not, it then checks the next declaration.
  • Otherwise, it accesses the name of the function and appends it to the result.
  • Returns the list of function names.

This is the complete source code, where we inspect the source.go file, which contains two exported and two unexported functions.

main.go
source.go
package main

import (
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
)

func main() {
	path := "source.go"

	names := funcNames(path, false)
	fmt.Println("All functions")
	printSlice(names)

	names = funcNames(path, true)
	fmt.Println("Exported functions:")
	printSlice(names)
}

func funcNames(filename string, exportOnly bool) []string {
    fset := token.NewFileSet()
    file , _ := parser.ParseFile(fset, filename, nil, 0)
    if exportOnly {
        ast.FileExports(file) // trim AST
    }

    funcNames := []string{}
    for _, decl := range file.Decls {
        fn, ok := decl.(*ast.FuncDecl) // assert type of declaration
        if !ok {
            continue
        }
        funcNames = append(funcNames, fn.Name.Name)
    }
    return funcNames
}
Use of FileExports function

You can learn more about this topic from the following:

RELATED TAGS

go
ast
communitycreator
RELATED COURSES

View all Courses

Keep Exploring