Debian Codegraph @

parser/unparser.go

raw
1 // Copyright 2019 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 parser
16
17 import (
18 "errors"
19 "fmt"
20 "regexp"
21 "strconv"
22 "strings"
23
24 "github.com/google/cel-go/common/ast"
25 "github.com/google/cel-go/common/operators"
26 "github.com/google/cel-go/common/types"
27 "github.com/google/cel-go/common/types/ref"
28 )
29
30 // Unparse takes an input expression and source position information and generates a human-readable
31 // expression.
32 //
33 // Note, unparsing an AST will often generate the same expression as was originally parsed, but some
34 // formatting may be lost in translation, notably:
35 //
36 // - All quoted literals are doubled quoted.
37 // - Byte literals are represented as octal escapes (same as Google SQL).
38 // - Floating point values are converted to the small number of digits needed to represent the value.
39 // - Spacing around punctuation marks may be lost.
40 // - Parentheses will only be applied when they affect operator precedence.
41 //
42 // This function optionally takes in one or more UnparserOption to alter the unparsing behavior, such as
43 // performing word wrapping on expressions.
44 func Unparse(expr ast.Expr, info *ast.SourceInfo, opts ...UnparserOption) (string, error) {
45 unparserOpts := &unparserOption{
46 wrapOnColumn: defaultWrapOnColumn,
47 wrapAfterColumnLimit: defaultWrapAfterColumnLimit,
48 operatorsToWrapOn: defaultOperatorsToWrapOn,
49 }
50
51 var err error
52 for _, opt := range opts {
53 unparserOpts, err = opt(unparserOpts)
54 if err != nil {
55 return "", err
56 }
57 }
58
59 un := &unparser{
60 info: info,
61 options: unparserOpts,
62 }
63 err = un.visit(expr)
64 if err != nil {
65 return "", err
66 }
67 return un.str.String(), nil
68 }
69
70 var identifierPartPattern *regexp.Regexp = regexp.MustCompile(`^[A-Za-z_][0-9A-Za-z_]*$`)
71
72 func maybeQuoteField(field string) string {
73 if !identifierPartPattern.MatchString(field) || field == "in" {
74 return "`" + field + "`"
75 }
76 return field
77 }
78
79 // unparser visits an expression to reconstruct a human-readable string from an AST.
80 type unparser struct {
81 str strings.Builder
82 info *ast.SourceInfo
83 options *unparserOption
84 lastWrappedIndex int
85 }
86
87 func (un *unparser) visit(expr ast.Expr) error {
88 if expr == nil {
89 return errors.New("unsupported expression")
90 }
91 visited, err := un.visitMaybeMacroCall(expr)
92 if visited || err != nil {
93 return err
94 }
95 switch expr.Kind() {
96 case ast.CallKind:
97 return un.visitCall(expr)
98 case ast.LiteralKind:
99 return un.visitConst(expr)
100 case ast.IdentKind:
101 return un.visitIdent(expr)
102 case ast.ListKind:
103 return un.visitList(expr)
104 case ast.MapKind:
105 return un.visitStructMap(expr)
106 case ast.SelectKind:
107 return un.visitSelect(expr)
108 case ast.StructKind:
109 return un.visitStructMsg(expr)
110 default:
111 return fmt.Errorf("unsupported expression: %v", expr)
112 }
113 }
114
115 func (un *unparser) visitCall(expr ast.Expr) error {
116 c := expr.AsCall()
117 fun := c.FunctionName()
118 switch fun {
119 // ternary operator
120 case operators.Conditional:
121 return un.visitCallConditional(expr)
122 // optional select operator
123 case operators.OptSelect:
124 return un.visitOptSelect(expr)
125 // index operator
126 case operators.Index:
127 return un.visitCallIndex(expr)
128 // optional index operator
129 case operators.OptIndex:
130 return un.visitCallOptIndex(expr)
131 // unary operators
132 case operators.LogicalNot, operators.Negate:
133 return un.visitCallUnary(expr)
134 // binary operators
135 case operators.Add,
136 operators.Divide,
137 operators.Equals,
138 operators.Greater,
139 operators.GreaterEquals,
140 operators.In,
141 operators.Less,
142 operators.LessEquals,
143 operators.LogicalAnd,
144 operators.LogicalOr,
145 operators.Modulo,
146 operators.Multiply,
147 operators.NotEquals,
148 operators.OldIn,
149 operators.Subtract:
150 return un.visitCallBinary(expr)
151 // standard function calls.
152 default:
153 return un.visitCallFunc(expr)
154 }
155 }
156
157 func (un *unparser) visitCallBinary(expr ast.Expr) error {
158 c := expr.AsCall()
159 fun := c.FunctionName()
160 args := c.Args()
161 lhs := args[0]
162 // add parens if the current operator is lower precedence than the lhs expr operator.
163 lhsParen := isComplexOperatorWithRespectTo(fun, lhs)
164 rhs := args[1]
165 // add parens if the current operator is lower precedence than the rhs expr operator,
166 // or the same precedence and the operator is left recursive.
167 rhsParen := isComplexOperatorWithRespectTo(fun, rhs)
168 if !rhsParen && isLeftRecursive(fun) {
169 rhsParen = isSamePrecedence(fun, rhs)
170 }
171 err := un.visitMaybeNested(lhs, lhsParen)
172 if err != nil {
173 return err
174 }
175 unmangled, found := operators.FindReverseBinaryOperator(fun)
176 if !found {
177 return fmt.Errorf("cannot unmangle operator: %s", fun)
178 }
179
180 un.writeOperatorWithWrapping(fun, unmangled)
181 return un.visitMaybeNested(rhs, rhsParen)
182 }
183
184 func (un *unparser) visitCallConditional(expr ast.Expr) error {
185 c := expr.AsCall()
186 args := c.Args()
187 // add parens if operand is a conditional itself.
188 nested := isSamePrecedence(operators.Conditional, args[0]) ||
189 isComplexOperator(args[0])
190 err := un.visitMaybeNested(args[0], nested)
191 if err != nil {
192 return err
193 }
194 un.writeOperatorWithWrapping(operators.Conditional, "?")
195
196 // add parens if operand is a conditional itself.
197 nested = isSamePrecedence(operators.Conditional, args[1]) ||
198 isComplexOperator(args[1])
199 err = un.visitMaybeNested(args[1], nested)
200 if err != nil {
201 return err
202 }
203
204 un.str.WriteString(" : ")
205 // add parens if operand is a conditional itself.
206 nested = isSamePrecedence(operators.Conditional, args[2]) ||
207 isComplexOperator(args[2])
208
209 return un.visitMaybeNested(args[2], nested)
210 }
211
212 func (un *unparser) visitCallFunc(expr ast.Expr) error {
213 c := expr.AsCall()
214 fun := c.FunctionName()
215 args := c.Args()
216 if c.IsMemberFunction() {
217 nested := isBinaryOrTernaryOperator(c.Target())
218 err := un.visitMaybeNested(c.Target(), nested)
219 if err != nil {
220 return err
221 }
222 un.str.WriteString(".")
223 }
224 un.str.WriteString(fun)
225 un.str.WriteString("(")
226 for i, arg := range args {
227 err := un.visit(arg)
228 if err != nil {
229 return err
230 }
231 if i < len(args)-1 {
232 un.str.WriteString(", ")
233 }
234 }
235 un.str.WriteString(")")
236 return nil
237 }
238
239 func (un *unparser) visitCallIndex(expr ast.Expr) error {
240 return un.visitCallIndexInternal(expr, "[")
241 }
242
243 func (un *unparser) visitCallOptIndex(expr ast.Expr) error {
244 return un.visitCallIndexInternal(expr, "[?")
245 }
246
247 func (un *unparser) visitCallIndexInternal(expr ast.Expr, op string) error {
248 c := expr.AsCall()
249 args := c.Args()
250 nested := isBinaryOrTernaryOperator(args[0])
251 err := un.visitMaybeNested(args[0], nested)
252 if err != nil {
253 return err
254 }
255 un.str.WriteString(op)
256 err = un.visit(args[1])
257 if err != nil {
258 return err
259 }
260 un.str.WriteString("]")
261 return nil
262 }
263
264 func (un *unparser) visitCallUnary(expr ast.Expr) error {
265 c := expr.AsCall()
266 fun := c.FunctionName()
267 args := c.Args()
268 unmangled, found := operators.FindReverse(fun)
269 if !found {
270 return fmt.Errorf("cannot unmangle operator: %s", fun)
271 }
272 un.str.WriteString(unmangled)
273 nested := isComplexOperator(args[0])
274 return un.visitMaybeNested(args[0], nested)
275 }
276
277 func (un *unparser) visitConstVal(val ref.Val) error {
278 optional := false
279 if optVal, ok := val.(*types.Optional); ok {
280 if !optVal.HasValue() {
281 un.str.WriteString("optional.none()")
282 return nil
283 }
284 optional = true
285 un.str.WriteString("optional.of(")
286 val = optVal.GetValue()
287 }
288 switch val := val.(type) {
289 case types.Bool:
290 un.str.WriteString(strconv.FormatBool(bool(val)))
291 case types.Bytes:
292 // bytes constants are surrounded with b"<bytes>"
293 un.str.WriteString(`b"`)
294 un.str.WriteString(bytesToOctets([]byte(val)))
295 un.str.WriteString(`"`)
296 case types.Double:
297 // represent the float using the minimum required digits
298 d := strconv.FormatFloat(float64(val), 'g', -1, 64)
299 un.str.WriteString(d)
300 if !strings.Contains(d, ".") {
301 un.str.WriteString(".0")
302 }
303 case types.Int:
304 i := strconv.FormatInt(int64(val), 10)
305 un.str.WriteString(i)
306 case types.Null:
307 un.str.WriteString("null")
308 case types.String:
309 // strings will be double quoted with quotes escaped.
310 un.str.WriteString(strconv.Quote(string(val)))
311 case types.Uint:
312 // uint literals have a 'u' suffix.
313 ui := strconv.FormatUint(uint64(val), 10)
314 un.str.WriteString(ui)
315 un.str.WriteString("u")
316 case *types.Optional:
317 if err := un.visitConstVal(val); err != nil {
318 return err
319 }
320 default:
321 return errors.New("unsupported constant")
322 }
323 if optional {
324 un.str.WriteString(")")
325 }
326 return nil
327 }
328 func (un *unparser) visitConst(expr ast.Expr) error {
329 val := expr.AsLiteral()
330 if err := un.visitConstVal(val); err != nil {
331 return fmt.Errorf("unsupported constant: %v", expr)
332 }
333 return nil
334 }
335
336 func (un *unparser) visitIdent(expr ast.Expr) error {
337 un.str.WriteString(expr.AsIdent())
338 return nil
339 }
340
341 func (un *unparser) visitList(expr ast.Expr) error {
342 l := expr.AsList()
343 elems := l.Elements()
344 optIndices := make(map[int]bool, len(elems))
345 for _, idx := range l.OptionalIndices() {
346 optIndices[int(idx)] = true
347 }
348 un.str.WriteString("[")
349 for i, elem := range elems {
350 if optIndices[i] {
351 un.str.WriteString("?")
352 }
353 err := un.visit(elem)
354 if err != nil {
355 return err
356 }
357 if i < len(elems)-1 {
358 un.str.WriteString(", ")
359 }
360 }
361 un.str.WriteString("]")
362 return nil
363 }
364
365 func (un *unparser) visitOptSelect(expr ast.Expr) error {
366 c := expr.AsCall()
367 args := c.Args()
368 operand := args[0]
369 field := args[1].AsLiteral().(types.String)
370 return un.visitSelectInternal(operand, false, ".?", string(field))
371 }
372
373 func (un *unparser) visitSelect(expr ast.Expr) error {
374 sel := expr.AsSelect()
375 return un.visitSelectInternal(sel.Operand(), sel.IsTestOnly(), ".", sel.FieldName())
376 }
377
378 func (un *unparser) visitSelectInternal(operand ast.Expr, testOnly bool, op string, field string) error {
379 // handle the case when the select expression was generated by the has() macro.
380 if testOnly {
381 un.str.WriteString("has(")
382 }
383 nested := !testOnly && isBinaryOrTernaryOperator(operand)
384 err := un.visitMaybeNested(operand, nested)
385 if err != nil {
386 return err
387 }
388 un.str.WriteString(op)
389 un.str.WriteString(maybeQuoteField(field))
390 if testOnly {
391 un.str.WriteString(")")
392 }
393 return nil
394 }
395
396 func (un *unparser) visitStructMsg(expr ast.Expr) error {
397 m := expr.AsStruct()
398 fields := m.Fields()
399 un.str.WriteString(m.TypeName())
400 un.str.WriteString("{")
401 for i, f := range fields {
402 field := f.AsStructField()
403 f := field.Name()
404 if field.IsOptional() {
405 un.str.WriteString("?")
406 }
407 un.str.WriteString(maybeQuoteField(f))
408 un.str.WriteString(": ")
409 v := field.Value()
410 err := un.visit(v)
411 if err != nil {
412 return err
413 }
414 if i < len(fields)-1 {
415 un.str.WriteString(", ")
416 }
417 }
418 un.str.WriteString("}")
419 return nil
420 }
421
422 func (un *unparser) visitStructMap(expr ast.Expr) error {
423 m := expr.AsMap()
424 entries := m.Entries()
425 un.str.WriteString("{")
426 for i, e := range entries {
427 entry := e.AsMapEntry()
428 k := entry.Key()
429 if entry.IsOptional() {
430 un.str.WriteString("?")
431 }
432 err := un.visit(k)
433 if err != nil {
434 return err
435 }
436 un.str.WriteString(": ")
437 v := entry.Value()
438 err = un.visit(v)
439 if err != nil {
440 return err
441 }
442 if i < len(entries)-1 {
443 un.str.WriteString(", ")
444 }
445 }
446 un.str.WriteString("}")
447 return nil
448 }
449
450 func (un *unparser) visitMaybeMacroCall(expr ast.Expr) (bool, error) {
451 call, found := un.info.GetMacroCall(expr.ID())
452 if !found {
453 return false, nil
454 }
455 return true, un.visit(call)
456 }
457
458 func (un *unparser) visitMaybeNested(expr ast.Expr, nested bool) error {
459 if nested {
460 un.str.WriteString("(")
461 }
462 err := un.visit(expr)
463 if err != nil {
464 return err
465 }
466 if nested {
467 un.str.WriteString(")")
468 }
469 return nil
470 }
471
472 // isLeftRecursive indicates whether the parser resolves the call in a left-recursive manner as
473 // this can have an effect of how parentheses affect the order of operations in the AST.
474 func isLeftRecursive(op string) bool {
475 return op != operators.LogicalAnd && op != operators.LogicalOr
476 }
477
478 // isSamePrecedence indicates whether the precedence of the input operator is the same as the
479 // precedence of the (possible) operation represented in the input Expr.
480 //
481 // If the expr is not a Call, the result is false.
482 func isSamePrecedence(op string, expr ast.Expr) bool {
483 if expr.Kind() != ast.CallKind {
484 return false
485 }
486 c := expr.AsCall()
487 other := c.FunctionName()
488 return operators.Precedence(op) == operators.Precedence(other)
489 }
490
491 // isLowerPrecedence indicates whether the precedence of the input operator is lower precedence
492 // than the (possible) operation represented in the input Expr.
493 //
494 // If the expr is not a Call, the result is false.
495 func isLowerPrecedence(op string, expr ast.Expr) bool {
496 c := expr.AsCall()
497 other := c.FunctionName()
498 return operators.Precedence(op) < operators.Precedence(other)
499 }
500
501 // Indicates whether the expr is a complex operator, i.e., a call expression
502 // with 2 or more arguments.
503 func isComplexOperator(expr ast.Expr) bool {
504 if expr.Kind() == ast.CallKind && len(expr.AsCall().Args()) >= 2 {
505 return true
506 }
507 return false
508 }
509
510 // Indicates whether it is a complex operation compared to another.
511 // expr is *not* considered complex if it is not a call expression or has
512 // less than two arguments, or if it has a higher precedence than op.
513 func isComplexOperatorWithRespectTo(op string, expr ast.Expr) bool {
514 if expr.Kind() != ast.CallKind || len(expr.AsCall().Args()) < 2 {
515 return false
516 }
517 return isLowerPrecedence(op, expr)
518 }
519
520 // Indicate whether this is a binary or ternary operator.
521 func isBinaryOrTernaryOperator(expr ast.Expr) bool {
522 if expr.Kind() != ast.CallKind || len(expr.AsCall().Args()) < 2 {
523 return false
524 }
525 _, isBinaryOp := operators.FindReverseBinaryOperator(expr.AsCall().FunctionName())
526 return isBinaryOp || isSamePrecedence(operators.Conditional, expr)
527 }
528
529 // bytesToOctets converts byte sequences to a string using a three digit octal encoded value
530 // per byte.
531 func bytesToOctets(byteVal []byte) string {
532 var b strings.Builder
533 for _, c := range byteVal {
534 fmt.Fprintf(&b, "\\%03o", c)
535 }
536 return b.String()
537 }
538
539 // writeOperatorWithWrapping outputs the operator and inserts a newline for operators configured
540 // in the unparser options.
541 func (un *unparser) writeOperatorWithWrapping(fun string, unmangled string) bool {
542 _, wrapOperatorExists := un.options.operatorsToWrapOn[fun]
543 lineLength := un.str.Len() - un.lastWrappedIndex + len(fun)
544
545 if wrapOperatorExists && lineLength >= un.options.wrapOnColumn {
546 un.lastWrappedIndex = un.str.Len()
547 // wrapAfterColumnLimit flag dictates whether the newline is placed
548 // before or after the operator
549 if un.options.wrapAfterColumnLimit {
550 // Input: a && b
551 // Output: a &&\nb
552 un.str.WriteString(" ")
553 un.str.WriteString(unmangled)
554 un.str.WriteString("\n")
555 } else {
556 // Input: a && b
557 // Output: a\n&& b
558 un.str.WriteString("\n")
559 un.str.WriteString(unmangled)
560 un.str.WriteString(" ")
561 }
562 return true
563 }
564 un.str.WriteString(" ")
565 un.str.WriteString(unmangled)
566 un.str.WriteString(" ")
567 return false
568 }
569
570 // Defined defaults for the unparser options
571 var (
572 defaultWrapOnColumn = 80
573 defaultWrapAfterColumnLimit = true
574 defaultOperatorsToWrapOn = map[string]bool{
575 operators.LogicalAnd: true,
576 operators.LogicalOr: true,
577 }
578 )
579
580 // UnparserOption is a functional option for configuring the output formatting
581 // of the Unparse function.
582 type UnparserOption func(*unparserOption) (*unparserOption, error)
583
584 // Internal representation of the UnparserOption type
585 type unparserOption struct {
586 wrapOnColumn int
587 operatorsToWrapOn map[string]bool
588 wrapAfterColumnLimit bool
589 }
590
591 // WrapOnColumn wraps the output expression when its string length exceeds a specified limit
592 // for operators set by WrapOnOperators function or by default, "&&" and "||" will be wrapped.
593 //
594 // Example usage:
595 //
596 // Unparse(expr, sourceInfo, WrapOnColumn(40), WrapOnOperators(Operators.LogicalAnd))
597 //
598 // This will insert a newline immediately after the logical AND operator for the below example input:
599 //
600 // Input:
601 // 'my-principal-group' in request.auth.claims && request.auth.claims.iat > now - duration('5m')
602 //
603 // Output:
604 // 'my-principal-group' in request.auth.claims &&
605 // request.auth.claims.iat > now - duration('5m')
606 func WrapOnColumn(col int) UnparserOption {
607 return func(opt *unparserOption) (*unparserOption, error) {
608 if col < 1 {
609 return nil, fmt.Errorf("Invalid unparser option. Wrap column value must be greater than or equal to 1. Got %v instead", col)
610 }
611 opt.wrapOnColumn = col
612 return opt, nil
613 }
614 }
615
616 // WrapOnOperators specifies which operators to perform word wrapping on an output expression when its string length
617 // exceeds the column limit set by WrapOnColumn function.
618 //
619 // Word wrapping is supported on non-unary symbolic operators. Refer to operators.go for the full list
620 //
621 // This will replace any previously supplied operators instead of merging them.
622 func WrapOnOperators(symbols ...string) UnparserOption {
623 return func(opt *unparserOption) (*unparserOption, error) {
624 opt.operatorsToWrapOn = make(map[string]bool)
625 for _, symbol := range symbols {
626 _, found := operators.FindReverse(symbol)
627 if !found {
628 return nil, fmt.Errorf("Invalid unparser option. Unsupported operator: %s", symbol)
629 }
630 arity := operators.Arity(symbol)
631 if arity < 2 {
632 return nil, fmt.Errorf("Invalid unparser option. Unary operators are unsupported: %s", symbol)
633 }
634
635 opt.operatorsToWrapOn[symbol] = true
636 }
637
638 return opt, nil
639 }
640 }
641
642 // WrapAfterColumnLimit dictates whether to insert a newline before or after the specified operator
643 // when word wrapping is performed.
644 //
645 // Example usage:
646 //
647 // Unparse(expr, sourceInfo, WrapOnColumn(40), WrapOnOperators(Operators.LogicalAnd), WrapAfterColumnLimit(false))
648 //
649 // This will insert a newline immediately before the logical AND operator for the below example input, ensuring
650 // that the length of a line never exceeds the specified column limit:
651 //
652 // Input:
653 // 'my-principal-group' in request.auth.claims && request.auth.claims.iat > now - duration('5m')
654 //
655 // Output:
656 // 'my-principal-group' in request.auth.claims
657 // && request.auth.claims.iat > now - duration('5m')
658 func WrapAfterColumnLimit(wrapAfter bool) UnparserOption {
659 return func(opt *unparserOption) (*unparserOption, error) {
660 opt.wrapAfterColumnLimit = wrapAfter
661 return opt, nil
662 }
663 }