apiparser.go 14 KB

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