sdt_walker.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package hhc_ast
  2. import (
  3. "git.swzry.com/zry/go-hhc-cli/hhc_common"
  4. )
  5. type SDTWalker struct {
  6. root *SyntaxDefinitionTreeRoot
  7. current SyntaxDefTreeNode
  8. ctx *SDTWalkContext
  9. currentError hhc_common.SDTWalkError
  10. depthCount uint32
  11. actualDepth uint32
  12. }
  13. func NewSDTWalker(rootnode *SyntaxDefinitionTreeRoot) *SDTWalker {
  14. w := &SDTWalker{
  15. root: rootnode,
  16. current: rootnode,
  17. ctx: &SDTWalkContext{ASTNodes: []ASTNode{}},
  18. currentError: nil,
  19. depthCount: 0,
  20. actualDepth: 0,
  21. }
  22. return w
  23. }
  24. func (w *SDTWalker) Reset() {
  25. w.current = w.root
  26. w.ctx = &SDTWalkContext{ASTNodes: []ASTNode{}}
  27. w.currentError = nil
  28. w.depthCount = 0
  29. w.actualDepth = 0
  30. }
  31. func (w *SDTWalker) NextStep(token string) bool {
  32. //fmt.Println("On NextStep, dc=", w.depthCount, "ad=", w.actualDepth)
  33. w.depthCount++
  34. if w.depthCount == w.actualDepth+1 {
  35. nc, serr := w.current.WalkNext(w.ctx, token)
  36. if serr != nil {
  37. w.currentError = serr
  38. return false
  39. }
  40. w.current = nc
  41. w.actualDepth++
  42. w.currentError = nil
  43. return true
  44. }
  45. return false
  46. }
  47. func (w *SDTWalker) Back() bool {
  48. //fmt.Println("On Back, dc=", w.depthCount, "ad=", w.actualDepth)
  49. if w.depthCount > 0 {
  50. w.depthCount--
  51. if w.depthCount < w.actualDepth {
  52. nc, serr := w.current.Fallback(w.ctx)
  53. if serr != nil {
  54. switch serr.(type) {
  55. case hhc_common.SDTWalkError_RootNodeCannotFallback:
  56. w.Reset()
  57. return false
  58. }
  59. w.currentError = serr
  60. return false
  61. }
  62. w.current = nc
  63. w.actualDepth--
  64. w.currentError = nil
  65. return true
  66. }
  67. }
  68. return false
  69. }
  70. func (w *SDTWalker) GetHelps(prefix string) []hhc_common.SDTHelpInfo {
  71. return w.current.GetHelps(prefix)
  72. }
  73. func (w *SDTWalker) GetContext() *SDTWalkContext {
  74. return w.ctx
  75. }
  76. func (w *SDTWalker) GetError() hhc_common.SDTWalkError {
  77. return w.currentError
  78. }
  79. func (w *SDTWalker) HasError() bool {
  80. return w.currentError != nil
  81. }
  82. func (w *SDTWalker) IsSync() bool {
  83. return w.actualDepth == w.actualDepth
  84. }
  85. func (w *SDTWalker) IsEnd() bool {
  86. return w.current.IsEnd()
  87. }
  88. func (w *SDTWalker) GetEndExecute() (bool, ExecuteFunc) {
  89. if w.IsEnd() {
  90. e := w.current.(*SDTNode_End)
  91. if e != nil {
  92. ef := e.Exec
  93. return true, ef
  94. } else {
  95. return false, nil
  96. }
  97. } else {
  98. return false, nil
  99. }
  100. }