main.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Package main is a demo of go/parser and go/token.
  2. package main
  3. import (
  4. _ "embed"
  5. . "fmt"
  6. "go/ast"
  7. "go/parser"
  8. "go/token"
  9. "io/fs"
  10. "log"
  11. )
  12. type (
  13. psDefined bool
  14. psAlias = bool
  15. psSlice []bool
  16. psArray [4]bool
  17. psChan chan bool
  18. psMap map[bool]bool
  19. )
  20. // showPackageImports will usually show nothing
  21. func showPackageImports(pkg *ast.Package) {
  22. type funcScope bool
  23. Printf("Package imports (?):\n")
  24. for impName, imp := range pkg.Imports {
  25. type forScope bool
  26. Printf("- %s %#v\n", impName, imp)
  27. }
  28. }
  29. func showFileImports(imps []*ast.ImportSpec) {
  30. if len(imps) == 0 {
  31. return
  32. }
  33. Printf(" - Imports:\n")
  34. for _, imp := range imps {
  35. Printf(" - %s", imp.Path.Value)
  36. if imp.Name != nil {
  37. Printf(" as %s", imp.Name)
  38. }
  39. Println()
  40. }
  41. }
  42. func main() {
  43. const dir = "."
  44. fset := token.NewFileSet() // positions are relative to fset
  45. pkgs, err := parser.ParseDir(fset, dir, func(fi fs.FileInfo) bool { return true },
  46. parser.ParseComments|parser.AllErrors)
  47. if err != nil {
  48. log.Fatalf("parsing %s: %v", dir, err)
  49. }
  50. for pkgName, pkg := range pkgs {
  51. Printf("- Package %s:\n", pkgName)
  52. for fileName, file := range pkg.Files {
  53. Printf(" - %s = %s\n", fileName, file.Name)
  54. // showFileImports(file.Imports)
  55. parseFile(file)
  56. }
  57. }
  58. }