writer.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. result.LeadingCommentGroup = append(result.LeadingCommentGroup, node.LeadingCommentGroup...)
  204. }
  205. return result
  206. }
  207. func ignoreHeadComment() tokenNodeOption {
  208. return func(o *tokenNodeOpt) {
  209. o.ignoreHeadComment = true
  210. }
  211. }
  212. func ignoreLeadingComment() tokenNodeOption {
  213. return func(o *tokenNodeOpt) {
  214. o.ignoreLeadingComment = true
  215. }
  216. }
  217. func ignoreComment() tokenNodeOption {
  218. return func(o *tokenNodeOpt) {
  219. o.ignoreHeadComment = true
  220. o.ignoreLeadingComment = true
  221. }
  222. }
  223. func withTokenNodePrefix(prefix ...string) tokenNodeOption {
  224. return func(o *tokenNodeOpt) {
  225. for _, p := range prefix {
  226. o.prefix = p
  227. }
  228. }
  229. }
  230. func withTokenNodeInfix(infix string) tokenNodeOption {
  231. return func(o *tokenNodeOpt) {
  232. o.infix = infix
  233. }
  234. }
  235. func expectSameLine() Option {
  236. return func(o *option) {
  237. o.mode = ModeExpectInSameLine
  238. }
  239. }
  240. func expectIndentInfix() Option {
  241. return func(o *option) {
  242. o.infix = Indent
  243. }
  244. }
  245. func withNode(nodes ...Node) Option {
  246. return func(o *option) {
  247. o.nodes = nodes
  248. }
  249. }
  250. func withMode(mode WriteMode) Option {
  251. return func(o *option) {
  252. o.mode = mode
  253. }
  254. }
  255. func withPrefix(prefix ...string) Option {
  256. return func(o *option) {
  257. for _, p := range prefix {
  258. o.prefix = p
  259. }
  260. }
  261. }
  262. func withInfix(infix string) Option {
  263. return func(o *option) {
  264. o.infix = infix
  265. }
  266. }
  267. func withRawText() Option {
  268. return func(o *option) {
  269. o.rawText = true
  270. }
  271. }
  272. // NewWriter returns a new Writer.
  273. func NewWriter(writer io.Writer) *Writer {
  274. return &Writer{
  275. tw: tabwriter.NewWriter(writer, 1, 8, 1, ' ', tabwriter.TabIndent),
  276. writer: writer,
  277. }
  278. }
  279. // NewBufferWriter returns a new buffer Writer.
  280. func NewBufferWriter() *Writer {
  281. writer := bytes.NewBuffer(nil)
  282. return &Writer{
  283. tw: tabwriter.NewWriter(writer, 1, 8, 1, ' ', tabwriter.TabIndent),
  284. writer: writer,
  285. }
  286. }
  287. // String returns the string of the buffer.
  288. func (w *Writer) String() string {
  289. buffer, ok := w.writer.(*bytes.Buffer)
  290. if !ok {
  291. return ""
  292. }
  293. w.Flush()
  294. return buffer.String()
  295. }
  296. // Flush flushes the buffer.
  297. func (w *Writer) Flush() {
  298. _ = w.tw.Flush()
  299. }
  300. // NewLine writes a new line.
  301. func (w *Writer) NewLine() {
  302. _, _ = fmt.Fprint(w.tw, NewLine)
  303. }
  304. // Write writes the node.
  305. func (w *Writer) Write(opts ...Option) {
  306. if len(opts) == 0 {
  307. return
  308. }
  309. var opt = new(option)
  310. opt.mode = ModeAuto
  311. opt.prefix = NilIndent
  312. opt.infix = WhiteSpace
  313. for _, v := range opts {
  314. v(opt)
  315. }
  316. w.write(opt)
  317. }
  318. // WriteText writes the text.
  319. func (w *Writer) WriteText(text string) {
  320. _, _ = fmt.Fprintf(w.tw, text)
  321. }
  322. func (w *Writer) write(opt *option) {
  323. if len(opt.nodes) == 0 {
  324. return
  325. }
  326. var textList []string
  327. line := opt.nodes[0].End().Line
  328. for idx, node := range opt.nodes {
  329. mode := opt.mode
  330. preIdx := idx - 1
  331. var preNodeHasLeading bool
  332. if preIdx > -1 && preIdx < len(opt.nodes) {
  333. preNode := opt.nodes[preIdx]
  334. preNodeHasLeading = preNode.HasLeadingCommentGroup()
  335. }
  336. if node.HasHeadCommentGroup() || preNodeHasLeading {
  337. mode = ModeAuto
  338. }
  339. if mode == ModeAuto && node.Pos().Line > line {
  340. textList = append(textList, NewLine)
  341. }
  342. line = node.End().Line
  343. if util.TrimWhiteSpace(node.Format()) == "" {
  344. continue
  345. }
  346. textList = append(textList, node.Format(opt.prefix))
  347. }
  348. text := strings.Join(textList, opt.infix)
  349. text = strings.ReplaceAll(text, " \n", "\n")
  350. text = strings.ReplaceAll(text, "\n ", "\n")
  351. if opt.rawText {
  352. _, _ = fmt.Fprint(w.writer, text)
  353. return
  354. }
  355. _, _ = fmt.Fprint(w.tw, text)
  356. }