stmt.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package main
  2. import (
  3. "fmt"
  4. "go/ast"
  5. )
  6. func parseStmt(loc string, s ast.Stmt) {
  7. switch s := s.(type) {
  8. case *ast.CaseClause:
  9. parseCaseClause(loc, s)
  10. case *ast.DeclStmt:
  11. parseDeclStmt(loc, s)
  12. case *ast.ExprStmt, *ast.AssignStmt, *ast.ReturnStmt:
  13. // fmt.Printf("%s/(%T)\n", loc, s)
  14. case *ast.IfStmt:
  15. parseIfStmt(loc, s)
  16. case *ast.RangeStmt:
  17. parseRangeStmt(loc, s)
  18. case *ast.TypeSwitchStmt:
  19. parseTypeSwitchStmt(loc, s)
  20. default:
  21. fmt.Printf("Unhandled type %T\n", s)
  22. }
  23. }
  24. func parseCaseClause(loc string, s *ast.CaseClause) {
  25. loc += "/case"
  26. if s.Body == nil {
  27. // fmt.Printf("%s/(nil case)\n", loc)
  28. return
  29. }
  30. for _, rs := range s.Body {
  31. parseStmt(loc, rs)
  32. }
  33. }
  34. func parseDeclStmt(loc string, s *ast.DeclStmt) {
  35. loc += "/decl"
  36. switch d := s.Decl.(type) {
  37. case *ast.GenDecl:
  38. parseGenDecl(loc, d)
  39. default:
  40. fmt.Printf("DeclStmt: %T\n", d)
  41. }
  42. }
  43. func parseIfStmt(loc string, s *ast.IfStmt) {
  44. loc += "/if"
  45. // fmt.Println(loc)
  46. if s.Body == nil {
  47. fmt.Printf("%s/(nil if)\n", loc)
  48. } else {
  49. thenLoc := loc + "/then"
  50. for _, rs := range s.Body.List {
  51. parseStmt(thenLoc, rs)
  52. }
  53. }
  54. if s.Else == nil {
  55. // fmt.Printf("%s/(nil else)\n", loc)
  56. return
  57. } else {
  58. elseLoc := loc + "/else"
  59. for _, rs := range s.Else.(*ast.BlockStmt).List {
  60. parseStmt(elseLoc, rs)
  61. }
  62. }
  63. }
  64. func parseRangeStmt(loc string, s *ast.RangeStmt) {
  65. loc += "/range"
  66. // fmt.Println(loc)
  67. if s.Body == nil {
  68. fmt.Printf("%s/(nil range)\n", loc)
  69. return
  70. }
  71. for _, rs := range s.Body.List {
  72. parseStmt(loc, rs)
  73. }
  74. }
  75. func parseTypeSwitchStmt(loc string, s *ast.TypeSwitchStmt) {
  76. loc += "/(type)"
  77. // fmt.Println(loc)
  78. if s.Body == nil {
  79. fmt.Printf("%s/(nil body)\n", loc)
  80. return
  81. }
  82. for _, clause := range s.Body.List {
  83. body := clause.(*ast.CaseClause).Body
  84. if body == nil {
  85. //fmt.Printf("%s/empty clause\n", loc)
  86. continue
  87. }
  88. for _, rs := range body {
  89. parseStmt(loc, rs)
  90. }
  91. }
  92. }