apiparser.go 12 KB

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