-
Notifications
You must be signed in to change notification settings - Fork 279
/
format.go
350 lines (300 loc) · 8.6 KB
/
format.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// Copyright 2018 The CUE Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package format implements standard formatting of CUE configurations.
package format // import "cuelang.org/go/cue/format"
// TODO: this package is in need of a rewrite. When doing so, the API should
// allow for reformatting an AST, without actually writing bytes.
//
// In essence, formatting determines the relative spacing to tokens. It should
// be possible to have an abstract implementation providing such information
// that can be used to either format or update an AST in a single walk.
import (
"bytes"
"fmt"
"strings"
"text/tabwriter"
"cuelang.org/go/cue/ast"
"cuelang.org/go/cue/parser"
"cuelang.org/go/cue/token"
)
// An Option sets behavior of the formatter.
type Option func(c *config)
// Simplify allows the formatter to simplify output, such as removing
// unnecessary quotes.
func Simplify() Option {
return func(c *config) { c.simplify = true }
}
// UseSpaces specifies that tabs should be converted to spaces and sets the
// default tab width.
func UseSpaces(tabwidth int) Option {
return func(c *config) {
c.UseSpaces = true
c.Tabwidth = tabwidth
}
}
// TabIndent specifies whether to use tabs for indentation independent of
// UseSpaces.
func TabIndent(indent bool) Option {
return func(c *config) { c.TabIndent = indent }
}
// IndentPrefix specifies the number of tabstops to use as a prefix for every
// line.
func IndentPrefix(n int) Option {
return func(c *config) { c.Indent = n }
}
// TODO: make public
// sortImportsOption causes import declarations to be sorted.
func sortImportsOption() Option {
return func(c *config) { c.sortImports = true }
}
// TODO: other options:
//
// const (
// RawFormat Mode = 1 << iota // do not use a tabwriter; if set, UseSpaces is ignored
// TabIndent // use tabs for indentation independent of UseSpaces
// UseSpaces // use spaces instead of tabs for alignment
// SourcePos // emit //line comments to preserve original source positions
// )
// Node formats node in canonical cue fmt style and writes the result to dst.
//
// The node type must be *ast.File, []syntax.Decl, syntax.Expr, syntax.Decl, or
// syntax.Spec. Node does not modify node. Imports are not sorted for nodes
// representing partial source files (for instance, if the node is not an
// *ast.File).
//
// The function may return early (before the entire result is written) and
// return a formatting error, for instance due to an incorrect AST.
//
func Node(node ast.Node, opt ...Option) ([]byte, error) {
cfg := newConfig(opt)
return cfg.fprint(node)
}
// Source formats src in canonical cue fmt style and returns the result or an
// (I/O or syntax) error. src is expected to be a syntactically correct CUE
// source file, or a list of CUE declarations or statements.
//
// If src is a partial source file, the leading and trailing space of src is
// applied to the result (such that it has the same leading and trailing space
// as src), and the result is indented by the same amount as the first line of
// src containing code. Imports are not sorted for partial source files.
//
// Caution: Tools relying on consistent formatting based on the installed
// version of cue (for instance, such as for presubmit checks) should execute
// that cue binary instead of calling Source.
//
func Source(b []byte, opt ...Option) ([]byte, error) {
cfg := newConfig(opt)
f, err := parser.ParseFile("", b, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("parse: %s", err)
}
// print AST
return cfg.fprint(f)
}
type config struct {
UseSpaces bool
TabIndent bool
Tabwidth int // default: 4
Indent int // default: 0 (all code is indented at least by this much)
simplify bool
sortImports bool
}
func newConfig(opt []Option) *config {
cfg := &config{
Tabwidth: 8,
TabIndent: true,
UseSpaces: true,
}
for _, o := range opt {
o(cfg)
}
return cfg
}
// Config defines the output of Fprint.
func (cfg *config) fprint(node interface{}) (out []byte, err error) {
var p printer
p.init(cfg)
if err = printNode(node, &p); err != nil {
return p.output, err
}
padchar := byte('\t')
if cfg.UseSpaces {
padchar = byte(' ')
}
twmode := tabwriter.StripEscape | tabwriter.TabIndent | tabwriter.DiscardEmptyColumns
if cfg.TabIndent {
twmode |= tabwriter.TabIndent
}
buf := &bytes.Buffer{}
tw := tabwriter.NewWriter(buf, 0, cfg.Tabwidth, 1, padchar, twmode)
// write printer result via tabwriter/trimmer to output
if _, err = tw.Write(p.output); err != nil {
return
}
err = tw.Flush()
if err != nil {
return buf.Bytes(), err
}
b := buf.Bytes()
if !cfg.TabIndent {
b = bytes.ReplaceAll(b, []byte{'\t'}, bytes.Repeat([]byte{' '}, cfg.Tabwidth))
}
return b, nil
}
// A formatter walks a syntax.Node, interspersed with comments and spacing
// directives, in the order that they would occur in printed form.
type formatter struct {
*printer
stack []frame
current frame
nestExpr int
}
func newFormatter(p *printer) *formatter {
f := &formatter{
printer: p,
current: frame{
settings: settings{
nodeSep: newline,
parentSep: newline,
},
},
}
return f
}
type whiteSpace int
const (
ignore whiteSpace = 0
// write a space, or disallow it
blank whiteSpace = 1 << iota
vtab // column marker
noblank
nooverride
comma // print a comma, unless trailcomma overrides it
trailcomma // print a trailing comma unless closed on same line
declcomma // write a comma when not at the end of line
newline // write a line in a table
formfeed // next line is not part of the table
newsection // add two newlines
indent // request indent an extra level after the next newline
unindent // unindent a level after the next newline
indented // element was indented.
)
type frame struct {
cg []*ast.CommentGroup
pos int8
settings
}
type settings struct {
// separator is blank if the current node spans a single line and newline
// otherwise.
nodeSep whiteSpace
parentSep whiteSpace
override whiteSpace
}
// suppress spurious linter warning: field is actually used.
func init() {
s := settings{}
_ = s.override
}
func (f *formatter) print(a ...interface{}) {
for _, x := range a {
f.Print(x)
switch x.(type) {
case string, token.Token: // , *syntax.BasicLit, *syntax.Ident:
f.current.pos++
}
}
f.visitComments(f.current.pos)
}
func (f *formatter) formfeed() whiteSpace {
if f.current.nodeSep == blank {
return blank
}
return formfeed
}
func (f *formatter) wsOverride(def whiteSpace) whiteSpace {
if f.current.override == ignore {
return def
}
return f.current.override
}
func (f *formatter) onOneLine(node ast.Node) bool {
a := node.Pos()
b := node.End()
if a.IsValid() && b.IsValid() {
return f.lineFor(a) == f.lineFor(b)
}
// TODO: walk and look at relative positions to determine the same?
return false
}
func (f *formatter) before(node ast.Node) bool {
f.stack = append(f.stack, f.current)
f.current = frame{settings: f.current.settings}
f.current.parentSep = f.current.nodeSep
if node != nil {
s, ok := node.(*ast.StructLit)
if ok && len(s.Elts) <= 1 && f.current.nodeSep != blank && f.onOneLine(node) {
f.current.nodeSep = blank
}
f.current.cg = node.Comments()
f.visitComments(f.current.pos)
return true
}
return false
}
func (f *formatter) after(node ast.Node) {
f.visitComments(127)
p := len(f.stack) - 1
f.current = f.stack[p]
f.stack = f.stack[:p]
f.current.pos++
f.visitComments(f.current.pos)
}
func (f *formatter) visitComments(until int8) {
c := &f.current
printed := false
for ; len(c.cg) > 0 && c.cg[0].Position <= until; c.cg = c.cg[1:] {
if printed {
f.Print(newsection)
}
printed = true
f.printComment(c.cg[0])
}
}
func (f *formatter) printComment(cg *ast.CommentGroup) {
f.Print(cg)
printBlank := false
if cg.Doc && len(f.output) > 0 {
f.Print(newline)
printBlank = true
}
for _, c := range cg.List {
isEnd := strings.HasPrefix(c.Text, "//")
if !printBlank {
if isEnd {
f.Print(vtab)
} else {
f.Print(blank)
}
}
f.Print(c.Slash)
f.Print(c)
if isEnd {
f.Print(newline)
if cg.Doc {
f.Print(nooverride)
}
}
}
}