writer.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. package ast
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "strings"
  7. "text/tabwriter"
  8. "github.com/zeromicro/go-zero/tools/goctl/pkg/parser/api/token"
  9. "github.com/zeromicro/go-zero/tools/goctl/util"
  10. )
  11. const (
  12. NilIndent = ""
  13. WhiteSpace = " "
  14. Indent = "\t"
  15. NewLine = "\n"
  16. )
  17. const (
  18. _ WriteMode = 1 << iota
  19. // ModeAuto is the default mode, which will automatically
  20. //determine whether to write a newline.
  21. ModeAuto
  22. // ModeExpectInSameLine will write in the same line.
  23. ModeExpectInSameLine
  24. )
  25. type Option func(o *option)
  26. type option struct {
  27. prefix string
  28. infix string
  29. mode WriteMode
  30. nodes []Node
  31. rawText bool
  32. }
  33. type tokenNodeOption func(o *tokenNodeOpt)
  34. type tokenNodeOpt struct {
  35. prefix string
  36. infix string
  37. ignoreHeadComment bool
  38. ignoreLeadingComment bool
  39. }
  40. // WriteMode is the mode of writing.
  41. type WriteMode int
  42. // Writer is the writer of ast.
  43. type Writer struct {
  44. tw *tabwriter.Writer
  45. writer io.Writer
  46. }
  47. func transfer2TokenNode(node Node, isChild bool, opt ...tokenNodeOption) *TokenNode {
  48. option := new(tokenNodeOpt)
  49. for _, o := range opt {
  50. o(option)
  51. }
  52. var copyOpt = append([]tokenNodeOption(nil), opt...)
  53. var tn *TokenNode
  54. switch val := node.(type) {
  55. case *AnyDataType:
  56. copyOpt = append(copyOpt, withTokenNodePrefix(NilIndent))
  57. tn = transferTokenNode(val.Any, copyOpt...)
  58. if option.ignoreHeadComment {
  59. tn.HeadCommentGroup = nil
  60. }
  61. if option.ignoreLeadingComment {
  62. tn.LeadingCommentGroup = nil
  63. }
  64. val.isChild = isChild
  65. val.Any = tn
  66. case *ArrayDataType:
  67. copyOpt = append(copyOpt, withTokenNodePrefix(NilIndent))
  68. tn = transferTokenNode(val.LBrack, copyOpt...)
  69. if option.ignoreHeadComment {
  70. tn.HeadCommentGroup = nil
  71. }
  72. if option.ignoreLeadingComment {
  73. tn.LeadingCommentGroup = nil
  74. }
  75. val.isChild = isChild
  76. val.LBrack = tn
  77. case *BaseDataType:
  78. copyOpt = append(copyOpt, withTokenNodePrefix(NilIndent))
  79. tn = transferTokenNode(val.Base, copyOpt...)
  80. if option.ignoreHeadComment {
  81. tn.HeadCommentGroup = nil
  82. }
  83. if option.ignoreLeadingComment {
  84. tn.LeadingCommentGroup = nil
  85. }
  86. val.isChild = isChild
  87. val.Base = tn
  88. case *InterfaceDataType:
  89. copyOpt = append(copyOpt, withTokenNodePrefix(NilIndent))
  90. tn = transferTokenNode(val.Interface, copyOpt...)
  91. if option.ignoreHeadComment {
  92. tn.HeadCommentGroup = nil
  93. }
  94. if option.ignoreLeadingComment {
  95. tn.LeadingCommentGroup = nil
  96. }
  97. val.isChild = isChild
  98. val.Interface = tn
  99. case *MapDataType:
  100. copyOpt = append(copyOpt, withTokenNodePrefix(NilIndent))
  101. tn = transferTokenNode(val.Map, copyOpt...)
  102. if option.ignoreHeadComment {
  103. tn.HeadCommentGroup = nil
  104. }
  105. if option.ignoreLeadingComment {
  106. tn.LeadingCommentGroup = nil
  107. }
  108. val.isChild = isChild
  109. val.Map = tn
  110. case *PointerDataType:
  111. copyOpt = append(copyOpt, withTokenNodePrefix(NilIndent))
  112. tn = transferTokenNode(val.Star, copyOpt...)
  113. if option.ignoreHeadComment {
  114. tn.HeadCommentGroup = nil
  115. }
  116. if option.ignoreLeadingComment {
  117. tn.LeadingCommentGroup = nil
  118. }
  119. val.isChild = isChild
  120. val.Star = tn
  121. case *SliceDataType:
  122. copyOpt = append(copyOpt, withTokenNodePrefix(NilIndent))
  123. tn = transferTokenNode(val.LBrack, copyOpt...)
  124. if option.ignoreHeadComment {
  125. tn.HeadCommentGroup = nil
  126. }
  127. if option.ignoreLeadingComment {
  128. tn.LeadingCommentGroup = nil
  129. }
  130. val.isChild = isChild
  131. val.LBrack = tn
  132. case *StructDataType:
  133. copyOpt = append(copyOpt, withTokenNodePrefix(NilIndent))
  134. tn = transferTokenNode(val.LBrace, copyOpt...)
  135. if option.ignoreHeadComment {
  136. tn.HeadCommentGroup = nil
  137. }
  138. if option.ignoreLeadingComment {
  139. tn.LeadingCommentGroup = nil
  140. }
  141. val.isChild = isChild
  142. val.LBrace = tn
  143. default:
  144. }
  145. return &TokenNode{
  146. headFlag: node.HasHeadCommentGroup(),
  147. leadingFlag: node.HasLeadingCommentGroup(),
  148. Token: token.Token{
  149. Text: node.Format(option.prefix),
  150. Position: node.Pos(),
  151. },
  152. LeadingCommentGroup: CommentGroup{
  153. {
  154. token.Token{Position: node.End()},
  155. },
  156. },
  157. }
  158. }
  159. func transferNilInfixNode(nodes []*TokenNode, opt ...tokenNodeOption) *TokenNode {
  160. result := &TokenNode{}
  161. var option = new(tokenNodeOpt)
  162. for _, o := range opt {
  163. o(option)
  164. }
  165. var list []string
  166. for _, n := range nodes {
  167. list = append(list, n.Token.Text)
  168. }
  169. result.Token = token.Token{
  170. Text: option.prefix + strings.Join(list, option.infix),
  171. Position: nodes[0].Pos(),
  172. }
  173. if !option.ignoreHeadComment {
  174. result.HeadCommentGroup = nodes[0].HeadCommentGroup
  175. }
  176. if !option.ignoreLeadingComment {
  177. result.LeadingCommentGroup = nodes[len(nodes)-1].LeadingCommentGroup
  178. }
  179. return result
  180. }
  181. func transferTokenNode(node *TokenNode, opt ...tokenNodeOption) *TokenNode {
  182. result := &TokenNode{}
  183. var option = new(tokenNodeOpt)
  184. for _, o := range opt {
  185. o(option)
  186. }
  187. result.Token = token.Token{
  188. Type: node.Token.Type,
  189. Text: option.prefix + node.Token.Text,
  190. Position: node.Token.Position,
  191. }
  192. if !option.ignoreHeadComment {
  193. for _, v := range node.HeadCommentGroup {
  194. result.HeadCommentGroup = append(result.HeadCommentGroup,
  195. &CommentStmt{Comment: token.Token{
  196. Type: v.Comment.Type,
  197. Text: option.prefix + v.Comment.Text,
  198. Position: v.Comment.Position,
  199. }})
  200. }
  201. }
  202. if !option.ignoreLeadingComment {
  203. for _, v := range node.LeadingCommentGroup {
  204. result.LeadingCommentGroup = append(result.LeadingCommentGroup, v)
  205. }
  206. }
  207. return result
  208. }
  209. func ignoreHeadComment() tokenNodeOption {
  210. return func(o *tokenNodeOpt) {
  211. o.ignoreHeadComment = true
  212. }
  213. }
  214. func ignoreLeadingComment() tokenNodeOption {
  215. return func(o *tokenNodeOpt) {
  216. o.ignoreLeadingComment = true
  217. }
  218. }
  219. func ignoreComment() tokenNodeOption {
  220. return func(o *tokenNodeOpt) {
  221. o.ignoreHeadComment = true
  222. o.ignoreLeadingComment = true
  223. }
  224. }
  225. func withTokenNodePrefix(prefix ...string) tokenNodeOption {
  226. return func(o *tokenNodeOpt) {
  227. for _, p := range prefix {
  228. o.prefix = p
  229. }
  230. }
  231. }
  232. func withTokenNodeInfix(infix string) tokenNodeOption {
  233. return func(o *tokenNodeOpt) {
  234. o.infix = infix
  235. }
  236. }
  237. func expectSameLine() Option {
  238. return func(o *option) {
  239. o.mode = ModeExpectInSameLine
  240. }
  241. }
  242. func expectIndentInfix() Option {
  243. return func(o *option) {
  244. o.infix = Indent
  245. }
  246. }
  247. func withNode(nodes ...Node) Option {
  248. return func(o *option) {
  249. o.nodes = nodes
  250. }
  251. }
  252. func withMode(mode WriteMode) Option {
  253. return func(o *option) {
  254. o.mode = mode
  255. }
  256. }
  257. func withPrefix(prefix ...string) Option {
  258. return func(o *option) {
  259. for _, p := range prefix {
  260. o.prefix = p
  261. }
  262. }
  263. }
  264. func withInfix(infix string) Option {
  265. return func(o *option) {
  266. o.infix = infix
  267. }
  268. }
  269. func withRawText() Option {
  270. return func(o *option) {
  271. o.rawText = true
  272. }
  273. }
  274. // NewWriter returns a new Writer.
  275. func NewWriter(writer io.Writer) *Writer {
  276. return &Writer{
  277. tw: tabwriter.NewWriter(writer, 1, 8, 1, ' ', tabwriter.TabIndent),
  278. writer: writer,
  279. }
  280. }
  281. // NewBufferWriter returns a new buffer Writer.
  282. func NewBufferWriter() *Writer {
  283. writer := bytes.NewBuffer(nil)
  284. return &Writer{
  285. tw: tabwriter.NewWriter(writer, 1, 8, 1, ' ', tabwriter.TabIndent),
  286. writer: writer,
  287. }
  288. }
  289. // String returns the string of the buffer.
  290. func (w *Writer) String() string {
  291. buffer, ok := w.writer.(*bytes.Buffer)
  292. if !ok {
  293. return ""
  294. }
  295. w.Flush()
  296. return buffer.String()
  297. }
  298. // Flush flushes the buffer.
  299. func (w *Writer) Flush() {
  300. _ = w.tw.Flush()
  301. }
  302. // NewLine writes a new line.
  303. func (w *Writer) NewLine() {
  304. _, _ = fmt.Fprint(w.tw, NewLine)
  305. }
  306. // Write writes the node.
  307. func (w *Writer) Write(opts ...Option) {
  308. if len(opts) == 0 {
  309. return
  310. }
  311. var opt = new(option)
  312. opt.mode = ModeAuto
  313. opt.prefix = NilIndent
  314. opt.infix = WhiteSpace
  315. for _, v := range opts {
  316. v(opt)
  317. }
  318. w.write(opt)
  319. }
  320. // WriteText writes the text.
  321. func (w *Writer) WriteText(text string) {
  322. _, _ = fmt.Fprintf(w.tw, text)
  323. }
  324. func (w *Writer) write(opt *option) {
  325. if len(opt.nodes) == 0 {
  326. return
  327. }
  328. var textList []string
  329. line := opt.nodes[0].End().Line
  330. for idx, node := range opt.nodes {
  331. mode := opt.mode
  332. preIdx := idx - 1
  333. var preNodeHasLeading bool
  334. if preIdx > -1 && preIdx < len(opt.nodes) {
  335. preNode := opt.nodes[preIdx]
  336. preNodeHasLeading = preNode.HasLeadingCommentGroup()
  337. }
  338. if node.HasHeadCommentGroup() || preNodeHasLeading {
  339. mode = ModeAuto
  340. }
  341. if mode == ModeAuto && node.Pos().Line > line {
  342. textList = append(textList, NewLine)
  343. }
  344. line = node.End().Line
  345. if util.TrimWhiteSpace(node.Format()) == "" {
  346. continue
  347. }
  348. textList = append(textList, node.Format(opt.prefix))
  349. }
  350. text := strings.Join(textList, opt.infix)
  351. text = strings.ReplaceAll(text, " \n", "\n")
  352. text = strings.ReplaceAll(text, "\n ", "\n")
  353. if opt.rawText {
  354. _, _ = fmt.Fprint(w.writer, text)
  355. return
  356. }
  357. _, _ = fmt.Fprint(w.tw, text)
  358. }