Debian Codegraph @

common/ast/ast.go

raw symbols SCIP
1 // Copyright 2023 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 ast declares data structures useful for parsed and checked abstract syntax trees
16 package ast
17
18 import (
19 "slices"
20
21 "github.com/google/cel-go/common"
22 "github.com/google/cel-go/common/types"
23 "github.com/google/cel-go/common/types/ref"
24 )
25
26 // AST contains a protobuf expression and source info along with CEL-native type and reference information.
27 type AST struct {
28 expr Expr
29 sourceInfo *SourceInfo
30 typeMap map[int64]*types.Type
31 refMap map[int64]*ReferenceInfo
32 }
33
34 // Expr returns the root ast.Expr value in the AST.
35 func (a *AST) Expr() Expr {
36 if a == nil {
37 return nilExpr
38 }
39 return a.expr
40 }
41
42 // SourceInfo returns the source metadata associated with the parse / type-check passes.
43 func (a *AST) SourceInfo() *SourceInfo {
44 if a == nil {
45 return nil
46 }
47 return a.sourceInfo
48 }
49
50 // GetType returns the type for the expression at the given id, if one exists, else types.DynType.
51 func (a *AST) GetType(id int64) *types.Type {
52 if t, found := a.TypeMap()[id]; found {
53 return t
54 }
55 return types.DynType
56 }
57
58 // SetType sets the type of the expression node at the given id.
59 func (a *AST) SetType(id int64, t *types.Type) {
60 if a == nil {
61 return
62 }
63 a.typeMap[id] = t
64 }
65
66 // TypeMap returns the map of expression ids to type-checked types.
67 //
68 // If the AST is not type-checked, the map will be empty.
69 func (a *AST) TypeMap() map[int64]*types.Type {
70 if a == nil {
71 return map[int64]*types.Type{}
72 }
73 return a.typeMap
74 }
75
76 // GetOverloadIDs returns the set of overload function names for a given expression id.
77 //
78 // If the expression id is not a function call, or the AST is not type-checked, the result will be empty.
79 func (a *AST) GetOverloadIDs(id int64) []string {
80 if ref, found := a.ReferenceMap()[id]; found {
81 return ref.OverloadIDs
82 }
83 return []string{}
84 }
85
86 // ReferenceMap returns the map of expression id to identifier, constant, and function references.
87 func (a *AST) ReferenceMap() map[int64]*ReferenceInfo {
88 if a == nil {
89 return map[int64]*ReferenceInfo{}
90 }
91 return a.refMap
92 }
93
94 // SetReference adds a reference to the checked AST type map.
95 func (a *AST) SetReference(id int64, r *ReferenceInfo) {
96 if a == nil {
97 return
98 }
99 a.refMap[id] = r
100 }
101
102 // IsChecked returns whether the AST is type-checked.
103 func (a *AST) IsChecked() bool {
104 return a != nil && len(a.TypeMap()) > 0
105 }
106
107 // NewAST creates a base AST instance with an ast.Expr and ast.SourceInfo value.
108 func NewAST(e Expr, sourceInfo *SourceInfo) *AST {
109 if e == nil {
110 e = nilExpr
111 }
112 return &AST{
113 expr: e,
114 sourceInfo: sourceInfo,
115 typeMap: make(map[int64]*types.Type),
116 refMap: make(map[int64]*ReferenceInfo),
117 }
118 }
119
120 // NewCheckedAST wraps an parsed AST and augments it with type and reference metadata.
121 func NewCheckedAST(parsed *AST, typeMap map[int64]*types.Type, refMap map[int64]*ReferenceInfo) *AST {
122 return &AST{
123 expr: parsed.Expr(),
124 sourceInfo: parsed.SourceInfo(),
125 typeMap: typeMap,
126 refMap: refMap,
127 }
128 }
129
130 // Copy creates a deep copy of the Expr and SourceInfo values in the input AST.
131 //
132 // Copies of the Expr value are generated using an internal default ExprFactory.
133 func Copy(a *AST) *AST {
134 if a == nil {
135 return nil
136 }
137 e := defaultFactory.CopyExpr(a.expr)
138 if !a.IsChecked() {
139 return NewAST(e, CopySourceInfo(a.SourceInfo()))
140 }
141 typesCopy := make(map[int64]*types.Type, len(a.typeMap))
142 for id, t := range a.typeMap {
143 typesCopy[id] = t
144 }
145 refsCopy := make(map[int64]*ReferenceInfo, len(a.refMap))
146 for id, r := range a.refMap {
147 refsCopy[id] = r
148 }
149 return NewCheckedAST(NewAST(e, CopySourceInfo(a.SourceInfo())), typesCopy, refsCopy)
150 }
151
152 // MaxID returns the upper-bound, non-inclusive, of ids present within the AST's Expr value.
153 func MaxID(a *AST) int64 {
154 visitor := &maxIDVisitor{maxID: 1}
155 PostOrderVisit(a.Expr(), visitor)
156 for id, call := range a.SourceInfo().MacroCalls() {
157 PostOrderVisit(call, visitor)
158 if id > visitor.maxID {
159 visitor.maxID = id + 1
160 }
161 }
162 return visitor.maxID + 1
163 }
164
165 // IDs returns the set of AST node IDs, including macro calls.
166 func (a *AST) IDs() map[int64]bool {
167 visitor := make(idVisitor)
168 PostOrderVisit(a.Expr(), visitor)
169 for _, call := range a.SourceInfo().MacroCalls() {
170 PostOrderVisit(call, visitor)
171 }
172 return visitor
173 }
174
175 // ClearUnusedIDs removes IDs not used in the AST or macro calls from SourceInfo.
176 func (a *AST) ClearUnusedIDs() {
177 ids := a.IDs()
178 for id := range a.SourceInfo().OffsetRanges() {
179 if !ids[id] {
180 a.SourceInfo().ClearOffsetRange(id)
181 }
182 }
183 }
184
185 // Heights computes the heights of all AST expressions and returns a map from expression id to height.
186 func Heights(a *AST) map[int64]int {
187 visitor := make(heightVisitor)
188 PostOrderVisit(a.Expr(), visitor)
189 return visitor
190 }
191
192 // NewSourceInfo creates a simple SourceInfo object from an input common.Source value.
193 func NewSourceInfo(src common.Source) *SourceInfo {
194 var lineOffsets []int32
195 var desc string
196 baseLine := int32(0)
197 baseCol := int32(0)
198 if src != nil {
199 desc = src.Description()
200 lineOffsets = src.LineOffsets()
201 // Determine whether the source metadata should be computed relative
202 // to a base line and column value. This can be determined by requesting
203 // the location for offset 0 from the source object.
204 if loc, found := src.OffsetLocation(0); found {
205 baseLine = int32(loc.Line()) - 1
206 baseCol = int32(loc.Column())
207 }
208 }
209 return &SourceInfo{
210 desc: desc,
211 lines: lineOffsets,
212 baseLine: baseLine,
213 baseCol: baseCol,
214 offsetRanges: make(map[int64]OffsetRange),
215 macroCalls: make(map[int64]Expr),
216 }
217 }
218
219 // CopySourceInfo creates a deep copy of the MacroCalls within the input SourceInfo.
220 //
221 // Copies of macro Expr values are generated using an internal default ExprFactory.
222 func CopySourceInfo(info *SourceInfo) *SourceInfo {
223 if info == nil {
224 return nil
225 }
226 rangesCopy := make(map[int64]OffsetRange, len(info.offsetRanges))
227 for id, off := range info.offsetRanges {
228 rangesCopy[id] = off
229 }
230 callsCopy := make(map[int64]Expr, len(info.macroCalls))
231 for id, call := range info.macroCalls {
232 callsCopy[id] = defaultFactory.CopyExpr(call)
233 }
234 return &SourceInfo{
235 syntax: info.syntax,
236 desc: info.desc,
237 lines: info.lines,
238 baseLine: info.baseLine,
239 baseCol: info.baseCol,
240 offsetRanges: rangesCopy,
241 macroCalls: callsCopy,
242 }
243 }
244
245 // SourceInfo records basic information about the expression as a textual input and
246 // as a parsed expression value.
247 type SourceInfo struct {
248 syntax string
249 desc string
250 lines []int32
251 baseLine int32
252 baseCol int32
253 offsetRanges map[int64]OffsetRange
254 macroCalls map[int64]Expr
255 }
256
257 // RenumberIDs performs an in-place update of the expression IDs within the SourceInfo.
258 func (s *SourceInfo) RenumberIDs(idGen IDGenerator) {
259 if s == nil {
260 return
261 }
262 oldIDs := []int64{}
263 for id := range s.offsetRanges {
264 oldIDs = append(oldIDs, id)
265 }
266 slices.Sort(oldIDs)
267 newRanges := make(map[int64]OffsetRange)
268 for _, id := range oldIDs {
269 newRanges[idGen(id)] = s.offsetRanges[id]
270 }
271 s.offsetRanges = newRanges
272 }
273
274 // SyntaxVersion returns the syntax version associated with the text expression.
275 func (s *SourceInfo) SyntaxVersion() string {
276 if s == nil {
277 return ""
278 }
279 return s.syntax
280 }
281
282 // Description provides information about where the expression came from.
283 func (s *SourceInfo) Description() string {
284 if s == nil {
285 return ""
286 }
287 return s.desc
288 }
289
290 // LineOffsets returns a list of the 0-based character offsets in the input text where newlines appear.
291 func (s *SourceInfo) LineOffsets() []int32 {
292 if s == nil {
293 return []int32{}
294 }
295 return s.lines
296 }
297
298 // MacroCalls returns a map of expression id to ast.Expr value where the id represents the expression
299 // node where the macro was inserted into the AST, and the ast.Expr value represents the original call
300 // signature which was replaced.
301 func (s *SourceInfo) MacroCalls() map[int64]Expr {
302 if s == nil {
303 return map[int64]Expr{}
304 }
305 return s.macroCalls
306 }
307
308 // GetMacroCall returns the original ast.Expr value for the given expression if it was generated via
309 // a macro replacement.
310 //
311 // Note, parsing options must be enabled to track macro calls before this method will return a value.
312 func (s *SourceInfo) GetMacroCall(id int64) (Expr, bool) {
313 e, found := s.MacroCalls()[id]
314 return e, found
315 }
316
317 // SetMacroCall records a macro call at a specific location.
318 func (s *SourceInfo) SetMacroCall(id int64, e Expr) {
319 if s != nil {
320 s.macroCalls[id] = e
321 }
322 }
323
324 // ClearMacroCall removes the macro call at the given expression id.
325 func (s *SourceInfo) ClearMacroCall(id int64) {
326 if s != nil {
327 delete(s.macroCalls, id)
328 }
329 }
330
331 // OffsetRanges returns a map of expression id to OffsetRange values where the range indicates either:
332 // the start and end position in the input stream where the expression occurs, or the start position
333 // only. If the range only captures start position, the stop position of the range will be equal to
334 // the start.
335 func (s *SourceInfo) OffsetRanges() map[int64]OffsetRange {
336 if s == nil {
337 return map[int64]OffsetRange{}
338 }
339 return s.offsetRanges
340 }
341
342 // GetOffsetRange retrieves an OffsetRange for the given expression id if one exists.
343 func (s *SourceInfo) GetOffsetRange(id int64) (OffsetRange, bool) {
344 if s == nil {
345 return OffsetRange{}, false
346 }
347 o, found := s.offsetRanges[id]
348 return o, found
349 }
350
351 // SetOffsetRange sets the OffsetRange for the given expression id.
352 func (s *SourceInfo) SetOffsetRange(id int64, o OffsetRange) {
353 if s == nil {
354 return
355 }
356 s.offsetRanges[id] = o
357 }
358
359 // ClearOffsetRange removes the OffsetRange for the given expression id.
360 func (s *SourceInfo) ClearOffsetRange(id int64) {
361 if s != nil {
362 delete(s.offsetRanges, id)
363 }
364 }
365
366 // GetStartLocation calculates the human-readable 1-based line and 0-based column of the first character
367 // of the expression node at the id.
368 func (s *SourceInfo) GetStartLocation(id int64) common.Location {
369 if o, found := s.GetOffsetRange(id); found {
370 return s.GetLocationByOffset(o.Start)
371 }
372 return common.NoLocation
373 }
374
375 // GetStopLocation calculates the human-readable 1-based line and 0-based column of the last character for
376 // the expression node at the given id.
377 //
378 // If the SourceInfo was generated from a serialized protobuf representation, the stop location will
379 // be identical to the start location for the expression.
380 func (s *SourceInfo) GetStopLocation(id int64) common.Location {
381 if o, found := s.GetOffsetRange(id); found {
382 return s.GetLocationByOffset(o.Stop)
383 }
384 return common.NoLocation
385 }
386
387 // GetLocationByOffset returns the line and column information for a given character offset.
388 func (s *SourceInfo) GetLocationByOffset(offset int32) common.Location {
389 line := 1
390 col := int(offset)
391 for _, lineOffset := range s.LineOffsets() {
392 if lineOffset > offset {
393 break
394 }
395 line++
396 col = int(offset - lineOffset)
397 }
398 return common.NewLocation(line, col)
399 }
400
401 // ComputeOffset calculates the 0-based character offset from a 1-based line and 0-based column.
402 func (s *SourceInfo) ComputeOffset(line, col int32) int32 {
403 if s != nil {
404 line = s.baseLine + line
405 col = s.baseCol + col
406 }
407 return s.ComputeOffsetAbsolute(line, col)
408 }
409
410 // ComputeOffsetAbsolute calculates the 0-based character offset from a 1-based line and 0-based column
411 // based on the absolute line and column of the SourceInfo.
412 func (s *SourceInfo) ComputeOffsetAbsolute(line, col int32) int32 {
413 if line == 1 {
414 return col
415 }
416 if line < 1 || line > int32(len(s.LineOffsets())) {
417 return -1
418 }
419 offset := s.LineOffsets()[line-2]
420 return offset + col
421 }
422
423 // OffsetRange captures the start and stop positions of a section of text in the input expression.
424 type OffsetRange struct {
425 Start int32
426 Stop int32
427 }
428
429 // ReferenceInfo contains a CEL native representation of an identifier reference which may refer to
430 // either a qualified identifier name, a set of overload ids, or a constant value from an enum.
431 type ReferenceInfo struct {
432 Name string
433 OverloadIDs []string
434 Value ref.Val
435 }
436
437 // NewIdentReference creates a ReferenceInfo instance for an identifier with an optional constant value.
438 func NewIdentReference(name string, value ref.Val) *ReferenceInfo {
439 return &ReferenceInfo{Name: name, Value: value}
440 }
441
442 // NewFunctionReference creates a ReferenceInfo instance for a set of function overloads.
443 func NewFunctionReference(overloads ...string) *ReferenceInfo {
444 info := &ReferenceInfo{}
445 for _, id := range overloads {
446 info.AddOverload(id)
447 }
448 return info
449 }
450
451 // AddOverload appends a function overload ID to the ReferenceInfo.
452 func (r *ReferenceInfo) AddOverload(overloadID string) {
453 for _, id := range r.OverloadIDs {
454 if id == overloadID {
455 return
456 }
457 }
458 r.OverloadIDs = append(r.OverloadIDs, overloadID)
459 }
460
461 // Equals returns whether two references are identical to each other.
462 func (r *ReferenceInfo) Equals(other *ReferenceInfo) bool {
463 if r.Name != other.Name {
464 return false
465 }
466 if len(r.OverloadIDs) != len(other.OverloadIDs) {
467 return false
468 }
469 if len(r.OverloadIDs) != 0 {
470 overloadMap := make(map[string]struct{}, len(r.OverloadIDs))
471 for _, id := range r.OverloadIDs {
472 overloadMap[id] = struct{}{}
473 }
474 for _, id := range other.OverloadIDs {
475 _, found := overloadMap[id]
476 if !found {
477 return false
478 }
479 }
480 }
481 if r.Value == nil && other.Value == nil {
482 return true
483 }
484 if r.Value == nil && other.Value != nil ||
485 r.Value != nil && other.Value == nil ||
486 r.Value.Equal(other.Value) != types.True {
487 return false
488 }
489 return true
490 }
491
492 type maxIDVisitor struct {
493 maxID int64
494 *baseVisitor
495 }
496
497 // VisitExpr updates the max identifier if the incoming expression id is greater than previously observed.
498 func (v *maxIDVisitor) VisitExpr(e Expr) {
499 if v.maxID < e.ID() {
500 v.maxID = e.ID()
501 }
502 }
503
504 // VisitEntryExpr updates the max identifier if the incoming entry id is greater than previously observed.
505 func (v *maxIDVisitor) VisitEntryExpr(e EntryExpr) {
506 if v.maxID < e.ID() {
507 v.maxID = e.ID()
508 }
509 }
510
511 type heightVisitor map[int64]int
512
513 // VisitExpr computes the height of a given node as the max height of its children plus one.
514 //
515 // Identifiers and literals are treated as having a height of zero.
516 func (hv heightVisitor) VisitExpr(e Expr) {
517 // default includes IdentKind, LiteralKind
518 hv[e.ID()] = 0
519 switch e.Kind() {
520 case SelectKind:
521 hv[e.ID()] = 1 + hv[e.AsSelect().Operand().ID()]
522 case CallKind:
523 c := e.AsCall()
524 height := hv.maxHeight(c.Args()...)
525 if c.IsMemberFunction() {
526 tHeight := hv[c.Target().ID()]
527 if tHeight > height {
528 height = tHeight
529 }
530 }
531 hv[e.ID()] = 1 + height
532 case ListKind:
533 l := e.AsList()
534 hv[e.ID()] = 1 + hv.maxHeight(l.Elements()...)
535 case MapKind:
536 m := e.AsMap()
537 hv[e.ID()] = 1 + hv.maxEntryHeight(m.Entries()...)
538 case StructKind:
539 s := e.AsStruct()
540 hv[e.ID()] = 1 + hv.maxEntryHeight(s.Fields()...)
541 case ComprehensionKind:
542 comp := e.AsComprehension()
543 hv[e.ID()] = 1 + hv.maxHeight(comp.IterRange(), comp.AccuInit(), comp.LoopCondition(), comp.LoopStep(), comp.Result())
544 }
545 }
546
547 // VisitEntryExpr computes the max height of a map or struct entry and associates the height with the entry id.
548 func (hv heightVisitor) VisitEntryExpr(e EntryExpr) {
549 hv[e.ID()] = 0
550 switch e.Kind() {
551 case MapEntryKind:
552 me := e.AsMapEntry()
553 hv[e.ID()] = hv.maxHeight(me.Value(), me.Key())
554 case StructFieldKind:
555 sf := e.AsStructField()
556 hv[e.ID()] = hv[sf.Value().ID()]
557 }
558 }
559
560 func (hv heightVisitor) maxHeight(exprs ...Expr) int {
561 max := 0
562 for _, e := range exprs {
563 h := hv[e.ID()]
564 if h > max {
565 max = h
566 }
567 }
568 return max
569 }
570
571 func (hv heightVisitor) maxEntryHeight(entries ...EntryExpr) int {
572 max := 0
573 for _, e := range entries {
574 h := hv[e.ID()]
575 if h > max {
576 max = h
577 }
578 }
579 return max
580 }
581
582 type idVisitor map[int64]bool
583
584 func (v idVisitor) VisitExpr(e Expr) {
585 v[e.ID()] = true
586 }
587
588 func (v idVisitor) VisitEntryExpr(e EntryExpr) {
589 v[e.ID()] = true
590 }