Debian Codegraph @

interpreter/evalstate.go

raw symbols SCIP
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 interpreter
16
17 import (
18 "github.com/google/cel-go/common/types/ref"
19 )
20
21 // EvalState tracks the values associated with expression ids during execution.
22 type EvalState interface {
23 // IDs returns the list of ids with recorded values.
24 IDs() []int64
25
26 // Value returns the observed value of the given expression id if found, and a nil false
27 // result if not.
28 Value(int64) (ref.Val, bool)
29
30 // SetValue sets the observed value of the expression id.
31 SetValue(int64, ref.Val)
32
33 // Reset clears the previously recorded expression values.
34 Reset()
35 }
36
37 // evalState permits the mutation of evaluation state for a given expression id.
38 type evalState struct {
39 values map[int64]ref.Val
40 }
41
42 // NewEvalState returns an EvalState instanced used to observe the intermediate
43 // evaluations of an expression.
44 func NewEvalState() EvalState {
45 return &evalState{
46 values: make(map[int64]ref.Val),
47 }
48 }
49
50 // IDs implements the EvalState interface method.
51 func (s *evalState) IDs() []int64 {
52 var ids []int64
53 for k, v := range s.values {
54 if v != nil {
55 ids = append(ids, k)
56 }
57 }
58 return ids
59 }
60
61 // Value is an implementation of the EvalState interface method.
62 func (s *evalState) Value(exprID int64) (ref.Val, bool) {
63 val, found := s.values[exprID]
64 return val, found
65 }
66
67 // SetValue is an implementation of the EvalState interface method.
68 func (s *evalState) SetValue(exprID int64, val ref.Val) {
69 if val == nil {
70 delete(s.values, exprID)
71 } else {
72 s.values[exprID] = val
73 }
74 }
75
76 // Reset implements the EvalState interface method.
77 func (s *evalState) Reset() {
78 s.values = map[int64]ref.Val{}
79 }