apiparser.go 14 KB

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