Debian Codegraph @

common/debug/debug.go

raw
1 // Copyright 2018 Google LLC
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
15 // Package debug provides tools to print a parsed expression graph and
16 // adorn each expression element with additional metadata.
17 package debug
18
19 import (
20 "bytes"
21 "fmt"
22 "strconv"
23 "strings"
24
25 "github.com/google/cel-go/common/ast"
26 "github.com/google/cel-go/common/types"
27 "github.com/google/cel-go/common/types/ref"
28 )
29
30 // Adorner returns debug metadata that will be tacked on to the string
31 // representation of an expression.
32 type Adorner interface {
33 // GetMetadata for the input context.
34 GetMetadata(ctx any) string
35 }
36
37 // Writer manages writing expressions to an internal string.
38 type Writer interface {
39 fmt.Stringer
40
41 // Buffer pushes an expression into an internal queue of expressions to
42 // write to a string.
43 Buffer(e ast.Expr)
44 }
45
46 type emptyDebugAdorner struct {
47 }
48
49 var emptyAdorner Adorner = &emptyDebugAdorner{}
50
51 func (a *emptyDebugAdorner) GetMetadata(e any) string {
52 return ""
53 }
54
55 // ToDebugString gives the unadorned string representation of the Expr.
56 func ToDebugString(e ast.Expr) string {
57 return ToAdornedDebugString(e, emptyAdorner)
58 }
59
60 // ToAdornedDebugString gives the adorned string representation of the Expr.
61 func ToAdornedDebugString(e ast.Expr, adorner Adorner) string {
62 w := newDebugWriter(adorner)
63 w.Buffer(e)
64 return w.String()
65 }
66
67 // debugWriter is used to print out pretty-printed debug strings.
68 type debugWriter struct {
69 adorner Adorner
70 buffer bytes.Buffer
71 indent int
72 lineStart bool
73 }
74
75 func newDebugWriter(a Adorner) *debugWriter {
76 return &debugWriter{
77 adorner: a,
78 indent: 0,
79 lineStart: true,
80 }
81 }
82
83 func (w *debugWriter) Buffer(e ast.Expr) {
84 if e == nil {
85 return
86 }
87 switch e.Kind() {
88 case ast.LiteralKind:
89 w.append(formatLiteral(e.AsLiteral()))
90 case ast.IdentKind:
91 w.append(e.AsIdent())
92 case ast.SelectKind:
93 w.appendSelect(e.AsSelect())
94 case ast.CallKind:
95 w.appendCall(e.AsCall())
96 case ast.ListKind:
97 w.appendList(e.AsList())
98 case ast.MapKind:
99 w.appendMap(e.AsMap())
100 case ast.StructKind:
101 w.appendStruct(e.AsStruct())
102 case ast.ComprehensionKind:
103 w.appendComprehension(e.AsComprehension())
104 }
105 w.adorn(e)
106 }
107
108 func (w *debugWriter) appendSelect(sel ast.SelectExpr) {
109 w.Buffer(sel.Operand())
110 w.append(".")
111 w.append(sel.FieldName())
112 if sel.IsTestOnly() {
113 w.append("~test-only~")
114 }
115 }
116
117 func (w *debugWriter) appendCall(call ast.CallExpr) {
118 if call.IsMemberFunction() {
119 w.Buffer(call.Target())
120 w.append(".")
121 }
122 w.append(call.FunctionName())
123 w.append("(")
124 if len(call.Args()) > 0 {
125 w.addIndent()
126 w.appendLine()
127 for i, arg := range call.Args() {
128 if i > 0 {
129 w.append(",")
130 w.appendLine()
131 }
132 w.Buffer(arg)
133 }
134 w.removeIndent()
135 w.appendLine()
136 }
137 w.append(")")
138 }
139
140 func (w *debugWriter) appendList(list ast.ListExpr) {
141 w.append("[")
142 if len(list.Elements()) > 0 {
143 w.appendLine()
144 w.addIndent()
145 for i, elem := range list.Elements() {
146 if i > 0 {
147 w.append(",")
148 w.appendLine()
149 }
150 w.Buffer(elem)
151 }
152 w.removeIndent()
153 w.appendLine()
154 }
155 w.append("]")
156 }
157
158 func (w *debugWriter) appendStruct(obj ast.StructExpr) {
159 w.append(obj.TypeName())
160 w.append("{")
161 if len(obj.Fields()) > 0 {
162 w.appendLine()
163 w.addIndent()
164 for i, f := range obj.Fields() {
165 field := f.AsStructField()
166 if i > 0 {
167 w.append(",")
168 w.appendLine()
169 }
170 if field.IsOptional() {
171 w.append("?")
172 }
173 w.append(field.Name())
174 w.append(":")
175 w.Buffer(field.Value())
176 w.adorn(f)
177 }
178 w.removeIndent()
179 w.appendLine()
180 }
181 w.append("}")
182 }
183
184 func (w *debugWriter) appendMap(m ast.MapExpr) {
185 w.append("{")
186 if m.Size() > 0 {
187 w.appendLine()
188 w.addIndent()
189 for i, e := range m.Entries() {
190 entry := e.AsMapEntry()
191 if i > 0 {
192 w.append(",")
193 w.appendLine()
194 }
195 if entry.IsOptional() {
196 w.append("?")
197 }
198 w.Buffer(entry.Key())
199 w.append(":")
200 w.Buffer(entry.Value())
201 w.adorn(e)
202 }
203 w.removeIndent()
204 w.appendLine()
205 }
206 w.append("}")
207 }
208
209 func (w *debugWriter) appendComprehension(comprehension ast.ComprehensionExpr) {
210 w.append("__comprehension__(")
211 w.addIndent()
212 w.appendLine()
213 w.append("// Variable")
214 w.appendLine()
215 w.append(comprehension.IterVar())
216 w.append(",")
217 w.appendLine()
218 if comprehension.HasIterVar2() {
219 w.append(comprehension.IterVar2())
220 w.append(",")
221 w.appendLine()
222 }
223 w.append("// Target")
224 w.appendLine()
225 w.Buffer(comprehension.IterRange())
226 w.append(",")
227 w.appendLine()
228 w.append("// Accumulator")
229 w.appendLine()
230 w.append(comprehension.AccuVar())
231 w.append(",")
232 w.appendLine()
233 w.append("// Init")
234 w.appendLine()
235 w.Buffer(comprehension.AccuInit())
236 w.append(",")
237 w.appendLine()
238 w.append("// LoopCondition")
239 w.appendLine()
240 w.Buffer(comprehension.LoopCondition())
241 w.append(",")
242 w.appendLine()
243 w.append("// LoopStep")
244 w.appendLine()
245 w.Buffer(comprehension.LoopStep())
246 w.append(",")
247 w.appendLine()
248 w.append("// Result")
249 w.appendLine()
250 w.Buffer(comprehension.Result())
251 w.append(")")
252 w.removeIndent()
253 }
254
255 func formatLiteral(c ref.Val) string {
256 switch v := c.(type) {
257 case types.Bool:
258 return fmt.Sprintf("%t", v)
259 case types.Bytes:
260 return fmt.Sprintf("b%s", strconv.Quote(string(v)))
261 case types.Double:
262 return fmt.Sprintf("%v", float64(v))
263 case types.Int:
264 return fmt.Sprintf("%d", int64(v))
265 case types.String:
266 return strconv.Quote(string(v))
267 case types.Uint:
268 return fmt.Sprintf("%du", uint64(v))
269 case types.Null:
270 return "null"
271 default:
272 panic("Unknown constant type")
273 }
274 }
275
276 func (w *debugWriter) append(s string) {
277 w.doIndent()
278 w.buffer.WriteString(s)
279 }
280
281 func (w *debugWriter) appendFormat(f string, args ...any) {
282 w.append(fmt.Sprintf(f, args...))
283 }
284
285 func (w *debugWriter) doIndent() {
286 if w.lineStart {
287 w.lineStart = false
288 w.buffer.WriteString(strings.Repeat(" ", w.indent))
289 }
290 }
291
292 func (w *debugWriter) adorn(e any) {
293 w.append(w.adorner.GetMetadata(e))
294 }
295
296 func (w *debugWriter) appendLine() {
297 w.buffer.WriteString("\n")
298 w.lineStart = true
299 }
300
301 func (w *debugWriter) addIndent() {
302 w.indent++
303 }
304
305 func (w *debugWriter) removeIndent() {
306 w.indent--
307 if w.indent < 0 {
308 panic("negative indent")
309 }
310 }
311
312 func (w *debugWriter) String() string {
313 return w.buffer.String()
314 }
315
316 type idAdorner struct{}
317
318 func (a *idAdorner) GetMetadata(elem any) string {
319 e, isExpr := elem.(ast.Expr)
320 if !isExpr {
321 return ""
322 }
323 return fmt.Sprintf("@id:%d ", e.ID())
324 }
325
326 // ToDebugStringWithIDs returns a string representation with AST node IDs.
327 func ToDebugStringWithIDs(e ast.Expr) string {
328 return ToAdornedDebugString(e, &idAdorner{})
329 }