12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- // 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"
- )
- 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)
- }
- }
- }
|