| 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 checker |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "strings" |
| 20 | |
| 21 | "github.com/google/cel-go/common/containers" |
| 22 | "github.com/google/cel-go/common/decls" |
| 23 | "github.com/google/cel-go/common/overloads" |
| 24 | "github.com/google/cel-go/common/types" |
| 25 | "github.com/google/cel-go/parser" |
| 26 | ) |
| 27 | |
| 28 | type aggregateLiteralElementType int |
| 29 | |
| 30 | const ( |
| 31 | dynElementType aggregateLiteralElementType = iota |
| 32 | homogenousElementType aggregateLiteralElementType = 1 << iota |
| 33 | ) |
| 34 | |
| 35 | var ( |
| 36 | crossTypeNumericComparisonOverloads = map[string]struct{}{ |
| 37 | // double <-> int | uint |
| 38 | overloads.LessDoubleInt64: {}, |
| 39 | overloads.LessDoubleUint64: {}, |
| 40 | overloads.LessEqualsDoubleInt64: {}, |
| 41 | overloads.LessEqualsDoubleUint64: {}, |
| 42 | overloads.GreaterDoubleInt64: {}, |
| 43 | overloads.GreaterDoubleUint64: {}, |
| 44 | overloads.GreaterEqualsDoubleInt64: {}, |
| 45 | overloads.GreaterEqualsDoubleUint64: {}, |
| 46 | // int <-> double | uint |
| 47 | overloads.LessInt64Double: {}, |
| 48 | overloads.LessInt64Uint64: {}, |
| 49 | overloads.LessEqualsInt64Double: {}, |
| 50 | overloads.LessEqualsInt64Uint64: {}, |
| 51 | overloads.GreaterInt64Double: {}, |
| 52 | overloads.GreaterInt64Uint64: {}, |
| 53 | overloads.GreaterEqualsInt64Double: {}, |
| 54 | overloads.GreaterEqualsInt64Uint64: {}, |
| 55 | // uint <-> double | int |
| 56 | overloads.LessUint64Double: {}, |
| 57 | overloads.LessUint64Int64: {}, |
| 58 | overloads.LessEqualsUint64Double: {}, |
| 59 | overloads.LessEqualsUint64Int64: {}, |
| 60 | overloads.GreaterUint64Double: {}, |
| 61 | overloads.GreaterUint64Int64: {}, |
| 62 | overloads.GreaterEqualsUint64Double: {}, |
| 63 | overloads.GreaterEqualsUint64Int64: {}, |
| 64 | } |
| 65 | ) |
| 66 | |
| 67 | // Env is the environment for type checking. |
| 68 | // |
| 69 | // The Env is comprised of a container, type provider, declarations, and other related objects |
| 70 | // which can be used to assist with type-checking. |
| 71 | type Env struct { |
| 72 | container *containers.Container |
| 73 | provider types.Provider |
| 74 | declarations *Scopes |
| 75 | aggLitElemType aggregateLiteralElementType |
| 76 | filteredOverloadIDs map[string]struct{} |
| 77 | } |
| 78 | |
| 79 | // NewEnv returns a new *Env with the given parameters. |
| 80 | func NewEnv(container *containers.Container, provider types.Provider, opts ...Option) (*Env, error) { |
| 81 | declarations := newScopes() |
| 82 | declarations.Push() |
| 83 | |
| 84 | envOptions := &options{} |
| 85 | for _, opt := range opts { |
| 86 | if err := opt(envOptions); err != nil { |
| 87 | return nil, err |
| 88 | } |
| 89 | } |
| 90 | aggLitElemType := dynElementType |
| 91 | if envOptions.homogeneousAggregateLiterals { |
| 92 | aggLitElemType = homogenousElementType |
| 93 | } |
| 94 | filteredOverloadIDs := crossTypeNumericComparisonOverloads |
| 95 | if envOptions.crossTypeNumericComparisons { |
| 96 | filteredOverloadIDs = make(map[string]struct{}) |
| 97 | } |
| 98 | if envOptions.validatedDeclarations != nil { |
| 99 | declarations = envOptions.validatedDeclarations.Copy() |
| 100 | } |
| 101 | return &Env{ |
| 102 | container: container, |
| 103 | provider: provider, |
| 104 | declarations: declarations, |
| 105 | aggLitElemType: aggLitElemType, |
| 106 | filteredOverloadIDs: filteredOverloadIDs, |
| 107 | }, nil |
| 108 | } |
| 109 | |
| 110 | // AddIdents configures the checker with a list of variable declarations. |
| 111 | // |
| 112 | // If there are overlapping declarations, the method will error. |
| 113 | func (e *Env) AddIdents(declarations ...*decls.VariableDecl) error { |
| 114 | errMsgs := make([]errorMsg, 0) |
| 115 | for _, d := range declarations { |
| 116 | errMsgs = append(errMsgs, e.addIdent(d)) |
| 117 | } |
| 118 | return formatError(errMsgs) |
| 119 | } |
| 120 | |
| 121 | // AddFunctions configures the checker with a list of function declarations. |
| 122 | // |
| 123 | // If there are overlapping declarations, the method will error. |
| 124 | func (e *Env) AddFunctions(declarations ...*decls.FunctionDecl) error { |
| 125 | errMsgs := make([]errorMsg, 0) |
| 126 | for _, d := range declarations { |
| 127 | errMsgs = append(errMsgs, e.setFunction(d)...) |
| 128 | } |
| 129 | return formatError(errMsgs) |
| 130 | } |
| 131 | |
| 132 | // newAttrResolution creates a new attribute resolution value. |
| 133 | func newAttrResolution(ident *decls.VariableDecl, requiresDisambiguation bool) *attributeResolution { |
| 134 | return &attributeResolution{ |
| 135 | VariableDecl: ident, |
| 136 | requiresDisambiguation: requiresDisambiguation, |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | // attributeResolution wraps an existing variable and denotes whether disambiguation is needed |
| 141 | // during variable resolution. |
| 142 | type attributeResolution struct { |
| 143 | *decls.VariableDecl |
| 144 | |
| 145 | // requiresDisambiguation indicates the variable name should be dot-prefixed. |
| 146 | requiresDisambiguation bool |
| 147 | } |
| 148 | |
| 149 | // resolveSimpleIdent determines the resolved attribute for a single identifier. |
| 150 | func (e *Env) resolveSimpleIdent(name string) *attributeResolution { |
| 151 | local := e.lookupLocalIdent(name) |
| 152 | if local != nil && !strings.HasPrefix(name, ".") { |
| 153 | return newAttrResolution(local, false) |
| 154 | } |
| 155 | for _, candidate := range e.container.ResolveCandidateNames(name) { |
| 156 | if ident := e.lookupGlobalIdent(candidate); ident != nil { |
| 157 | return newAttrResolution(ident, local != nil) |
| 158 | } |
| 159 | } |
| 160 | return nil |
| 161 | } |
| 162 | |
| 163 | // resolveQualifiedIdent determines the resolved attribute for a qualified identifier. |
| 164 | func (e *Env) resolveQualifiedIdent(qualifiers ...string) *attributeResolution { |
| 165 | if len(qualifiers) == 1 { |
| 166 | return e.resolveSimpleIdent(qualifiers[0]) |
| 167 | } |
| 168 | local := e.lookupLocalIdent(qualifiers[0]) |
| 169 | if local != nil && !strings.HasPrefix(qualifiers[0], ".") { |
| 170 | // this should resolve through a field selection rather than a qualified identifier |
| 171 | return nil |
| 172 | } |
| 173 | // The qualifiers are concatenated together to indicate the qualified name to search |
| 174 | // for as a global identifier. Since select expressions are resolved from leaf to root |
| 175 | // if the fully concatenated string doesn't match a global identifier, indicate that |
| 176 | // no variable was found to continue the traversal up to the next simpler name. |
| 177 | varName := strings.Join(qualifiers, ".") |
| 178 | for _, candidate := range e.container.ResolveCandidateNames(varName) { |
| 179 | if ident := e.lookupGlobalIdent(candidate); ident != nil { |
| 180 | return newAttrResolution(ident, local != nil) |
| 181 | } |
| 182 | } |
| 183 | return nil |
| 184 | } |
| 185 | |
| 186 | // resolveTypeIdent returns a Decl proto for typeName as an identifier in the Env. |
| 187 | // Returns nil if no such identifier is found in the Env. |
| 188 | func (e *Env) resolveTypeIdent(name string) *decls.VariableDecl { |
| 189 | for _, candidate := range e.container.ResolveCandidateNames(name) { |
| 190 | // Try to import the name as a reference to a message type. |
| 191 | if i, found := e.provider.FindIdent(candidate); found { |
| 192 | if t, ok := i.(*types.Type); ok { |
| 193 | return decls.NewVariable(candidate, types.NewTypeTypeWithParam(t)) |
| 194 | } |
| 195 | } |
| 196 | // Next, try to find the struct type. |
| 197 | if t, found := e.provider.FindStructType(candidate); found { |
| 198 | return decls.NewVariable(candidate, t) |
| 199 | } |
| 200 | } |
| 201 | return nil |
| 202 | } |
| 203 | |
| 204 | // lookupLocalIdent finds the variable candidate in a local scope, returning nil if |
| 205 | // the candidate variable name is not a local variable. |
| 206 | func (e *Env) lookupLocalIdent(candidate string) *decls.VariableDecl { |
| 207 | return e.declarations.FindLocalIdent(candidate) |
| 208 | } |
| 209 | |
| 210 | // lookupGlobalIdent finds a candidate variable name in the root scope, returning |
| 211 | // nil if the identifier is not in the global scope. |
| 212 | func (e *Env) lookupGlobalIdent(candidate string) *decls.VariableDecl { |
| 213 | // Try to resolve the global identifier first. |
| 214 | if ident := e.declarations.FindGlobalIdent(candidate); ident != nil { |
| 215 | return ident |
| 216 | } |
| 217 | // Next try to import the name as a reference to a message type. |
| 218 | if i, found := e.provider.FindIdent(candidate); found { |
| 219 | if t, ok := i.(*types.Type); ok { |
| 220 | return decls.NewVariable(candidate, types.NewTypeTypeWithParam(t)) |
| 221 | } |
| 222 | } |
| 223 | if t, found := e.provider.FindStructType(candidate); found { |
| 224 | return decls.NewVariable(candidate, t) |
| 225 | } |
| 226 | // Next try to import this as an enum value by splitting the name in a type prefix and |
| 227 | // the enum inside. |
| 228 | if enumValue := e.provider.EnumValue(candidate); enumValue.Type() != types.ErrType { |
| 229 | return decls.NewConstant(candidate, types.IntType, enumValue) |
| 230 | } |
| 231 | return nil |
| 232 | } |
| 233 | |
| 234 | // lookupFunction returns a Decl proto for typeName as a function in env. |
| 235 | // Returns nil if no such function is found in env. |
| 236 | func (e *Env) lookupFunction(name string) *decls.FunctionDecl { |
| 237 | for _, candidate := range e.container.ResolveCandidateNames(name) { |
| 238 | if fn := e.declarations.FindFunction(candidate); fn != nil { |
| 239 | return fn |
| 240 | } |
| 241 | } |
| 242 | return nil |
| 243 | } |
| 244 | |
| 245 | // setFunction adds the function Decl to the Env. |
| 246 | // Adds a function decl if one doesn't already exist, then adds all overloads from the Decl. |
| 247 | // If overload overlaps with an existing overload, adds to the errors in the Env instead. |
| 248 | func (e *Env) setFunction(fn *decls.FunctionDecl) []errorMsg { |
| 249 | errMsgs := make([]errorMsg, 0) |
| 250 | current := e.declarations.FindFunction(fn.Name()) |
| 251 | if current != nil { |
| 252 | var err error |
| 253 | current, err = current.Merge(fn) |
| 254 | if err != nil { |
| 255 | return append(errMsgs, errorMsg(err.Error())) |
| 256 | } |
| 257 | } else { |
| 258 | current = fn |
| 259 | } |
| 260 | for _, overload := range current.OverloadDecls() { |
| 261 | for _, macro := range parser.AllMacros { |
| 262 | if macro.Function() == current.Name() && |
| 263 | macro.IsReceiverStyle() == overload.IsMemberFunction() && |
| 264 | macro.ArgCount() == len(overload.ArgTypes()) { |
| 265 | errMsgs = append(errMsgs, overlappingMacroError(current.Name(), macro.ArgCount())) |
| 266 | } |
| 267 | } |
| 268 | if len(errMsgs) > 0 { |
| 269 | return errMsgs |
| 270 | } |
| 271 | } |
| 272 | e.declarations.SetFunction(current) |
| 273 | return errMsgs |
| 274 | } |
| 275 | |
| 276 | // addIdent adds the Decl to the declarations in the Env. |
| 277 | // Returns a non-empty errorMsg if the identifier is already declared in the scope. |
| 278 | func (e *Env) addIdent(decl *decls.VariableDecl) errorMsg { |
| 279 | current := e.declarations.FindIdentInScope(decl.Name()) |
| 280 | if current != nil { |
| 281 | if current.DeclarationIsEquivalent(decl) { |
| 282 | return "" |
| 283 | } |
| 284 | return overlappingIdentifierError(decl.Name()) |
| 285 | } |
| 286 | e.declarations.AddIdent(decl) |
| 287 | return "" |
| 288 | } |
| 289 | |
| 290 | // isOverloadDisabled returns whether the overloadID is disabled in the current environment. |
| 291 | func (e *Env) isOverloadDisabled(overloadID string) bool { |
| 292 | _, found := e.filteredOverloadIDs[overloadID] |
| 293 | return found |
| 294 | } |
| 295 | |
| 296 | // validatedDeclarations returns a reference to the validated variable and function declaration scope stack. |
| 297 | // must be copied before use. |
| 298 | func (e *Env) validatedDeclarations() *Scopes { |
| 299 | return e.declarations |
| 300 | } |
| 301 | |
| 302 | // enterScope creates a new Env instance with a new innermost declaration scope. |
| 303 | func (e *Env) enterScope() *Env { |
| 304 | childDecls := e.declarations.Push() |
| 305 | return &Env{ |
| 306 | declarations: childDecls, |
| 307 | container: e.container, |
| 308 | provider: e.provider, |
| 309 | aggLitElemType: e.aggLitElemType, |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | // exitScope creates a new Env instance with the nearest outer declaration scope. |
| 314 | func (e *Env) exitScope() *Env { |
| 315 | parentDecls := e.declarations.Pop() |
| 316 | return &Env{ |
| 317 | declarations: parentDecls, |
| 318 | container: e.container, |
| 319 | provider: e.provider, |
| 320 | aggLitElemType: e.aggLitElemType, |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | // errorMsg is a type alias meant to represent error-based return values which |
| 325 | // may be accumulated into an error at a later point in execution. |
| 326 | type errorMsg string |
| 327 | |
| 328 | func overlappingIdentifierError(name string) errorMsg { |
| 329 | return errorMsg(fmt.Sprintf("overlapping identifier for name '%s'", name)) |
| 330 | } |
| 331 | |
| 332 | func overlappingMacroError(name string, argCount int) errorMsg { |
| 333 | return errorMsg(fmt.Sprintf( |
| 334 | "overlapping macro for name '%s' with %d args", name, argCount)) |
| 335 | } |
| 336 | |
| 337 | func formatError(errMsgs []errorMsg) error { |
| 338 | errStrs := make([]string, 0) |
| 339 | if len(errMsgs) > 0 { |
| 340 | for i := 0; i < len(errMsgs); i++ { |
| 341 | if errMsgs[i] != "" { |
| 342 | errStrs = append(errStrs, string(errMsgs[i])) |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | if len(errStrs) > 0 { |
| 347 | return fmt.Errorf("%s", strings.Join(errStrs, "\n")) |
| 348 | } |
| 349 | return nil |
| 350 | } |