apiparser.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. 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) {
  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(), g.Route.Path.Text())
  213. p.routeMap[route] = Holder
  214. }
  215. }
  216. }
  217. for _, each := range api.Service {
  218. routeMap(each.ServiceApi.ServiceRoute)
  219. }
  220. for _, each := range api.Type {
  221. p.typeMap[each.NameExpr().Text()] = Holder
  222. }
  223. }
  224. func (p *Parser) valid(nestedApi *Api) error {
  225. if p.syntax != nil && nestedApi.Syntax != nil {
  226. if p.syntax.Version.Text() != nestedApi.Syntax.Version.Text() {
  227. syntaxToken := nestedApi.Syntax.Syntax
  228. return fmt.Errorf("%s line %d:%d multiple syntax declaration, expecting syntax '%s', but found '%s'",
  229. nestedApi.LinePrefix, syntaxToken.Line(), syntaxToken.Column(), p.syntax.Version.Text(), nestedApi.Syntax.Version.Text())
  230. }
  231. }
  232. // duplicate route check
  233. err := p.duplicateRouteCheck(nestedApi)
  234. if err != nil {
  235. return err
  236. }
  237. // duplicate type check
  238. for _, each := range nestedApi.Type {
  239. if _, ok := p.typeMap[each.NameExpr().Text()]; ok {
  240. return fmt.Errorf("%s line %d:%d duplicate type declaration '%s'",
  241. nestedApi.LinePrefix, each.NameExpr().Line(), each.NameExpr().Column(), each.NameExpr().Text())
  242. }
  243. }
  244. return nil
  245. }
  246. func (p *Parser) duplicateRouteCheck(nestedApi *Api) error {
  247. for _, each := range nestedApi.Service {
  248. var prefix, group string
  249. if each.AtServer != nil {
  250. p := each.AtServer.Kv.Get(prefixKey)
  251. if p != nil {
  252. prefix = p.Text()
  253. }
  254. g := each.AtServer.Kv.Get(groupKey)
  255. if g != nil {
  256. group = g.Text()
  257. }
  258. }
  259. for _, r := range each.ServiceApi.ServiceRoute {
  260. handler := r.GetHandler()
  261. if !handler.IsNotNil() {
  262. return fmt.Errorf("%s handler not exist near line %d", nestedApi.LinePrefix, r.Route.Method.Line())
  263. }
  264. handlerKey := handler.Text()
  265. if len(group) > 0 {
  266. handlerKey = fmt.Sprintf("%s/%s", group, handler.Text())
  267. }
  268. if _, ok := p.handlerMap[handlerKey]; ok {
  269. return fmt.Errorf("%s line %d:%d duplicate handler '%s'",
  270. nestedApi.LinePrefix, handler.Line(), handler.Column(), handlerKey)
  271. }
  272. routeKey := fmt.Sprintf("%s://%s", r.Route.Method.Text(), path.Join(prefix, r.Route.Path.Text()))
  273. if _, ok := p.routeMap[routeKey]; ok {
  274. return fmt.Errorf("%s line %d:%d duplicate route '%s'",
  275. nestedApi.LinePrefix, r.Route.Method.Line(), r.Route.Method.Column(), r.Route.Method.Text()+" "+r.Route.Path.Text())
  276. }
  277. }
  278. }
  279. return nil
  280. }
  281. func (p *Parser) nestedApiCheck(mainApi, nestedApi *Api) error {
  282. if len(nestedApi.Import) > 0 {
  283. importToken := nestedApi.Import[0].Import
  284. return fmt.Errorf("%s line %d:%d the nested api does not support import",
  285. nestedApi.LinePrefix, importToken.Line(), importToken.Column())
  286. }
  287. if mainApi.Syntax != nil && nestedApi.Syntax != nil {
  288. if mainApi.Syntax.Version.Text() != nestedApi.Syntax.Version.Text() {
  289. syntaxToken := nestedApi.Syntax.Syntax
  290. return fmt.Errorf("%s line %d:%d multiple syntax declaration, expecting syntax '%s', but found '%s'",
  291. nestedApi.LinePrefix, syntaxToken.Line(), syntaxToken.Column(), mainApi.Syntax.Version.Text(), nestedApi.Syntax.Version.Text())
  292. }
  293. }
  294. if len(mainApi.Service) > 0 {
  295. mainService := mainApi.Service[0]
  296. for _, service := range nestedApi.Service {
  297. if mainService.ServiceApi.Name.Text() != service.ServiceApi.Name.Text() {
  298. return fmt.Errorf("%s multiple service name declaration, expecting service name '%s', but found '%s'",
  299. nestedApi.LinePrefix, mainService.ServiceApi.Name.Text(), service.ServiceApi.Name.Text())
  300. }
  301. }
  302. }
  303. return nil
  304. }
  305. func (p *Parser) memberFill(apiList []*Api) *Api {
  306. var root Api
  307. for index, each := range apiList {
  308. if index == 0 {
  309. root.Syntax = each.Syntax
  310. root.Info = each.Info
  311. root.Import = each.Import
  312. }
  313. root.Type = append(root.Type, each.Type...)
  314. root.Service = append(root.Service, each.Service...)
  315. }
  316. return &root
  317. }
  318. // checkTypeDeclaration checks whether a struct type has been declared in context
  319. func (p *Parser) checkTypeDeclaration(apiList []*Api) error {
  320. types := make(map[string]TypeExpr)
  321. for _, root := range apiList {
  322. for _, each := range root.Type {
  323. types[each.NameExpr().Text()] = each
  324. }
  325. }
  326. for _, apiItem := range apiList {
  327. linePrefix := apiItem.LinePrefix
  328. err := p.checkTypes(apiItem, linePrefix, types)
  329. if err != nil {
  330. return err
  331. }
  332. err = p.checkServices(apiItem, types, linePrefix)
  333. if err != nil {
  334. return err
  335. }
  336. }
  337. return nil
  338. }
  339. func (p *Parser) checkServices(apiItem *Api, types map[string]TypeExpr, linePrefix string) error {
  340. for _, service := range apiItem.Service {
  341. for _, each := range service.ServiceApi.ServiceRoute {
  342. route := each.Route
  343. err := p.checkRequestBody(route, types, linePrefix)
  344. if err != nil {
  345. return err
  346. }
  347. if route.Reply != nil && route.Reply.Name.IsNotNil() && route.Reply.Name.Expr().IsNotNil() {
  348. reply := route.Reply.Name
  349. var structName string
  350. switch tp := reply.(type) {
  351. case *Literal:
  352. structName = tp.Literal.Text()
  353. case *Array:
  354. switch innerTp := tp.Literal.(type) {
  355. case *Literal:
  356. structName = innerTp.Literal.Text()
  357. case *Pointer:
  358. structName = innerTp.Name.Text()
  359. }
  360. }
  361. if api.IsBasicType(structName) {
  362. continue
  363. }
  364. _, ok := types[structName]
  365. if !ok {
  366. return fmt.Errorf("%s line %d:%d can not found declaration '%s' in context",
  367. linePrefix, route.Reply.Name.Expr().Line(), route.Reply.Name.Expr().Column(), structName)
  368. }
  369. }
  370. }
  371. }
  372. return nil
  373. }
  374. func (p *Parser) checkRequestBody(route *Route, types map[string]TypeExpr, linePrefix string) error {
  375. if route.Req != nil && route.Req.Name.IsNotNil() && route.Req.Name.Expr().IsNotNil() {
  376. _, ok := types[route.Req.Name.Expr().Text()]
  377. if !ok {
  378. return fmt.Errorf("%s line %d:%d can not found declaration '%s' in context",
  379. linePrefix, route.Req.Name.Expr().Line(), route.Req.Name.Expr().Column(), route.Req.Name.Expr().Text())
  380. }
  381. }
  382. return nil
  383. }
  384. func (p *Parser) checkTypes(apiItem *Api, linePrefix string, types map[string]TypeExpr) error {
  385. for _, each := range apiItem.Type {
  386. tp, ok := each.(*TypeStruct)
  387. if !ok {
  388. continue
  389. }
  390. for _, member := range tp.Fields {
  391. err := p.checkType(linePrefix, types, member.DataType)
  392. if err != nil {
  393. return err
  394. }
  395. }
  396. }
  397. return nil
  398. }
  399. func (p *Parser) checkType(linePrefix string, types map[string]TypeExpr, expr DataType) error {
  400. if expr == nil {
  401. return nil
  402. }
  403. switch v := expr.(type) {
  404. case *Literal:
  405. name := v.Literal.Text()
  406. if api.IsBasicType(name) {
  407. return nil
  408. }
  409. _, ok := types[name]
  410. if !ok {
  411. return fmt.Errorf("%s line %d:%d can not found declaration '%s' in context",
  412. linePrefix, v.Literal.Line(), v.Literal.Column(), name)
  413. }
  414. case *Pointer:
  415. name := v.Name.Text()
  416. if api.IsBasicType(name) {
  417. return nil
  418. }
  419. _, ok := types[name]
  420. if !ok {
  421. return fmt.Errorf("%s line %d:%d can not found declaration '%s' in context",
  422. linePrefix, v.Name.Line(), v.Name.Column(), name)
  423. }
  424. case *Map:
  425. return p.checkType(linePrefix, types, v.Value)
  426. case *Array:
  427. return p.checkType(linePrefix, types, v.Literal)
  428. default:
  429. return nil
  430. }
  431. return nil
  432. }
  433. func (p *Parser) readContent(filename string) (string, error) {
  434. filename = strings.ReplaceAll(filename, `"`, "")
  435. data, err := ioutil.ReadFile(filename)
  436. if err != nil {
  437. return "", err
  438. }
  439. return string(data), nil
  440. }
  441. // SyntaxError accepts errors and panic it
  442. func (p *Parser) SyntaxError(_ antlr.Recognizer, _ interface{}, line, column int, msg string, _ antlr.RecognitionException) {
  443. str := fmt.Sprintf(`%s line %d:%d %s`, p.linePrefix, line, column, msg)
  444. if p.debug {
  445. p.log.Error(str)
  446. }
  447. panic(str)
  448. }
  449. // WithParserDebug returns a debug ParserOption
  450. func WithParserDebug() ParserOption {
  451. return func(p *Parser) {
  452. p.debug = true
  453. }
  454. }
  455. // WithParserPrefix returns a prefix ParserOption
  456. func WithParserPrefix(prefix string) ParserOption {
  457. return func(p *Parser) {
  458. p.linePrefix = prefix
  459. }
  460. }
  461. func WithParserSkipCheckTypeDeclaration() ParserOption {
  462. return func(p *Parser) {
  463. p.skipCheckTypeDeclaration = true
  464. }
  465. }