apiparser.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. package ast
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "path"
  6. "path/filepath"
  7. "strings"
  8. "github.com/zeromicro/antlr"
  9. "github.com/zeromicro/go-zero/tools/goctl/api/parser/g4/gen/api"
  10. "github.com/zeromicro/go-zero/tools/goctl/util/console"
  11. )
  12. type (
  13. // Parser provides api parsing capabilities
  14. Parser struct {
  15. linePrefix string
  16. debug bool
  17. log console.Console
  18. antlr.DefaultErrorListener
  19. src string
  20. }
  21. // ParserOption defines an function with argument Parser
  22. ParserOption func(p *Parser)
  23. )
  24. // NewParser creates an instance for Parser
  25. func NewParser(options ...ParserOption) *Parser {
  26. p := &Parser{
  27. log: console.NewColorConsole(),
  28. }
  29. for _, opt := range options {
  30. opt(p)
  31. }
  32. return p
  33. }
  34. // Accept can parse any terminalNode of api tree by fn.
  35. // -- for debug
  36. func (p *Parser) Accept(fn func(p *api.ApiParserParser, visitor *ApiVisitor) interface{}, content string) (v interface{}, err error) {
  37. defer func() {
  38. p := recover()
  39. if p != nil {
  40. switch e := p.(type) {
  41. case error:
  42. err = e
  43. default:
  44. err = fmt.Errorf("%+v", p)
  45. }
  46. }
  47. }()
  48. inputStream := antlr.NewInputStream(content)
  49. lexer := api.NewApiParserLexer(inputStream)
  50. lexer.RemoveErrorListeners()
  51. tokens := antlr.NewCommonTokenStream(lexer, antlr.LexerDefaultTokenChannel)
  52. apiParser := api.NewApiParserParser(tokens)
  53. apiParser.RemoveErrorListeners()
  54. apiParser.AddErrorListener(p)
  55. var visitorOptions []VisitorOption
  56. visitorOptions = append(visitorOptions, WithVisitorPrefix(p.linePrefix))
  57. if p.debug {
  58. visitorOptions = append(visitorOptions, WithVisitorDebug())
  59. }
  60. visitor := NewApiVisitor(visitorOptions...)
  61. v = fn(apiParser, visitor)
  62. return
  63. }
  64. // Parse is used to parse the api from the specified file name
  65. func (p *Parser) Parse(filename string) (*Api, error) {
  66. abs, err := filepath.Abs(filename)
  67. if err != nil {
  68. return nil, err
  69. }
  70. p.src = abs
  71. data, err := p.readContent(filename)
  72. if err != nil {
  73. return nil, err
  74. }
  75. return p.parse(filename, data)
  76. }
  77. // ParseContent is used to parse the api from the specified content
  78. func (p *Parser) ParseContent(content string, filename ...string) (*Api, error) {
  79. var f string
  80. if len(filename) > 0 {
  81. f = filename[0]
  82. abs, err := filepath.Abs(f)
  83. if err != nil {
  84. return nil, err
  85. }
  86. p.src = abs
  87. }
  88. return p.parse(f, content)
  89. }
  90. // parse is used to parse api from the content
  91. // filename is only used to mark the file where the error is located
  92. func (p *Parser) parse(filename, content string) (*Api, error) {
  93. root, err := p.invoke(filename, content)
  94. if err != nil {
  95. return nil, err
  96. }
  97. var apiAstList []*Api
  98. apiAstList = append(apiAstList, root)
  99. for _, imp := range root.Import {
  100. dir := filepath.Dir(p.src)
  101. imp := filepath.Join(dir, imp.Value.Text())
  102. data, err := p.readContent(imp)
  103. if err != nil {
  104. return nil, err
  105. }
  106. nestedApi, err := p.invoke(imp, data)
  107. if err != nil {
  108. return nil, err
  109. }
  110. err = p.valid(root, nestedApi)
  111. if err != nil {
  112. return nil, err
  113. }
  114. apiAstList = append(apiAstList, nestedApi)
  115. }
  116. err = p.checkTypeDeclaration(apiAstList)
  117. if err != nil {
  118. return nil, err
  119. }
  120. allApi := p.memberFill(apiAstList)
  121. return allApi, nil
  122. }
  123. func (p *Parser) invoke(linePrefix, content string) (v *Api, err error) {
  124. defer func() {
  125. p := recover()
  126. if p != nil {
  127. switch e := p.(type) {
  128. case error:
  129. err = e
  130. default:
  131. err = fmt.Errorf("%+v", p)
  132. }
  133. }
  134. }()
  135. if linePrefix != "" {
  136. p.linePrefix = linePrefix
  137. }
  138. inputStream := antlr.NewInputStream(content)
  139. lexer := api.NewApiParserLexer(inputStream)
  140. lexer.RemoveErrorListeners()
  141. tokens := antlr.NewCommonTokenStream(lexer, antlr.LexerDefaultTokenChannel)
  142. apiParser := api.NewApiParserParser(tokens)
  143. apiParser.RemoveErrorListeners()
  144. apiParser.AddErrorListener(p)
  145. var visitorOptions []VisitorOption
  146. visitorOptions = append(visitorOptions, WithVisitorPrefix(p.linePrefix))
  147. if p.debug {
  148. visitorOptions = append(visitorOptions, WithVisitorDebug())
  149. }
  150. visitor := NewApiVisitor(visitorOptions...)
  151. v = apiParser.Api().Accept(visitor).(*Api)
  152. v.LinePrefix = p.linePrefix
  153. return
  154. }
  155. func (p *Parser) valid(mainApi, nestedApi *Api) error {
  156. err := p.nestedApiCheck(mainApi, nestedApi)
  157. if err != nil {
  158. return err
  159. }
  160. mainHandlerMap := make(map[string]PlaceHolder)
  161. mainRouteMap := make(map[string]PlaceHolder)
  162. mainTypeMap := make(map[string]PlaceHolder)
  163. routeMap := func(list []*ServiceRoute) (map[string]PlaceHolder, map[string]PlaceHolder) {
  164. handlerMap := make(map[string]PlaceHolder)
  165. routeMap := make(map[string]PlaceHolder)
  166. for _, g := range list {
  167. handler := g.GetHandler()
  168. if handler.IsNotNil() {
  169. handlerName := handler.Text()
  170. handlerMap[handlerName] = Holder
  171. route := fmt.Sprintf("%s://%s", g.Route.Method.Text(), g.Route.Path.Text())
  172. routeMap[route] = Holder
  173. }
  174. }
  175. return handlerMap, routeMap
  176. }
  177. for _, each := range mainApi.Service {
  178. h, r := routeMap(each.ServiceApi.ServiceRoute)
  179. for k, v := range h {
  180. mainHandlerMap[k] = v
  181. }
  182. for k, v := range r {
  183. mainRouteMap[k] = v
  184. }
  185. }
  186. for _, each := range mainApi.Type {
  187. mainTypeMap[each.NameExpr().Text()] = Holder
  188. }
  189. // duplicate route check
  190. err = p.duplicateRouteCheck(nestedApi, mainHandlerMap, mainRouteMap)
  191. if err != nil {
  192. return err
  193. }
  194. // duplicate type check
  195. for _, each := range nestedApi.Type {
  196. if _, ok := mainTypeMap[each.NameExpr().Text()]; ok {
  197. return fmt.Errorf("%s line %d:%d duplicate type declaration '%s'",
  198. nestedApi.LinePrefix, each.NameExpr().Line(), each.NameExpr().Column(), each.NameExpr().Text())
  199. }
  200. }
  201. return nil
  202. }
  203. func (p *Parser) duplicateRouteCheck(nestedApi *Api, mainHandlerMap, mainRouteMap map[string]PlaceHolder) error {
  204. for _, each := range nestedApi.Service {
  205. var prefix, group string
  206. if each.AtServer != nil {
  207. p := each.AtServer.Kv.Get(prefixKey)
  208. if p != nil {
  209. prefix = p.Text()
  210. }
  211. g := each.AtServer.Kv.Get(groupKey)
  212. if p != nil {
  213. group = g.Text()
  214. }
  215. }
  216. for _, r := range each.ServiceApi.ServiceRoute {
  217. handler := r.GetHandler()
  218. if !handler.IsNotNil() {
  219. return fmt.Errorf("%s handler not exist near line %d", nestedApi.LinePrefix, r.Route.Method.Line())
  220. }
  221. handlerKey := handler.Text()
  222. if len(group) > 0 {
  223. handlerKey = fmt.Sprintf("%s/%s", group, handler.Text())
  224. }
  225. if _, ok := mainHandlerMap[handlerKey]; ok {
  226. return fmt.Errorf("%s line %d:%d duplicate handler '%s'",
  227. nestedApi.LinePrefix, handler.Line(), handler.Column(), handlerKey)
  228. }
  229. p := fmt.Sprintf("%s://%s", r.Route.Method.Text(), path.Join(prefix, r.Route.Path.Text()))
  230. if _, ok := mainRouteMap[p]; ok {
  231. return fmt.Errorf("%s line %d:%d duplicate route '%s'",
  232. nestedApi.LinePrefix, r.Route.Method.Line(), r.Route.Method.Column(), r.Route.Method.Text()+" "+r.Route.Path.Text())
  233. }
  234. }
  235. }
  236. return nil
  237. }
  238. func (p *Parser) nestedApiCheck(mainApi, nestedApi *Api) error {
  239. if len(nestedApi.Import) > 0 {
  240. importToken := nestedApi.Import[0].Import
  241. return fmt.Errorf("%s line %d:%d the nested api does not support import",
  242. nestedApi.LinePrefix, importToken.Line(), importToken.Column())
  243. }
  244. if mainApi.Syntax != nil && nestedApi.Syntax != nil {
  245. if mainApi.Syntax.Version.Text() != nestedApi.Syntax.Version.Text() {
  246. syntaxToken := nestedApi.Syntax.Syntax
  247. return fmt.Errorf("%s line %d:%d multiple syntax declaration, expecting syntax '%s', but found '%s'",
  248. nestedApi.LinePrefix, syntaxToken.Line(), syntaxToken.Column(), mainApi.Syntax.Version.Text(), nestedApi.Syntax.Version.Text())
  249. }
  250. }
  251. if len(mainApi.Service) > 0 {
  252. mainService := mainApi.Service[0]
  253. for _, service := range nestedApi.Service {
  254. if mainService.ServiceApi.Name.Text() != service.ServiceApi.Name.Text() {
  255. return fmt.Errorf("%s multiple service name declaration, expecting service name '%s', but found '%s'",
  256. nestedApi.LinePrefix, mainService.ServiceApi.Name.Text(), service.ServiceApi.Name.Text())
  257. }
  258. }
  259. }
  260. return nil
  261. }
  262. func (p *Parser) memberFill(apiList []*Api) *Api {
  263. var root Api
  264. for index, each := range apiList {
  265. if index == 0 {
  266. root.Syntax = each.Syntax
  267. root.Info = each.Info
  268. root.Import = each.Import
  269. }
  270. root.Type = append(root.Type, each.Type...)
  271. root.Service = append(root.Service, each.Service...)
  272. }
  273. return &root
  274. }
  275. // checkTypeDeclaration checks whether a struct type has been declared in context
  276. func (p *Parser) checkTypeDeclaration(apiList []*Api) error {
  277. types := make(map[string]TypeExpr)
  278. for _, root := range apiList {
  279. for _, each := range root.Type {
  280. types[each.NameExpr().Text()] = each
  281. }
  282. }
  283. for _, apiItem := range apiList {
  284. linePrefix := apiItem.LinePrefix
  285. err := p.checkTypes(apiItem, linePrefix, types)
  286. if err != nil {
  287. return err
  288. }
  289. err = p.checkServices(apiItem, types, linePrefix)
  290. if err != nil {
  291. return err
  292. }
  293. }
  294. return nil
  295. }
  296. func (p *Parser) checkServices(apiItem *Api, types map[string]TypeExpr, linePrefix string) error {
  297. for _, service := range apiItem.Service {
  298. for _, each := range service.ServiceApi.ServiceRoute {
  299. route := each.Route
  300. err := p.checkRequestBody(route, types, linePrefix)
  301. if err != nil {
  302. return err
  303. }
  304. if route.Reply != nil && route.Reply.Name.IsNotNil() && route.Reply.Name.Expr().IsNotNil() {
  305. reply := route.Reply.Name
  306. var structName string
  307. switch tp := reply.(type) {
  308. case *Literal:
  309. structName = tp.Literal.Text()
  310. case *Array:
  311. switch innerTp := tp.Literal.(type) {
  312. case *Literal:
  313. structName = innerTp.Literal.Text()
  314. case *Pointer:
  315. structName = innerTp.Name.Text()
  316. }
  317. }
  318. if api.IsBasicType(structName) {
  319. continue
  320. }
  321. _, ok := types[structName]
  322. if !ok {
  323. return fmt.Errorf("%s line %d:%d can not found declaration '%s' in context",
  324. linePrefix, route.Reply.Name.Expr().Line(), route.Reply.Name.Expr().Column(), structName)
  325. }
  326. }
  327. }
  328. }
  329. return nil
  330. }
  331. func (p *Parser) checkRequestBody(route *Route, types map[string]TypeExpr, linePrefix string) error {
  332. if route.Req != nil && route.Req.Name.IsNotNil() && route.Req.Name.Expr().IsNotNil() {
  333. _, ok := types[route.Req.Name.Expr().Text()]
  334. if !ok {
  335. return fmt.Errorf("%s line %d:%d can not found declaration '%s' in context",
  336. linePrefix, route.Req.Name.Expr().Line(), route.Req.Name.Expr().Column(), route.Req.Name.Expr().Text())
  337. }
  338. }
  339. return nil
  340. }
  341. func (p *Parser) checkTypes(apiItem *Api, linePrefix string, types map[string]TypeExpr) error {
  342. for _, each := range apiItem.Type {
  343. tp, ok := each.(*TypeStruct)
  344. if !ok {
  345. continue
  346. }
  347. for _, member := range tp.Fields {
  348. err := p.checkType(linePrefix, types, member.DataType)
  349. if err != nil {
  350. return err
  351. }
  352. }
  353. }
  354. return nil
  355. }
  356. func (p *Parser) checkType(linePrefix string, types map[string]TypeExpr, expr DataType) error {
  357. if expr == nil {
  358. return nil
  359. }
  360. switch v := expr.(type) {
  361. case *Literal:
  362. name := v.Literal.Text()
  363. if api.IsBasicType(name) {
  364. return nil
  365. }
  366. _, ok := types[name]
  367. if !ok {
  368. return fmt.Errorf("%s line %d:%d can not found declaration '%s' in context",
  369. linePrefix, v.Literal.Line(), v.Literal.Column(), name)
  370. }
  371. case *Pointer:
  372. name := v.Name.Text()
  373. if api.IsBasicType(name) {
  374. return nil
  375. }
  376. _, ok := types[name]
  377. if !ok {
  378. return fmt.Errorf("%s line %d:%d can not found declaration '%s' in context",
  379. linePrefix, v.Name.Line(), v.Name.Column(), name)
  380. }
  381. case *Map:
  382. return p.checkType(linePrefix, types, v.Value)
  383. case *Array:
  384. return p.checkType(linePrefix, types, v.Literal)
  385. default:
  386. return nil
  387. }
  388. return nil
  389. }
  390. func (p *Parser) readContent(filename string) (string, error) {
  391. filename = strings.ReplaceAll(filename, `"`, "")
  392. data, err := ioutil.ReadFile(filename)
  393. if err != nil {
  394. return "", err
  395. }
  396. return string(data), nil
  397. }
  398. // SyntaxError accepts errors and panic it
  399. func (p *Parser) SyntaxError(_ antlr.Recognizer, _ interface{}, line, column int, msg string, _ antlr.RecognitionException) {
  400. str := fmt.Sprintf(`%s line %d:%d %s`, p.linePrefix, line, column, msg)
  401. if p.debug {
  402. p.log.Error(str)
  403. }
  404. panic(str)
  405. }
  406. // WithParserDebug returns a debug ParserOption
  407. func WithParserDebug() ParserOption {
  408. return func(p *Parser) {
  409. p.debug = true
  410. }
  411. }
  412. // WithParserPrefix returns a prefix ParserOption
  413. func WithParserPrefix(prefix string) ParserOption {
  414. return func(p *Parser) {
  415. p.linePrefix = prefix
  416. }
  417. }