parser.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. package parser
  2. import (
  3. "errors"
  4. "fmt"
  5. "go/token"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "unicode"
  10. "unicode/utf8"
  11. "github.com/emicklei/proto"
  12. )
  13. type (
  14. // DefaultProtoParser types a empty struct
  15. DefaultProtoParser struct{}
  16. )
  17. // NewDefaultProtoParser creates a new instance
  18. func NewDefaultProtoParser() *DefaultProtoParser {
  19. return &DefaultProtoParser{}
  20. }
  21. // Parse provides to parse the proto file into a golang structure,
  22. // which is convenient for subsequent rpc generation and use
  23. func (p *DefaultProtoParser) Parse(src string) (Proto, error) {
  24. var ret Proto
  25. abs, err := filepath.Abs(src)
  26. if err != nil {
  27. return Proto{}, err
  28. }
  29. r, err := os.Open(abs)
  30. if err != nil {
  31. return ret, err
  32. }
  33. defer r.Close()
  34. parser := proto.NewParser(r)
  35. set, err := parser.Parse()
  36. if err != nil {
  37. return ret, err
  38. }
  39. var serviceList []Service
  40. proto.Walk(
  41. set,
  42. proto.WithImport(func(i *proto.Import) {
  43. ret.Import = append(ret.Import, Import{Import: i})
  44. }),
  45. proto.WithMessage(func(message *proto.Message) {
  46. ret.Message = append(ret.Message, Message{Message: message})
  47. }),
  48. proto.WithPackage(func(p *proto.Package) {
  49. ret.Package = Package{Package: p}
  50. }),
  51. proto.WithService(func(service *proto.Service) {
  52. serv := Service{Service: service}
  53. elements := service.Elements
  54. for _, el := range elements {
  55. v, _ := el.(*proto.RPC)
  56. if v == nil {
  57. continue
  58. }
  59. serv.RPC = append(serv.RPC, &RPC{RPC: v})
  60. }
  61. serviceList = append(serviceList, serv)
  62. }),
  63. proto.WithOption(func(option *proto.Option) {
  64. if option.Name == "go_package" {
  65. ret.GoPackage = option.Constant.Source
  66. }
  67. }),
  68. )
  69. if len(serviceList) == 0 {
  70. return ret, errors.New("rpc service not found")
  71. }
  72. if len(serviceList) > 1 {
  73. return ret, errors.New("only one service expected")
  74. }
  75. service := serviceList[0]
  76. name := filepath.Base(abs)
  77. for _, rpc := range service.RPC {
  78. if strings.Contains(rpc.RequestType, ".") {
  79. return ret, fmt.Errorf("line %v:%v, request type must defined in %s", rpc.Position.Line, rpc.Position.Column, name)
  80. }
  81. if strings.Contains(rpc.ReturnsType, ".") {
  82. return ret, fmt.Errorf("line %v:%v, returns type must defined in %s", rpc.Position.Line, rpc.Position.Column, name)
  83. }
  84. }
  85. if len(ret.GoPackage) == 0 {
  86. ret.GoPackage = ret.Package.Name
  87. }
  88. ret.PbPackage = GoSanitized(filepath.Base(ret.GoPackage))
  89. ret.Src = abs
  90. ret.Name = name
  91. ret.Service = service
  92. return ret, nil
  93. }
  94. // GoSanitized copy from protobuf, for more information, please see google.golang.org/protobuf@v1.25.0/internal/strs/strings.go:71
  95. func GoSanitized(s string) string {
  96. // Sanitize the input to the set of valid characters,
  97. // which must be '_' or be in the Unicode L or N categories.
  98. s = strings.Map(func(r rune) rune {
  99. if unicode.IsLetter(r) || unicode.IsDigit(r) {
  100. return r
  101. }
  102. return '_'
  103. }, s)
  104. // Prepend '_' in the event of a Go keyword conflict or if
  105. // the identifier is invalid (does not start in the Unicode L category).
  106. r, _ := utf8.DecodeRuneInString(s)
  107. if token.Lookup(s).IsKeyword() || !unicode.IsLetter(r) {
  108. return "_" + s
  109. }
  110. return s
  111. }
  112. // CamelCase copy from protobuf, for more information, please see github.com/golang/protobuf@v1.4.2/protoc-gen-go/generator/generator.go:2648
  113. func CamelCase(s string) string {
  114. if s == "" {
  115. return ""
  116. }
  117. t := make([]byte, 0, 32)
  118. i := 0
  119. if s[0] == '_' {
  120. // Need a capital letter; drop the '_'.
  121. t = append(t, 'X')
  122. i++
  123. }
  124. // Invariant: if the next letter is lower case, it must be converted
  125. // to upper case.
  126. // That is, we process a word at a time, where words are marked by _ or
  127. // upper case letter. Digits are treated as words.
  128. for ; i < len(s); i++ {
  129. c := s[i]
  130. if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) {
  131. continue // Skip the underscore in s.
  132. }
  133. if isASCIIDigit(c) {
  134. t = append(t, c)
  135. continue
  136. }
  137. // Assume we have a letter now - if not, it's a bogus identifier.
  138. // The next word is a sequence of characters that must start upper case.
  139. if isASCIILower(c) {
  140. c ^= ' ' // Make it a capital letter.
  141. }
  142. t = append(t, c) // Guaranteed not lower case.
  143. // Accept lower case sequence that follows.
  144. for i+1 < len(s) && isASCIILower(s[i+1]) {
  145. i++
  146. t = append(t, s[i])
  147. }
  148. }
  149. return string(t)
  150. }
  151. func isASCIILower(c byte) bool {
  152. return 'a' <= c && c <= 'z'
  153. }
  154. // Is c an ASCII digit?
  155. func isASCIIDigit(c byte) bool {
  156. return '0' <= c && c <= '9'
  157. }