parser.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. package parser
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "unicode"
  6. "github.com/tal-tech/go-zero/tools/goctl/api/parser/g4/ast"
  7. "github.com/tal-tech/go-zero/tools/goctl/api/parser/g4/gen/api"
  8. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  9. )
  10. type parser struct {
  11. ast *ast.Api
  12. spec *spec.ApiSpec
  13. }
  14. // Parse parses the api file
  15. func Parse(filename string) (*spec.ApiSpec, error) {
  16. astParser := ast.NewParser(ast.WithParserPrefix(filepath.Base(filename)))
  17. ast, err := astParser.Parse(filename)
  18. if err != nil {
  19. return nil, err
  20. }
  21. spec := new(spec.ApiSpec)
  22. p := parser{ast: ast, spec: spec}
  23. err = p.convert2Spec()
  24. if err != nil {
  25. return nil, err
  26. }
  27. return spec, nil
  28. }
  29. // ParseContent parses the api content
  30. func ParseContent(content string) (*spec.ApiSpec, error) {
  31. astParser := ast.NewParser()
  32. ast, err := astParser.ParseContent(content)
  33. if err != nil {
  34. return nil, err
  35. }
  36. spec := new(spec.ApiSpec)
  37. p := parser{ast: ast, spec: spec}
  38. err = p.convert2Spec()
  39. if err != nil {
  40. return nil, err
  41. }
  42. return spec, nil
  43. }
  44. func (p parser) convert2Spec() error {
  45. p.fillInfo()
  46. p.fillSyntax()
  47. p.fillImport()
  48. err := p.fillTypes()
  49. if err != nil {
  50. return err
  51. }
  52. return p.fillService()
  53. }
  54. func (p parser) fillInfo() {
  55. properties := make(map[string]string, 0)
  56. if p.ast.Info != nil {
  57. p.spec.Info = spec.Info{}
  58. for _, kv := range p.ast.Info.Kvs {
  59. properties[kv.Key.Text()] = kv.Value.Text()
  60. }
  61. }
  62. p.spec.Info.Properties = properties
  63. }
  64. func (p parser) fillSyntax() {
  65. if p.ast.Syntax != nil {
  66. p.spec.Syntax = spec.ApiSyntax{Version: p.ast.Syntax.Version.Text()}
  67. }
  68. }
  69. func (p parser) fillImport() {
  70. if len(p.ast.Import) > 0 {
  71. for _, item := range p.ast.Import {
  72. p.spec.Imports = append(p.spec.Imports, spec.Import{Value: item.Value.Text()})
  73. }
  74. }
  75. }
  76. func (p parser) fillTypes() error {
  77. for _, item := range p.ast.Type {
  78. switch v := (item).(type) {
  79. case *ast.TypeStruct:
  80. var members []spec.Member
  81. for _, item := range v.Fields {
  82. members = append(members, p.fieldToMember(item))
  83. }
  84. p.spec.Types = append(p.spec.Types, spec.DefineStruct{
  85. RawName: v.Name.Text(),
  86. Members: members,
  87. Docs: p.stringExprs(v.Doc()),
  88. })
  89. default:
  90. return fmt.Errorf("unknown type %+v", v)
  91. }
  92. }
  93. var types []spec.Type
  94. for _, item := range p.spec.Types {
  95. switch v := (item).(type) {
  96. case spec.DefineStruct:
  97. var members []spec.Member
  98. for _, member := range v.Members {
  99. switch v := member.Type.(type) {
  100. case spec.DefineStruct:
  101. tp, err := p.findDefinedType(v.RawName)
  102. if err != nil {
  103. return err
  104. }
  105. member.Type = *tp
  106. }
  107. members = append(members, member)
  108. }
  109. v.Members = members
  110. types = append(types, v)
  111. default:
  112. return fmt.Errorf("unknown type %+v", v)
  113. }
  114. }
  115. p.spec.Types = types
  116. return nil
  117. }
  118. func (p parser) findDefinedType(name string) (*spec.Type, error) {
  119. for _, item := range p.spec.Types {
  120. if _, ok := item.(spec.DefineStruct); ok {
  121. if item.Name() == name {
  122. return &item, nil
  123. }
  124. }
  125. }
  126. return nil, fmt.Errorf("type %s not defined", name)
  127. }
  128. func (p parser) fieldToMember(field *ast.TypeField) spec.Member {
  129. name := ""
  130. tag := ""
  131. if !field.IsAnonymous {
  132. name = field.Name.Text()
  133. if field.Tag == nil {
  134. panic(fmt.Sprintf("error: line %d:%d field %s has no tag", field.Name.Line(), field.Name.Column(),
  135. field.Name.Text()))
  136. }
  137. tag = field.Tag.Text()
  138. }
  139. return spec.Member{
  140. Name: name,
  141. Type: p.astTypeToSpec(field.DataType),
  142. Tag: tag,
  143. Comment: p.commentExprs(field.Comment()),
  144. Docs: p.stringExprs(field.Doc()),
  145. IsInline: field.IsAnonymous,
  146. }
  147. }
  148. func (p parser) astTypeToSpec(in ast.DataType) spec.Type {
  149. switch v := (in).(type) {
  150. case *ast.Literal:
  151. raw := v.Literal.Text()
  152. if api.IsBasicType(raw) {
  153. return spec.PrimitiveType{RawName: raw}
  154. }
  155. return spec.DefineStruct{RawName: raw}
  156. case *ast.Interface:
  157. return spec.InterfaceType{RawName: v.Literal.Text()}
  158. case *ast.Map:
  159. return spec.MapType{RawName: v.MapExpr.Text(), Key: v.Key.Text(), Value: p.astTypeToSpec(v.Value)}
  160. case *ast.Array:
  161. return spec.ArrayType{RawName: v.ArrayExpr.Text(), Value: p.astTypeToSpec(v.Literal)}
  162. case *ast.Pointer:
  163. raw := v.Name.Text()
  164. if api.IsBasicType(raw) {
  165. return spec.PointerType{RawName: v.PointerExpr.Text(), Type: spec.PrimitiveType{RawName: raw}}
  166. }
  167. return spec.PointerType{RawName: v.PointerExpr.Text(), Type: spec.DefineStruct{RawName: raw}}
  168. }
  169. panic(fmt.Sprintf("unspported type %+v", in))
  170. }
  171. func (p parser) stringExprs(docs []ast.Expr) []string {
  172. var result []string
  173. for _, item := range docs {
  174. result = append(result, item.Text())
  175. }
  176. return result
  177. }
  178. func (p parser) commentExprs(comment ast.Expr) string {
  179. if comment == nil {
  180. return ""
  181. }
  182. return comment.Text()
  183. }
  184. func (p parser) fillService() error {
  185. var groups []spec.Group
  186. for _, item := range p.ast.Service {
  187. var group spec.Group
  188. p.fillAtServer(item, &group)
  189. for _, astRoute := range item.ServiceApi.ServiceRoute {
  190. route := spec.Route{
  191. AtServerAnnotation: spec.Annotation{},
  192. Method: astRoute.Route.Method.Text(),
  193. Path: astRoute.Route.Path.Text(),
  194. }
  195. if astRoute.AtHandler != nil {
  196. route.Handler = astRoute.AtHandler.Name.Text()
  197. }
  198. err := p.fillRouteAtServer(astRoute, &route)
  199. if err != nil {
  200. return err
  201. }
  202. if astRoute.Route.Req != nil {
  203. route.RequestType = p.astTypeToSpec(astRoute.Route.Req.Name)
  204. }
  205. if astRoute.Route.Reply != nil {
  206. route.ResponseType = p.astTypeToSpec(astRoute.Route.Reply.Name)
  207. }
  208. if astRoute.AtDoc != nil {
  209. properties := make(map[string]string, 0)
  210. for _, kv := range astRoute.AtDoc.Kv {
  211. properties[kv.Key.Text()] = kv.Value.Text()
  212. }
  213. route.AtDoc.Properties = properties
  214. if astRoute.AtDoc.LineDoc != nil {
  215. route.AtDoc.Text = astRoute.AtDoc.LineDoc.Text()
  216. }
  217. }
  218. err = p.fillRouteType(&route)
  219. if err != nil {
  220. return err
  221. }
  222. group.Routes = append(group.Routes, route)
  223. name := item.ServiceApi.Name.Text()
  224. if len(p.spec.Service.Name) > 0 && p.spec.Service.Name != name {
  225. return fmt.Errorf("mulit service name defined %s and %s", name, p.spec.Service.Name)
  226. }
  227. p.spec.Service.Name = name
  228. }
  229. groups = append(groups, group)
  230. }
  231. p.spec.Service.Groups = groups
  232. return nil
  233. }
  234. func (p parser) fillRouteAtServer(astRoute *ast.ServiceRoute, route *spec.Route) error {
  235. if astRoute.AtServer != nil {
  236. properties := make(map[string]string, 0)
  237. for _, kv := range astRoute.AtServer.Kv {
  238. properties[kv.Key.Text()] = kv.Value.Text()
  239. }
  240. route.AtServerAnnotation.Properties = properties
  241. if len(route.Handler) == 0 {
  242. route.Handler = properties["handler"]
  243. }
  244. if len(route.Handler) == 0 {
  245. return fmt.Errorf("missing handler annotation for %q", route.Path)
  246. }
  247. for _, char := range route.Handler {
  248. if !unicode.IsDigit(char) && !unicode.IsLetter(char) {
  249. return fmt.Errorf("route [%s] handler [%s] invalid, handler name should only contains letter or digit",
  250. route.Path, route.Handler)
  251. }
  252. }
  253. }
  254. return nil
  255. }
  256. func (p parser) fillAtServer(item *ast.Service, group *spec.Group) {
  257. if item.AtServer != nil {
  258. properties := make(map[string]string, 0)
  259. for _, kv := range item.AtServer.Kv {
  260. properties[kv.Key.Text()] = kv.Value.Text()
  261. }
  262. group.Annotation.Properties = properties
  263. }
  264. }
  265. func (p parser) fillRouteType(route *spec.Route) error {
  266. if route.RequestType != nil {
  267. switch route.RequestType.(type) {
  268. case spec.DefineStruct:
  269. tp, err := p.findDefinedType(route.RequestType.Name())
  270. if err != nil {
  271. return err
  272. }
  273. route.RequestType = *tp
  274. }
  275. }
  276. if route.ResponseType != nil {
  277. switch route.ResponseType.(type) {
  278. case spec.DefineStruct:
  279. tp, err := p.findDefinedType(route.ResponseType.Name())
  280. if err != nil {
  281. return err
  282. }
  283. route.ResponseType = *tp
  284. }
  285. }
  286. return nil
  287. }