apiparser.go 10 KB

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