blob: a51ad57bad47971d5ac85c81bf52d3ed59dc2fb0 [file] [log] [blame]
Marcel van Lohuizenb001da52018-12-10 15:34:30 +01001// Copyright 2018 The CUE Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package format
16
17import (
18 "fmt"
19 "strconv"
20 "strings"
21
22 "cuelang.org/go/cue/ast"
23 "cuelang.org/go/cue/parser"
24 "cuelang.org/go/cue/token"
25)
26
27func printNode(node interface{}, f *printer) error {
28 s := newFormatter(f)
29
30 // format node
31 f.allowed = nooverride // gobble initial whitespace.
32 switch x := node.(type) {
33 case *ast.File:
34 s.file(x)
35 case ast.Expr:
36 s.expr(x)
37 case ast.Decl:
38 s.decl(x)
39 // case ast.Node: // TODO: do we need this?
40 // s.walk(x)
41 case []ast.Decl:
42 s.walkDeclList(x)
43 default:
44 goto unsupported
45 }
46
47 return nil
48
49unsupported:
50 return fmt.Errorf("cue/format: unsupported node type %T", node)
51}
52
53// Helper functions for common node lists. They may be empty.
54
55func (f *formatter) walkDeclList(list []ast.Decl) {
56 f.before(nil)
57 for i, x := range list {
58 if i > 0 {
59 f.print(declcomma)
60 }
61 f.decl(x)
62 f.print(f.current.parentSep)
63 }
64 f.after(nil)
65}
66
67func (f *formatter) walkSpecList(list []*ast.ImportSpec) {
68 f.before(nil)
69 for _, x := range list {
70 f.importSpec(x)
71 }
72 f.after(nil)
73}
74
75func (f *formatter) walkClauseList(list []ast.Clause) {
76 f.before(nil)
77 for _, x := range list {
78 f.clause(x)
79 }
80 f.after(nil)
81}
82
83func (f *formatter) walkExprList(list []ast.Expr, depth int) {
84 f.before(nil)
85 for _, x := range list {
86 f.before(x)
87 f.exprRaw(x, token.LowestPrec, depth)
88 f.print(comma, blank)
89 f.after(x)
90 }
91 f.after(nil)
92}
93
94func (f *formatter) file(file *ast.File) {
95 f.before(file)
96 if file.Name != nil {
97 f.print(file.Package, "package")
98 f.print(blank, file.Name, newline, newsection)
99 }
100 f.current.pos = 3
101 f.visitComments(3)
102 f.walkDeclList(file.Decls)
103 f.after(file)
104 f.print(token.EOF)
105}
106func (f *formatter) decl(decl ast.Decl) {
107 if decl == nil {
108 return
109 }
110 if !f.before(decl) {
111 goto after
112 }
113 switch n := decl.(type) {
114 case *ast.Field:
115 // shortcut single-element structs.
116 lastSize := len(f.labelBuf)
117 f.labelBuf = f.labelBuf[:0]
118 first := n.Label
119 for {
120 obj, ok := n.Value.(*ast.StructLit)
121 if !ok || len(obj.Elts) != 1 || (obj.Lbrace.IsValid() && !f.printer.cfg.simplify) {
122 break
123 }
124
125 // Verify that struct doesn't have inside comments and that
126 // element doesn't have doc comments.
127 hasComments := len(obj.Elts[0].Comments()) > 0
128 for _, c := range obj.Comments() {
129 if c.Position == 1 || c.Position == 2 {
130 hasComments = true
131 }
132 }
133 if hasComments {
134 break
135 }
136
137 mem, ok := obj.Elts[0].(*ast.Field)
138 if !ok {
139 break
140 }
141 f.labelBuf = append(f.labelBuf, mem.Label)
142 n = mem
143 }
144
145 if lastSize != len(f.labelBuf) {
146 f.print(formfeed)
147 }
148
149 f.before(nil)
150 f.label(first)
151 for _, x := range f.labelBuf {
152 f.print(blank, nooverride)
153 f.label(x)
154 }
155 f.after(nil)
156
157 nextFF := f.nextNeedsFormfeed(n.Value)
158 tab := vtab
159 if nextFF || f.nestExpr >= 1 {
160 tab = blank
161 }
162
163 f.print(n.Colon, token.COLON, tab)
164 if n.Value != nil {
165 f.expr(n.Value)
166 } else {
167 f.current.pos++
168 f.visitComments(f.current.pos)
169 }
170
171 if nextFF {
172 f.print(formfeed)
173 }
174
175 case *ast.ComprehensionDecl:
176 f.decl(n.Field)
177 f.print(blank)
178 if n.Select != token.NoPos {
179 f.print(n.Select, token.ARROW, blank)
180 }
181 f.print(indent)
182 f.walkClauseList(n.Clauses)
183 f.print(unindent)
184 f.print("") // force whitespace to be written
185
186 case *ast.BadDecl:
187 f.print(n.From, "*bad decl*", declcomma)
188
189 case *ast.ImportDecl:
190 f.print(n.Import, "import")
191 if len(n.Specs) == 0 {
192 f.print(blank, n.Lparen, token.LPAREN, n.Rparen, token.RPAREN, newline)
193 }
194 switch {
195 case len(n.Specs) == 1:
196 if !n.Lparen.IsValid() {
197 f.print(blank)
198 f.walkSpecList(n.Specs)
199 break
200 }
201 fallthrough
202 default:
203 f.print(blank, n.Lparen, token.LPAREN, newline, indent)
204 f.walkSpecList(n.Specs)
205 f.print(unindent, newline, n.Rparen, token.RPAREN, newline)
206 }
207 f.print(newsection)
208
209 case *ast.EmitDecl:
210 f.expr(n.Expr)
211 f.print(newline, newsection) // force newline
212
213 case *ast.Alias:
214 f.expr(n.Ident)
215 f.print(blank, n.Equal, token.BIND, blank)
216 f.expr(n.Expr)
217 f.print(declcomma, newline) // implied
218 }
219after:
220 f.after(decl)
221}
222
223func (f *formatter) nextNeedsFormfeed(n ast.Expr) bool {
224 switch x := n.(type) {
225 case *ast.StructLit:
226 return true
227 case *ast.BasicLit:
228 return strings.IndexByte(x.Value, '\n') >= 0
229 case *ast.ListLit:
230 return true
231 }
232 return false
233}
234
235func (f *formatter) importSpec(x *ast.ImportSpec) {
236 if x.Name != nil {
237 f.label(x.Name)
238 f.print(blank)
239 } else {
240 f.current.pos++
241 f.visitComments(f.current.pos)
242 }
243 f.expr(x.Path)
244 f.print(newline)
245}
246
247func (f *formatter) label(l ast.Label) {
248 switch n := l.(type) {
249 case *ast.Ident:
250 f.print(n.NamePos, n)
251
252 case *ast.BasicLit:
253 if f.cfg.simplify && n.Kind == token.STRING && len(n.Value) > 2 {
254 s := n.Value
255 unquoted, err := strconv.Unquote(s)
256 fset := token.NewFileSet()
257 if err == nil {
258 e, _ := parser.ParseExpr(fset, "check", unquoted)
259 if _, ok := e.(*ast.Ident); ok {
260 f.print(n.ValuePos, unquoted)
261 break
262 }
263 }
264 }
265 f.print(n.ValuePos, n.Value)
266
267 case *ast.TemplateLabel:
268 f.print(n.Langle, token.LSS, indent)
269 f.label(n.Ident)
270 f.print(unindent, n.Rangle, token.GTR)
271
272 case *ast.Interpolation:
273 f.expr(n)
274
Marcel van Lohuizenb001da52018-12-10 15:34:30 +0100275 default:
276 panic(fmt.Sprintf("unknown label type %T", n))
277 }
278}
279
280func (f *formatter) expr(x ast.Expr) {
281 const depth = 1
282 f.expr1(x, token.LowestPrec, depth)
283}
284
285func (f *formatter) expr0(x ast.Expr, depth int) {
286 f.expr1(x, token.LowestPrec, depth)
287}
288
289func (f *formatter) expr1(expr ast.Expr, prec1, depth int) {
290 if f.before(expr) {
291 f.exprRaw(expr, prec1, depth)
292 }
293 f.after(expr)
294}
295
296func (f *formatter) exprRaw(expr ast.Expr, prec1, depth int) {
297
298 switch x := expr.(type) {
299 case *ast.BadExpr:
300 f.print(x.From, "BadExpr")
301
302 case *ast.BottomLit:
303 f.print(x.Bottom, token.BOTTOM)
304
305 case *ast.Ident:
306 f.print(x.NamePos, x)
307
308 case *ast.BinaryExpr:
309 if depth < 1 {
310 f.internalError("depth < 1:", depth)
311 depth = 1
312 }
313 if prec1 == 8 { // ..
314 prec1 = 9 // always parentheses for values of ranges
315 }
316 f.binaryExpr(x, prec1, cutoff(x, depth), depth)
317
318 case *ast.UnaryExpr:
319 const prec = token.UnaryPrec
320 if prec < prec1 {
321 // parenthesis needed
322 f.print(token.LPAREN, nooverride)
323 f.expr(x)
324 f.print(token.RPAREN)
325 } else {
326 // no parenthesis needed
327 f.print(x.OpPos, x.Op, nooverride)
328 f.expr1(x.X, prec, depth)
329 }
330
331 case *ast.BasicLit:
332 f.print(x.ValuePos, x)
333
334 case *ast.Interpolation:
335 f.before(nil)
336 for _, x := range x.Elts {
337 f.expr0(x, depth+1)
338 }
339 f.after(nil)
340
341 case *ast.ParenExpr:
342 if _, hasParens := x.X.(*ast.ParenExpr); hasParens {
343 // don't print parentheses around an already parenthesized expression
344 // TODO: consider making this more general and incorporate precedence levels
345 f.expr0(x.X, depth)
346 } else {
347 f.print(x.Lparen, token.LPAREN)
348 f.expr0(x.X, reduceDepth(depth)) // parentheses undo one level of depth
349 f.print(x.Rparen, token.RPAREN)
350 }
351
352 case *ast.SelectorExpr:
353 f.selectorExpr(x, depth)
354
355 case *ast.IndexExpr:
356 f.expr1(x.X, token.HighestPrec, 1)
357 f.print(x.Lbrack, token.LBRACK)
358 f.expr0(x.Index, depth+1)
359 f.print(x.Rbrack, token.RBRACK)
360
361 case *ast.SliceExpr:
362 f.expr1(x.X, token.HighestPrec, 1)
363 f.print(x.Lbrack, token.LBRACK)
364 indices := []ast.Expr{x.Low, x.High}
365 for i, y := range indices {
366 if i > 0 {
367 // blanks around ":" if both sides exist and either side is a binary expression
368 x := indices[i-1]
369 if depth <= 1 && x != nil && y != nil && (isBinary(x) || isBinary(y)) {
370 f.print(blank, token.COLON, blank)
371 } else {
372 f.print(token.COLON)
373 }
374 }
375 if y != nil {
376 f.expr0(y, depth+1)
377 }
378 }
379 f.print(x.Rbrack, token.RBRACK)
380
381 case *ast.CallExpr:
382 if len(x.Args) > 1 {
383 depth++
384 }
385 wasIndented := f.possibleSelectorExpr(x.Fun, token.HighestPrec, depth)
386 f.print(x.Lparen, token.LPAREN)
387 f.walkExprList(x.Args, depth)
388 f.print(trailcomma, noblank, x.Rparen, token.RPAREN)
389 if wasIndented {
390 f.print(unindent)
391 }
392
393 case *ast.Ellipsis:
394 f.print(x.Ellipsis, token.ELLIPSIS)
395 if x.Elt != nil {
396 f.expr(x.Elt) // TODO
397 }
398
399 case *ast.StructLit:
400 f.print(x.Lbrace, token.LBRACE, noblank, f.formfeed(), indent)
401 f.walkDeclList(x.Elts)
402 f.matchUnindent()
403 f.print(noblank, x.Rbrace, token.RBRACE)
404
405 case *ast.ListLit:
406 f.print(x.Lbrack, token.LBRACK, indent)
407 f.walkExprList(x.Elts, 1)
408 if x.Ellipsis != token.NoPos || x.Type != nil {
409 f.print(x.Ellipsis, token.ELLIPSIS)
410 if x.Type != nil && !isTop(x.Type) {
411 f.expr(x.Type)
412 }
413 } else {
414 f.print(trailcomma, noblank)
415 f.current.pos += 2
416 f.visitComments(f.current.pos)
417 }
418 f.matchUnindent()
419 f.print(noblank, x.Rbrack, token.RBRACK)
420
421 case *ast.ListComprehension:
422 f.print(x.Lbrack, token.LBRACK, blank, indent)
423 f.expr(x.Expr)
424 f.print(blank)
425 f.walkClauseList(x.Clauses)
426 f.print(unindent, f.wsOverride(blank), x.Rbrack, token.RBRACK)
427
Marcel van Lohuizenb001da52018-12-10 15:34:30 +0100428 default:
429 panic(fmt.Sprintf("unimplemented type %T", x))
430 }
431 return
432}
433
434func (f *formatter) clause(clause ast.Clause) {
435 switch n := clause.(type) {
436 case *ast.ForClause:
437 f.print(blank, n.For, "for", blank)
438 if n.Key != nil {
439 f.label(n.Key)
440 f.print(n.Colon, token.COMMA, blank)
441 } else {
442 f.current.pos++
443 f.visitComments(f.current.pos)
444 }
445 f.label(n.Value)
446 f.print(blank, n.In, "in", blank)
447 f.expr(n.Source)
448
449 case *ast.IfClause:
450 f.print(blank, n.If, "if", blank)
451 f.expr(n.Condition)
452
453 default:
454 panic("unknown clause type")
455 }
456}
457
458func walkBinary(e *ast.BinaryExpr) (has6, has7, has8 bool, maxProblem int) {
459 switch e.Op.Precedence() {
460 case 6:
461 has6 = true
462 case 7:
463 has7 = true
464 case 8:
465 has8 = true
466 }
467
468 switch l := e.X.(type) {
469 case *ast.BinaryExpr:
470 if l.Op.Precedence() < e.Op.Precedence() {
471 // parens will be inserted.
472 // pretend this is an *syntax.ParenExpr and do nothing.
473 break
474 }
475 h6, h7, h8, mp := walkBinary(l)
476 has6 = has6 || h6
477 has7 = has7 || h7
478 has8 = has8 || h8
479 if maxProblem < mp {
480 maxProblem = mp
481 }
482 }
483
484 switch r := e.Y.(type) {
485 case *ast.BinaryExpr:
486 if r.Op.Precedence() <= e.Op.Precedence() {
487 // parens will be inserted.
488 // pretend this is an *syntax.ParenExpr and do nothing.
489 break
490 }
491 h6, h7, h8, mp := walkBinary(r)
492 has6 = has6 || h6
493 has7 = has7 || h7
494 has8 = has8 || h8
495 if maxProblem < mp {
496 maxProblem = mp
497 }
498
499 case *ast.UnaryExpr:
500 switch e.Op.String() + r.Op.String() {
501 case "/*":
502 maxProblem = 8
503 case "++", "--":
504 if maxProblem < 6 {
505 maxProblem = 6
506 }
507 }
508 }
509 return
510}
511
512func cutoff(e *ast.BinaryExpr, depth int) int {
513 has6, has7, has8, maxProblem := walkBinary(e)
514 if maxProblem > 0 {
515 return maxProblem + 1
516 }
517 if (has6 || has7) && has8 {
518 if depth == 1 {
519 return 8
520 }
521 if has7 {
522 return 7
523 }
524 return 6
525 }
526 if has6 && has7 {
527 if depth == 1 {
528 return 7
529 }
530 return 6
531 }
532 if depth == 1 {
533 return 8
534 }
535 return 6
536}
537
538func diffPrec(expr ast.Expr, prec int) int {
539 x, ok := expr.(*ast.BinaryExpr)
540 if !ok || prec != x.Op.Precedence() {
541 return 1
542 }
543 return 0
544}
545
546func reduceDepth(depth int) int {
547 depth--
548 if depth < 1 {
549 depth = 1
550 }
551 return depth
552}
553
554// Format the binary expression: decide the cutoff and then format.
555// Let's call depth == 1 Normal mode, and depth > 1 Compact mode.
556// (Algorithm suggestion by Russ Cox.)
557//
558// The precedences are:
559// 8 ..
560// 7 * / % quo rem div mod
561// 6 + -
562// 5 == != < <= > >=
563// 4 &&
564// 3 ||
565// 2 &
566// 1 |
567//
568// The only decision is whether there will be spaces around levels 6 and 7.
569// There are never spaces at level 8 (unary), and always spaces at levels 5 and below.
570//
571// To choose the cutoff, look at the whole expression but excluding primary
572// expressions (function calls, parenthesized exprs), and apply these rules:
573//
574// 1) If there is a binary operator with a right side unary operand
575// that would clash without a space, the cutoff must be (in order):
576//
577// /* 8
578// ++ 7 // not necessary, but to avoid confusion
579// -- 7
580//
581// (Comparison operators always have spaces around them.)
582//
583// 2) If there is a mix of level 7 and level 6 operators, then the cutoff
584// is 7 (use spaces to distinguish precedence) in Normal mode
585// and 6 (never use spaces) in Compact mode.
586//
587// 3) If there are no level 6 operators or no level 7 operators, then the
588// cutoff is 8 (always use spaces) in Normal mode
589// and 6 (never use spaces) in Compact mode.
590//
591func (f *formatter) binaryExpr(x *ast.BinaryExpr, prec1, cutoff, depth int) {
592 f.nestExpr++
593 defer func() { f.nestExpr-- }()
594
595 prec := x.Op.Precedence()
596 if prec < prec1 {
597 // parenthesis needed
598 // Note: The parser inserts an syntax.ParenExpr node; thus this case
599 // can only occur if the AST is created in a different way.
600 // defer p.pushComment(nil).pop()
601 f.print(token.LPAREN, nooverride)
602 f.expr0(x, reduceDepth(depth)) // parentheses undo one level of depth
603 f.print(token.RPAREN)
604 return
605 }
606
607 printBlank := prec < cutoff
608
609 ws := indent
610 f.expr1(x.X, prec, depth+diffPrec(x.X, prec))
611 f.print(nooverride)
612 if printBlank {
613 f.print(blank)
614 }
615 f.print(x.OpPos, x.Op)
616 if x.Y.Pos().IsNewline() {
617 // at least one line break, but respect an extra empty line
618 // in the source
619 f.print(formfeed)
620 printBlank = false // no blank after line break
621 } else {
622 f.print(nooverride)
623 }
624 if printBlank {
625 f.print(blank)
626 }
627 f.expr1(x.Y, prec+1, depth+1)
628 if ws == ignore {
629 f.print(unindent)
630 }
631}
632
633func isBinary(expr ast.Expr) bool {
634 _, ok := expr.(*ast.BinaryExpr)
635 return ok
636}
637
638func (f *formatter) possibleSelectorExpr(expr ast.Expr, prec1, depth int) bool {
639 if x, ok := expr.(*ast.SelectorExpr); ok {
640 return f.selectorExpr(x, depth)
641 }
642 f.expr1(expr, prec1, depth)
643 return false
644}
645
646// selectorExpr handles an *syntax.SelectorExpr node and returns whether x spans
647// multiple lines.
648func (f *formatter) selectorExpr(x *ast.SelectorExpr, depth int) bool {
649 f.expr1(x.X, token.HighestPrec, depth)
650 f.print(token.PERIOD)
651 if x.Sel.Pos().IsNewline() {
652 f.print(indent, formfeed, x.Sel.Pos(), x.Sel)
653 f.print(unindent)
654 return true
655 }
656 f.print(x.Sel.Pos(), x.Sel)
657 return false
658}
659
660func isTop(e ast.Expr) bool {
661 ident, ok := e.(*ast.Ident)
662 return ok && ident.Name == "_"
663}