kv.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package ast
  2. import (
  3. "strings"
  4. "github.com/tal-tech/go-zero/tools/goctl/api/parser/g4/gen/api"
  5. )
  6. // KvExpr describes key-value for api
  7. type KvExpr struct {
  8. Key Expr
  9. Value Expr
  10. DocExpr []Expr
  11. CommentExpr Expr
  12. }
  13. // VisitKvLit implements from api.BaseApiParserVisitor
  14. func (v *ApiVisitor) VisitKvLit(ctx *api.KvLitContext) interface{} {
  15. var kvExpr KvExpr
  16. kvExpr.Key = v.newExprWithToken(ctx.GetKey())
  17. commentExpr := v.getComment(ctx)
  18. if ctx.GetValue() != nil {
  19. valueText := ctx.GetValue().GetText()
  20. valueExpr := v.newExprWithToken(ctx.GetValue())
  21. if strings.Contains(valueText, "//") {
  22. if commentExpr == nil {
  23. commentExpr = v.newExprWithToken(ctx.GetValue())
  24. commentExpr.SetText("")
  25. }
  26. index := strings.Index(valueText, "//")
  27. commentExpr.SetText(valueText[index:])
  28. valueExpr.SetText(strings.TrimSpace(valueText[:index]))
  29. } else if strings.Contains(valueText, "/*") {
  30. if commentExpr == nil {
  31. commentExpr = v.newExprWithToken(ctx.GetValue())
  32. commentExpr.SetText("")
  33. }
  34. index := strings.Index(valueText, "/*")
  35. commentExpr.SetText(valueText[index:])
  36. valueExpr.SetText(strings.TrimSpace(valueText[:index]))
  37. }
  38. kvExpr.Value = valueExpr
  39. }
  40. kvExpr.DocExpr = v.getDoc(ctx)
  41. kvExpr.CommentExpr = commentExpr
  42. return &kvExpr
  43. }
  44. // Format provides a formatter for api command, now nothing to do
  45. func (k *KvExpr) Format() error {
  46. // todo
  47. return nil
  48. }
  49. // Equal compares whether the element literals in two KvExpr are equal
  50. func (k *KvExpr) Equal(v interface{}) bool {
  51. if v == nil {
  52. return false
  53. }
  54. kv, ok := v.(*KvExpr)
  55. if !ok {
  56. return false
  57. }
  58. if !EqualDoc(k, kv) {
  59. return false
  60. }
  61. return k.Key.Equal(kv.Key) && k.Value.Equal(kv.Value)
  62. }
  63. // Doc returns the document of KvExpr, like // some text
  64. func (k *KvExpr) Doc() []Expr {
  65. return k.DocExpr
  66. }
  67. // Comment returns the comment of KvExpr, like // some text
  68. func (k *KvExpr) Comment() Expr {
  69. return k.CommentExpr
  70. }