forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pretty.go
84 lines (73 loc) · 1.61 KB
/
pretty.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
// Copyright 2018 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package ast
import (
"fmt"
"io"
"strings"
)
// Pretty writes a pretty representation of the AST rooted at x to w.
//
// This is function is intended for debug purposes when inspecting ASTs.
func Pretty(w io.Writer, x interface{}) {
pp := &prettyPrinter{
depth: -1,
w: w,
}
WalkBeforeAndAfter(pp, x)
}
type prettyPrinter struct {
depth int
w io.Writer
}
func (pp *prettyPrinter) Before(x interface{}) {
switch x.(type) {
case *Term:
default:
pp.depth++
}
}
func (pp *prettyPrinter) After(x interface{}) {
switch x.(type) {
case *Term:
default:
pp.depth--
}
}
func (pp *prettyPrinter) Visit(x interface{}) Visitor {
switch x := x.(type) {
case *Term:
return pp
case Args:
if len(x) == 0 {
return pp
}
pp.writeType(x)
case *Expr:
extras := []string{}
if x.Negated {
extras = append(extras, "negated")
}
extras = append(extras, fmt.Sprintf("index=%d", x.Index))
pp.writeIndent("%v %v", TypeName(x), strings.Join(extras, " "))
case Null, Boolean, Number, String, Var:
pp.writeValue(x)
default:
pp.writeType(x)
}
return pp
}
func (pp *prettyPrinter) writeValue(x interface{}) {
pp.writeIndent(fmt.Sprint(x))
}
func (pp *prettyPrinter) writeType(x interface{}) {
pp.writeIndent(TypeName(x))
}
func (pp *prettyPrinter) writeIndent(f string, a ...interface{}) {
pad := strings.Repeat(" ", pp.depth)
pp.write(pad+f, a...)
}
func (pp *prettyPrinter) write(f string, a ...interface{}) {
fmt.Fprintf(pp.w, f+"\n", a...)
}