main.go 1.3 KB

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