main.go 1.3 KB

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