apiparser.go 12 KB

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