// Package main is a demo of go/parser and go/token. package main import ( _ "embed" . "fmt" "go/ast" "go/parser" "go/token" "io/fs" "log" ) //go:embed main.go var mainFile string type ( psDefined bool psAlias = bool psSlice []bool psArray [4]bool psChan chan bool psMap map[bool]bool ) // showPackageImports will usually show nothing func showPackageImports(pkg *ast.Package) { type funcScope bool Printf("Package imports (?):\n") for impName, imp := range pkg.Imports { type forScope bool Printf("- %s %#v\n", impName, imp) } } func showFileImports(imps []*ast.ImportSpec) { if len(imps) == 0 { return } Printf(" - Imports:\n") for _, imp := range imps { Printf(" - %s", imp.Path.Value) if imp.Name != nil { Printf(" as %s", imp.Name) } Println() } } func main() { const dir = "." fset := token.NewFileSet() // positions are relative to fset pkgs, err := parser.ParseDir(fset, dir, func(fi fs.FileInfo) bool { return true }, parser.ParseComments|parser.AllErrors) if err != nil { log.Fatalf("parsing %s: %v", dir, err) } for pkgName, pkg := range pkgs { Printf("- Package %s:\n", pkgName) for fileName, file := range pkg.Files { Printf(" - %s = %s\n", fileName, file.Name) // showFileImports(file.Imports) parseFile(file) } } }