Debian Codegraph @

parser/helper.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 parser
16
17 import (
18 "sync"
19
20 antlr "github.com/antlr4-go/antlr/v4"
21
22 "github.com/google/cel-go/common"
23 "github.com/google/cel-go/common/ast"
24 "github.com/google/cel-go/common/types"
25 "github.com/google/cel-go/common/types/ref"
26 )
27
28 type parserHelper struct {
29 exprFactory ast.ExprFactory
30 source common.Source
31 sourceInfo *ast.SourceInfo
32 nextID int64
33 }
34
35 func newParserHelper(source common.Source, fac ast.ExprFactory) *parserHelper {
36 return &parserHelper{
37 exprFactory: fac,
38 source: source,
39 sourceInfo: ast.NewSourceInfo(source),
40 nextID: 1,
41 }
42 }
43
44 func (p *parserHelper) getSourceInfo() *ast.SourceInfo {
45 return p.sourceInfo
46 }
47
48 func (p *parserHelper) newLiteral(ctx any, value ref.Val) ast.Expr {
49 return p.exprFactory.NewLiteral(p.newID(ctx), value)
50 }
51
52 func (p *parserHelper) newLiteralBool(ctx any, value bool) ast.Expr {
53 return p.newLiteral(ctx, types.Bool(value))
54 }
55
56 func (p *parserHelper) newLiteralString(ctx any, value string) ast.Expr {
57 return p.newLiteral(ctx, types.String(value))
58 }
59
60 func (p *parserHelper) newLiteralBytes(ctx any, value []byte) ast.Expr {
61 return p.newLiteral(ctx, types.Bytes(value))
62 }
63
64 func (p *parserHelper) newLiteralInt(ctx any, value int64) ast.Expr {
65 return p.newLiteral(ctx, types.Int(value))
66 }
67
68 func (p *parserHelper) newLiteralUint(ctx any, value uint64) ast.Expr {
69 return p.newLiteral(ctx, types.Uint(value))
70 }
71
72 func (p *parserHelper) newLiteralDouble(ctx any, value float64) ast.Expr {
73 return p.newLiteral(ctx, types.Double(value))
74 }
75
76 func (p *parserHelper) newIdent(ctx any, name string) ast.Expr {
77 return p.exprFactory.NewIdent(p.newID(ctx), name)
78 }
79
80 func (p *parserHelper) newSelect(ctx any, operand ast.Expr, field string) ast.Expr {
81 return p.exprFactory.NewSelect(p.newID(ctx), operand, field)
82 }
83
84 func (p *parserHelper) newPresenceTest(ctx any, operand ast.Expr, field string) ast.Expr {
85 return p.exprFactory.NewPresenceTest(p.newID(ctx), operand, field)
86 }
87
88 func (p *parserHelper) newGlobalCall(ctx any, function string, args ...ast.Expr) ast.Expr {
89 return p.exprFactory.NewCall(p.newID(ctx), function, args...)
90 }
91
92 func (p *parserHelper) newReceiverCall(ctx any, function string, target ast.Expr, args ...ast.Expr) ast.Expr {
93 return p.exprFactory.NewMemberCall(p.newID(ctx), function, target, args...)
94 }
95
96 func (p *parserHelper) newList(ctx any, elements []ast.Expr, optionals ...int32) ast.Expr {
97 return p.exprFactory.NewList(p.newID(ctx), elements, optionals)
98 }
99
100 func (p *parserHelper) newMap(ctx any, entries ...ast.EntryExpr) ast.Expr {
101 return p.exprFactory.NewMap(p.newID(ctx), entries)
102 }
103
104 func (p *parserHelper) newMapEntry(entryID int64, key ast.Expr, value ast.Expr, optional bool) ast.EntryExpr {
105 return p.exprFactory.NewMapEntry(entryID, key, value, optional)
106 }
107
108 func (p *parserHelper) newObject(ctx any, typeName string, fields ...ast.EntryExpr) ast.Expr {
109 return p.exprFactory.NewStruct(p.newID(ctx), typeName, fields)
110 }
111
112 func (p *parserHelper) newObjectField(fieldID int64, field string, value ast.Expr, optional bool) ast.EntryExpr {
113 return p.exprFactory.NewStructField(fieldID, field, value, optional)
114 }
115
116 func (p *parserHelper) newComprehension(ctx any,
117 iterRange ast.Expr,
118 iterVar,
119 accuVar string,
120 accuInit ast.Expr,
121 condition ast.Expr,
122 step ast.Expr,
123 result ast.Expr) ast.Expr {
124 return p.exprFactory.NewComprehension(
125 p.newID(ctx), iterRange, iterVar, accuVar, accuInit, condition, step, result)
126 }
127
128 func (p *parserHelper) newComprehensionTwoVar(ctx any,
129 iterRange ast.Expr,
130 iterVar, iterVar2,
131 accuVar string,
132 accuInit ast.Expr,
133 condition ast.Expr,
134 step ast.Expr,
135 result ast.Expr) ast.Expr {
136 return p.exprFactory.NewComprehensionTwoVar(
137 p.newID(ctx), iterRange, iterVar, iterVar2, accuVar, accuInit, condition, step, result)
138 }
139
140 func (p *parserHelper) newID(ctx any) int64 {
141 if id, isID := ctx.(int64); isID {
142 return id
143 }
144 return p.id(ctx)
145 }
146
147 func (p *parserHelper) newExpr(ctx any) ast.Expr {
148 return p.exprFactory.NewUnspecifiedExpr(p.newID(ctx))
149 }
150
151 func (p *parserHelper) id(ctx any) int64 {
152 var offset ast.OffsetRange
153 switch c := ctx.(type) {
154 case antlr.ParserRuleContext:
155 start := c.GetStart()
156 offset.Start = p.sourceInfo.ComputeOffset(int32(start.GetLine()), int32(start.GetColumn()))
157 offset.Stop = offset.Start + int32(len(c.GetText()))
158 case antlr.Token:
159 offset.Start = p.sourceInfo.ComputeOffset(int32(c.GetLine()), int32(c.GetColumn()))
160 offset.Stop = offset.Start + int32(len(c.GetText()))
161 case common.Location:
162 offset.Start = p.sourceInfo.ComputeOffsetAbsolute(int32(c.Line()), int32(c.Column()))
163 offset.Stop = offset.Start
164 case ast.OffsetRange:
165 offset = c
166 default:
167 // This should only happen if the ctx is nil
168 return -1
169 }
170 id := p.nextID
171 p.sourceInfo.SetOffsetRange(id, offset)
172 p.nextID++
173 return id
174 }
175
176 func (p *parserHelper) deleteID(id int64) {
177 p.sourceInfo.ClearOffsetRange(id)
178 if id == p.nextID-1 {
179 p.nextID--
180 }
181 }
182
183 func (p *parserHelper) getLocation(id int64) common.Location {
184 return p.sourceInfo.GetStartLocation(id)
185 }
186
187 func (p *parserHelper) getLocationByOffset(offset int32) common.Location {
188 return p.getSourceInfo().GetLocationByOffset(offset)
189 }
190
191 // buildMacroCallArg iterates the expression and returns a new expression
192 // where all macros have been replaced by their IDs in MacroCalls
193 func (p *parserHelper) buildMacroCallArg(expr ast.Expr) ast.Expr {
194 if _, found := p.sourceInfo.GetMacroCall(expr.ID()); found {
195 return p.exprFactory.NewUnspecifiedExpr(expr.ID())
196 }
197
198 switch expr.Kind() {
199 case ast.CallKind:
200 // Iterate the AST from `expr` recursively looking for macros. Because we are at most
201 // starting from the top level macro, this recursion is bounded by the size of the AST. This
202 // means that the depth check on the AST during parsing will catch recursion overflows
203 // before we get to here.
204 call := expr.AsCall()
205 macroArgs := make([]ast.Expr, len(call.Args()))
206 for index, arg := range call.Args() {
207 macroArgs[index] = p.buildMacroCallArg(arg)
208 }
209 if !call.IsMemberFunction() {
210 return p.exprFactory.NewCall(expr.ID(), call.FunctionName(), macroArgs...)
211 }
212 macroTarget := p.buildMacroCallArg(call.Target())
213 return p.exprFactory.NewMemberCall(expr.ID(), call.FunctionName(), macroTarget, macroArgs...)
214 case ast.ListKind:
215 list := expr.AsList()
216 macroListArgs := make([]ast.Expr, list.Size())
217 for i, elem := range list.Elements() {
218 macroListArgs[i] = p.buildMacroCallArg(elem)
219 }
220 return p.exprFactory.NewList(expr.ID(), macroListArgs, list.OptionalIndices())
221 }
222 return expr
223 }
224
225 // addMacroCall adds the macro the the MacroCalls map in source info. If a macro has args/subargs/target
226 // that are macros, their ID will be stored instead for later self-lookups.
227 func (p *parserHelper) addMacroCall(exprID int64, function string, target ast.Expr, args ...ast.Expr) {
228 macroArgs := make([]ast.Expr, len(args))
229 for index, arg := range args {
230 macroArgs[index] = p.buildMacroCallArg(arg)
231 }
232 if target == nil {
233 p.sourceInfo.SetMacroCall(exprID, p.exprFactory.NewCall(0, function, macroArgs...))
234 return
235 }
236 macroTarget := target
237 if _, found := p.sourceInfo.GetMacroCall(target.ID()); found {
238 macroTarget = p.exprFactory.NewUnspecifiedExpr(target.ID())
239 } else {
240 macroTarget = p.buildMacroCallArg(target)
241 }
242 p.sourceInfo.SetMacroCall(exprID, p.exprFactory.NewMemberCall(0, function, macroTarget, macroArgs...))
243 }
244
245 // logicManager compacts logical trees into a more efficient structure which is semantically
246 // equivalent with how the logic graph is constructed by the ANTLR parser.
247 //
248 // The purpose of the logicManager is to ensure a compact serialization format for the logical &&, ||
249 // operators which have a tendency to create long DAGs which are skewed in one direction. Since the
250 // operators are commutative re-ordering the terms *must not* affect the evaluation result.
251 //
252 // The logic manager will either render the terms to N-chained && / || operators as a single logical
253 // call with N-terms, or will rebalance the tree. Rebalancing the terms is a safe, if somewhat
254 // controversial choice as it alters the traditional order of execution assumptions present in most
255 // expressions.
256 type logicManager struct {
257 exprFactory ast.ExprFactory
258 function string
259 terms []ast.Expr
260 ops []int64
261 variadicASTs bool
262 }
263
264 // newVariadicLogicManager creates a logic manager instance bound to a specific function and its first term.
265 func newVariadicLogicManager(fac ast.ExprFactory, function string, term ast.Expr) *logicManager {
266 return &logicManager{
267 exprFactory: fac,
268 function: function,
269 terms: []ast.Expr{term},
270 ops: []int64{},
271 variadicASTs: true,
272 }
273 }
274
275 // newBalancingLogicManager creates a logic manager instance bound to a specific function and its first term.
276 func newBalancingLogicManager(fac ast.ExprFactory, function string, term ast.Expr) *logicManager {
277 return &logicManager{
278 exprFactory: fac,
279 function: function,
280 terms: []ast.Expr{term},
281 ops: []int64{},
282 variadicASTs: false,
283 }
284 }
285
286 // addTerm adds an operation identifier and term to the set of terms to be balanced.
287 func (l *logicManager) addTerm(op int64, term ast.Expr) {
288 l.terms = append(l.terms, term)
289 l.ops = append(l.ops, op)
290 }
291
292 // toExpr renders the logic graph into an Expr value, either balancing a tree of logical
293 // operations or creating a variadic representation of the logical operator.
294 func (l *logicManager) toExpr() ast.Expr {
295 if len(l.terms) == 1 {
296 return l.terms[0]
297 }
298 if l.variadicASTs {
299 return l.exprFactory.NewCall(l.ops[0], l.function, l.terms...)
300 }
301 return l.balancedTree(0, len(l.ops)-1)
302 }
303
304 // balancedTree recursively balances the terms provided to a commutative operator.
305 func (l *logicManager) balancedTree(lo, hi int) ast.Expr {
306 mid := (lo + hi + 1) / 2
307
308 var left ast.Expr
309 if mid == lo {
310 left = l.terms[mid]
311 } else {
312 left = l.balancedTree(lo, mid-1)
313 }
314
315 var right ast.Expr
316 if mid == hi {
317 right = l.terms[mid+1]
318 } else {
319 right = l.balancedTree(mid+1, hi)
320 }
321 return l.exprFactory.NewCall(l.ops[mid], l.function, left, right)
322 }
323
324 type exprHelper struct {
325 *parserHelper
326 id int64
327 }
328
329 func (e *exprHelper) nextMacroID() int64 {
330 return e.parserHelper.id(e.parserHelper.getLocation(e.id))
331 }
332
333 // Copy implements the ExprHelper interface method by producing a copy of the input Expr value
334 // with a fresh set of numeric identifiers the Expr and all its descendants.
335 func (e *exprHelper) Copy(expr ast.Expr) ast.Expr {
336 offsetRange, _ := e.parserHelper.sourceInfo.GetOffsetRange(expr.ID())
337 copyID := e.parserHelper.newID(offsetRange)
338 switch expr.Kind() {
339 case ast.LiteralKind:
340 return e.exprFactory.NewLiteral(copyID, expr.AsLiteral())
341 case ast.IdentKind:
342 return e.exprFactory.NewIdent(copyID, expr.AsIdent())
343 case ast.SelectKind:
344 sel := expr.AsSelect()
345 op := e.Copy(sel.Operand())
346 if sel.IsTestOnly() {
347 return e.exprFactory.NewPresenceTest(copyID, op, sel.FieldName())
348 }
349 return e.exprFactory.NewSelect(copyID, op, sel.FieldName())
350 case ast.CallKind:
351 call := expr.AsCall()
352 args := call.Args()
353 argsCopy := make([]ast.Expr, len(args))
354 for i, arg := range args {
355 argsCopy[i] = e.Copy(arg)
356 }
357 if !call.IsMemberFunction() {
358 return e.exprFactory.NewCall(copyID, call.FunctionName(), argsCopy...)
359 }
360 return e.exprFactory.NewMemberCall(copyID, call.FunctionName(), e.Copy(call.Target()), argsCopy...)
361 case ast.ListKind:
362 list := expr.AsList()
363 elems := list.Elements()
364 elemsCopy := make([]ast.Expr, len(elems))
365 for i, elem := range elems {
366 elemsCopy[i] = e.Copy(elem)
367 }
368 return e.exprFactory.NewList(copyID, elemsCopy, list.OptionalIndices())
369 case ast.MapKind:
370 m := expr.AsMap()
371 entries := m.Entries()
372 entriesCopy := make([]ast.EntryExpr, len(entries))
373 for i, en := range entries {
374 entry := en.AsMapEntry()
375 entryID := e.nextMacroID()
376 entriesCopy[i] = e.exprFactory.NewMapEntry(entryID,
377 e.Copy(entry.Key()), e.Copy(entry.Value()), entry.IsOptional())
378 }
379 return e.exprFactory.NewMap(copyID, entriesCopy)
380 case ast.StructKind:
381 s := expr.AsStruct()
382 fields := s.Fields()
383 fieldsCopy := make([]ast.EntryExpr, len(fields))
384 for i, f := range fields {
385 field := f.AsStructField()
386 fieldID := e.nextMacroID()
387 fieldsCopy[i] = e.exprFactory.NewStructField(fieldID,
388 field.Name(), e.Copy(field.Value()), field.IsOptional())
389 }
390 return e.exprFactory.NewStruct(copyID, s.TypeName(), fieldsCopy)
391 case ast.ComprehensionKind:
392 compre := expr.AsComprehension()
393 iterRange := e.Copy(compre.IterRange())
394 accuInit := e.Copy(compre.AccuInit())
395 cond := e.Copy(compre.LoopCondition())
396 step := e.Copy(compre.LoopStep())
397 result := e.Copy(compre.Result())
398 // All comprehensions can be represented by the two-variable comprehension since the
399 // differentiation between one and two-variable is whether the iterVar2 value is non-empty.
400 return e.exprFactory.NewComprehensionTwoVar(copyID,
401 iterRange, compre.IterVar(), compre.IterVar2(), compre.AccuVar(), accuInit, cond, step, result)
402 }
403 return e.exprFactory.NewUnspecifiedExpr(copyID)
404 }
405
406 // NewLiteral implements the ExprHelper interface method.
407 func (e *exprHelper) NewLiteral(value ref.Val) ast.Expr {
408 return e.exprFactory.NewLiteral(e.nextMacroID(), value)
409 }
410
411 // NewList implements the ExprHelper interface method.
412 func (e *exprHelper) NewList(elems ...ast.Expr) ast.Expr {
413 return e.exprFactory.NewList(e.nextMacroID(), elems, []int32{})
414 }
415
416 // NewMap implements the ExprHelper interface method.
417 func (e *exprHelper) NewMap(entries ...ast.EntryExpr) ast.Expr {
418 return e.exprFactory.NewMap(e.nextMacroID(), entries)
419 }
420
421 // NewMapEntry implements the ExprHelper interface method.
422 func (e *exprHelper) NewMapEntry(key ast.Expr, val ast.Expr, optional bool) ast.EntryExpr {
423 return e.exprFactory.NewMapEntry(e.nextMacroID(), key, val, optional)
424 }
425
426 // NewStruct implements the ExprHelper interface method.
427 func (e *exprHelper) NewStruct(typeName string, fieldInits ...ast.EntryExpr) ast.Expr {
428 return e.exprFactory.NewStruct(e.nextMacroID(), typeName, fieldInits)
429 }
430
431 // NewStructField implements the ExprHelper interface method.
432 func (e *exprHelper) NewStructField(field string, init ast.Expr, optional bool) ast.EntryExpr {
433 return e.exprFactory.NewStructField(e.nextMacroID(), field, init, optional)
434 }
435
436 // NewComprehension implements the ExprHelper interface method.
437 func (e *exprHelper) NewComprehension(
438 iterRange ast.Expr,
439 iterVar string,
440 accuVar string,
441 accuInit ast.Expr,
442 condition ast.Expr,
443 step ast.Expr,
444 result ast.Expr) ast.Expr {
445 return e.exprFactory.NewComprehension(
446 e.nextMacroID(), iterRange, iterVar, accuVar, accuInit, condition, step, result)
447 }
448
449 // NewComprehensionTwoVar implements the ExprHelper interface method.
450 func (e *exprHelper) NewComprehensionTwoVar(
451 iterRange ast.Expr,
452 iterVar,
453 iterVar2,
454 accuVar string,
455 accuInit,
456 condition,
457 step,
458 result ast.Expr) ast.Expr {
459 return e.exprFactory.NewComprehensionTwoVar(
460 e.nextMacroID(), iterRange, iterVar, iterVar2, accuVar, accuInit, condition, step, result)
461 }
462
463 // NewIdent implements the ExprHelper interface method.
464 func (e *exprHelper) NewIdent(name string) ast.Expr {
465 return e.exprFactory.NewIdent(e.nextMacroID(), name)
466 }
467
468 // NewAccuIdent implements the ExprHelper interface method.
469 func (e *exprHelper) NewAccuIdent() ast.Expr {
470 return e.exprFactory.NewAccuIdent(e.nextMacroID())
471 }
472
473 // AccuIdentName implements the ExprHelper interface method.
474 func (e *exprHelper) AccuIdentName() string {
475 return e.exprFactory.AccuIdentName()
476 }
477
478 // NewGlobalCall implements the ExprHelper interface method.
479 func (e *exprHelper) NewCall(function string, args ...ast.Expr) ast.Expr {
480 return e.exprFactory.NewCall(e.nextMacroID(), function, args...)
481 }
482
483 // NewMemberCall implements the ExprHelper interface method.
484 func (e *exprHelper) NewMemberCall(function string, target ast.Expr, args ...ast.Expr) ast.Expr {
485 return e.exprFactory.NewMemberCall(e.nextMacroID(), function, target, args...)
486 }
487
488 // NewPresenceTest implements the ExprHelper interface method.
489 func (e *exprHelper) NewPresenceTest(operand ast.Expr, field string) ast.Expr {
490 return e.exprFactory.NewPresenceTest(e.nextMacroID(), operand, field)
491 }
492
493 // NewSelect implements the ExprHelper interface method.
494 func (e *exprHelper) NewSelect(operand ast.Expr, field string) ast.Expr {
495 return e.exprFactory.NewSelect(e.nextMacroID(), operand, field)
496 }
497
498 // OffsetLocation implements the ExprHelper interface method.
499 func (e *exprHelper) OffsetLocation(exprID int64) common.Location {
500 return e.parserHelper.sourceInfo.GetStartLocation(exprID)
501 }
502
503 // NewError associates an error message with a given expression id, populating the source offset location of the error if possible.
504 func (e *exprHelper) NewError(exprID int64, message string) *common.Error {
505 return common.NewError(exprID, message, e.OffsetLocation(exprID))
506 }
507
508 var (
509 // Thread-safe pool of ExprHelper values to minimize alloc overhead of ExprHelper creations.
510 exprHelperPool = &sync.Pool{
511 New: func() any {
512 return &exprHelper{}
513 },
514 }
515 )