apiparser.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. package ast
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "path"
  6. "path/filepath"
  7. "strings"
  8. "github.com/tal-tech/go-zero/tools/goctl/api/parser/g4/gen/api"
  9. "github.com/tal-tech/go-zero/tools/goctl/util/console"
  10. "github.com/zeromicro/antlr"
  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 string
  206. if each.AtServer != nil {
  207. p := each.AtServer.Kv.Get(prefixKey)
  208. if p != nil {
  209. prefix = p.Text()
  210. }
  211. }
  212. for _, r := range each.ServiceApi.ServiceRoute {
  213. handler := r.GetHandler()
  214. if !handler.IsNotNil() {
  215. return fmt.Errorf("%s handler not exist near line %d", nestedApi.LinePrefix, r.Route.Method.Line())
  216. }
  217. if _, ok := mainHandlerMap[handler.Text()]; ok {
  218. return fmt.Errorf("%s line %d:%d duplicate handler '%s'",
  219. nestedApi.LinePrefix, handler.Line(), handler.Column(), handler.Text())
  220. }
  221. p := fmt.Sprintf("%s://%s", r.Route.Method.Text(), path.Join(prefix, r.Route.Path.Text()))
  222. if _, ok := mainRouteMap[p]; ok {
  223. return fmt.Errorf("%s line %d:%d duplicate route '%s'",
  224. nestedApi.LinePrefix, r.Route.Method.Line(), r.Route.Method.Column(), r.Route.Method.Text()+" "+r.Route.Path.Text())
  225. }
  226. }
  227. }
  228. return nil
  229. }
  230. func (p *Parser) nestedApiCheck(mainApi, nestedApi *Api) error {
  231. if len(nestedApi.Import) > 0 {
  232. importToken := nestedApi.Import[0].Import
  233. return fmt.Errorf("%s line %d:%d the nested api does not support import",
  234. nestedApi.LinePrefix, importToken.Line(), importToken.Column())
  235. }
  236. if mainApi.Syntax != nil && nestedApi.Syntax != nil {
  237. if mainApi.Syntax.Version.Text() != nestedApi.Syntax.Version.Text() {
  238. syntaxToken := nestedApi.Syntax.Syntax
  239. return fmt.Errorf("%s line %d:%d multiple syntax declaration, expecting syntax '%s', but found '%s'",
  240. nestedApi.LinePrefix, syntaxToken.Line(), syntaxToken.Column(), mainApi.Syntax.Version.Text(), nestedApi.Syntax.Version.Text())
  241. }
  242. }
  243. if len(mainApi.Service) > 0 {
  244. mainService := mainApi.Service[0]
  245. for _, service := range nestedApi.Service {
  246. if mainService.ServiceApi.Name.Text() != service.ServiceApi.Name.Text() {
  247. return fmt.Errorf("%s multiple service name declaration, expecting service name '%s', but found '%s'",
  248. nestedApi.LinePrefix, mainService.ServiceApi.Name.Text(), service.ServiceApi.Name.Text())
  249. }
  250. }
  251. }
  252. return nil
  253. }
  254. func (p *Parser) memberFill(apiList []*Api) *Api {
  255. var root Api
  256. for index, each := range apiList {
  257. if index == 0 {
  258. root.Syntax = each.Syntax
  259. root.Info = each.Info
  260. root.Import = each.Import
  261. }
  262. root.Type = append(root.Type, each.Type...)
  263. root.Service = append(root.Service, each.Service...)
  264. }
  265. return &root
  266. }
  267. // checkTypeDeclaration checks whether a struct type has been declared in context
  268. func (p *Parser) checkTypeDeclaration(apiList []*Api) error {
  269. types := make(map[string]TypeExpr)
  270. for _, root := range apiList {
  271. for _, each := range root.Type {
  272. types[each.NameExpr().Text()] = each
  273. }
  274. }
  275. for _, apiItem := range apiList {
  276. linePrefix := apiItem.LinePrefix
  277. err := p.checkTypes(apiItem, linePrefix, types)
  278. if err != nil {
  279. return err
  280. }
  281. err = p.checkServices(apiItem, types, linePrefix)
  282. if err != nil {
  283. return err
  284. }
  285. }
  286. return nil
  287. }
  288. func (p *Parser) checkServices(apiItem *Api, types map[string]TypeExpr, linePrefix string) error {
  289. for _, service := range apiItem.Service {
  290. for _, each := range service.ServiceApi.ServiceRoute {
  291. route := each.Route
  292. err := p.checkRequestBody(route, types, linePrefix)
  293. if err != nil {
  294. return err
  295. }
  296. if route.Reply != nil && route.Reply.Name.IsNotNil() && route.Reply.Name.Expr().IsNotNil() {
  297. reply := route.Reply.Name
  298. var structName string
  299. switch tp := reply.(type) {
  300. case *Literal:
  301. structName = tp.Literal.Text()
  302. case *Array:
  303. switch innerTp := tp.Literal.(type) {
  304. case *Literal:
  305. structName = innerTp.Literal.Text()
  306. case *Pointer:
  307. structName = innerTp.Name.Text()
  308. }
  309. }
  310. if api.IsBasicType(structName) {
  311. continue
  312. }
  313. _, ok := types[structName]
  314. if !ok {
  315. return fmt.Errorf("%s line %d:%d can not found declaration '%s' in context",
  316. linePrefix, route.Reply.Name.Expr().Line(), route.Reply.Name.Expr().Column(), structName)
  317. }
  318. }
  319. }
  320. }
  321. return nil
  322. }
  323. func (p *Parser) checkRequestBody(route *Route, types map[string]TypeExpr, linePrefix string) error {
  324. if route.Req != nil && route.Req.Name.IsNotNil() && route.Req.Name.Expr().IsNotNil() {
  325. _, ok := types[route.Req.Name.Expr().Text()]
  326. if !ok {
  327. return fmt.Errorf("%s line %d:%d can not found declaration '%s' in context",
  328. linePrefix, route.Req.Name.Expr().Line(), route.Req.Name.Expr().Column(), route.Req.Name.Expr().Text())
  329. }
  330. }
  331. return nil
  332. }
  333. func (p *Parser) checkTypes(apiItem *Api, linePrefix string, types map[string]TypeExpr) error {
  334. for _, each := range apiItem.Type {
  335. tp, ok := each.(*TypeStruct)
  336. if !ok {
  337. continue
  338. }
  339. for _, member := range tp.Fields {
  340. err := p.checkType(linePrefix, types, member.DataType)
  341. if err != nil {
  342. return err
  343. }
  344. }
  345. }
  346. return nil
  347. }
  348. func (p *Parser) checkType(linePrefix string, types map[string]TypeExpr, expr DataType) error {
  349. if expr == nil {
  350. return nil
  351. }
  352. switch v := expr.(type) {
  353. case *Literal:
  354. name := v.Literal.Text()
  355. if api.IsBasicType(name) {
  356. return nil
  357. }
  358. _, ok := types[name]
  359. if !ok {
  360. return fmt.Errorf("%s line %d:%d can not found declaration '%s' in context",
  361. linePrefix, v.Literal.Line(), v.Literal.Column(), name)
  362. }
  363. case *Pointer:
  364. name := v.Name.Text()
  365. if api.IsBasicType(name) {
  366. return nil
  367. }
  368. _, ok := types[name]
  369. if !ok {
  370. return fmt.Errorf("%s line %d:%d can not found declaration '%s' in context",
  371. linePrefix, v.Name.Line(), v.Name.Column(), name)
  372. }
  373. case *Map:
  374. return p.checkType(linePrefix, types, v.Value)
  375. case *Array:
  376. return p.checkType(linePrefix, types, v.Literal)
  377. default:
  378. return nil
  379. }
  380. return nil
  381. }
  382. func (p *Parser) readContent(filename string) (string, error) {
  383. filename = strings.ReplaceAll(filename, `"`, "")
  384. data, err := ioutil.ReadFile(filename)
  385. if err != nil {
  386. return "", err
  387. }
  388. return string(data), nil
  389. }
  390. // SyntaxError accepts errors and panic it
  391. func (p *Parser) SyntaxError(_ antlr.Recognizer, _ interface{}, line, column int, msg string, _ antlr.RecognitionException) {
  392. str := fmt.Sprintf(`%s line %d:%d %s`, p.linePrefix, line, column, msg)
  393. if p.debug {
  394. p.log.Error(str)
  395. }
  396. panic(str)
  397. }
  398. // WithParserDebug returns a debug ParserOption
  399. func WithParserDebug() ParserOption {
  400. return func(p *Parser) {
  401. p.debug = true
  402. }
  403. }
  404. // WithParserPrefix returns a prefix ParserOption
  405. func WithParserPrefix(prefix string) ParserOption {
  406. return func(p *Parser) {
  407. p.linePrefix = prefix
  408. }
  409. }