apiparser.go 12 KB

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