| 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 decls contains function and variable declaration structs and helper methods. |
| 16 |
package decls |
| 17 |
|
| 18 |
import ( |
| 19 |
"fmt" |
| 20 |
"strings" |
| 21 |
|
| 22 |
chkdecls "github.com/google/cel-go/checker/decls" |
| 23 |
"github.com/google/cel-go/common" |
| 24 |
"github.com/google/cel-go/common/functions" |
| 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 |
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" |
| 30 |
) |
| 31 |
|
| 32 |
// NewFunction creates a new function declaration with a set of function options to configure overloads |
| 33 |
// and function definitions (implementations). |
| 34 |
// |
| 35 |
// Functions are checked for name collisions and singleton redefinition. |
| 36 |
func NewFunction(name string, opts ...FunctionOpt) (*FunctionDecl, error) { |
| 37 |
fn := &FunctionDecl{ |
| 38 |
name: name, |
| 39 |
overloads: map[string]*OverloadDecl{}, |
| 40 |
overloadOrdinals: []string{}, |
| 41 |
} |
| 42 |
var err error |
| 43 |
for _, opt := range opts { |
| 44 |
fn, err = opt(fn) |
| 45 |
if err != nil { |
| 46 |
return nil, err |
| 47 |
} |
| 48 |
} |
| 49 |
if len(fn.overloads) == 0 { |
| 50 |
return nil, fmt.Errorf("function %s must have at least one overload", name) |
| 51 |
} |
| 52 |
return fn, nil |
| 53 |
} |
| 54 |
|
| 55 |
// FunctionDecl defines a function name, overload set, and optionally a singleton definition for all |
| 56 |
// overload instances. |
| 57 |
type FunctionDecl struct { |
| 58 |
name string |
| 59 |
doc string |
| 60 |
|
| 61 |
// overloads associated with the function name. |
| 62 |
overloads map[string]*OverloadDecl |
| 63 |
|
| 64 |
// singleton implementation of the function for all overloads. |
| 65 |
// |
| 66 |
// If this option is set, an error will occur if any overloads specify a per-overload implementation |
| 67 |
// or if another function with the same name attempts to redefine the singleton. |
| 68 |
singleton *functions.Overload |
| 69 |
|
| 70 |
// disableTypeGuards is a performance optimization to disable detailed runtime type checks which could |
| 71 |
// add overhead on common operations. Setting this option true leaves error checks and argument checks |
| 72 |
// intact. |
| 73 |
disableTypeGuards bool |
| 74 |
|
| 75 |
// state indicates that the binding should be provided as a declaration, as a runtime binding, or both. |
| 76 |
state declarationState |
| 77 |
|
| 78 |
// overloadOrdinals indicates the order in which the overload was declared. |
| 79 |
overloadOrdinals []string |
| 80 |
} |
| 81 |
|
| 82 |
type declarationState int |
| 83 |
|
| 84 |
const ( |
| 85 |
declarationStateUnset declarationState = iota |
| 86 |
declarationDisabled |
| 87 |
declarationEnabled |
| 88 |
) |
| 89 |
|
| 90 |
// Documentation generates documentation about the Function and its overloads as a common.Doc object. |
| 91 |
func (f *FunctionDecl) Documentation() *common.Doc { |
| 92 |
if f == nil { |
| 93 |
return nil |
| 94 |
} |
| 95 |
children := make([]*common.Doc, len(f.OverloadDecls())) |
| 96 |
for i, o := range f.OverloadDecls() { |
| 97 |
var examples []*common.Doc |
| 98 |
for _, ex := range o.Examples() { |
| 99 |
examples = append(examples, common.NewExampleDoc(ex)) |
| 100 |
} |
| 101 |
od := common.NewOverloadDoc(o.ID(), formatSignature(f.Name(), o), examples...) |
| 102 |
children[i] = od |
| 103 |
} |
| 104 |
return common.NewFunctionDoc( |
| 105 |
f.Name(), |
| 106 |
f.Description(), |
| 107 |
children...) |
| 108 |
} |
| 109 |
|
| 110 |
// Name returns the function name in human-readable terms, e.g. 'contains' of 'math.least' |
| 111 |
func (f *FunctionDecl) Name() string { |
| 112 |
if f == nil { |
| 113 |
return "" |
| 114 |
} |
| 115 |
return f.name |
| 116 |
} |
| 117 |
|
| 118 |
// Description provides an overview of the function's purpose. |
| 119 |
// |
| 120 |
// Usage examples should be included on specific overloads. |
| 121 |
func (f *FunctionDecl) Description() string { |
| 122 |
if f == nil { |
| 123 |
return "" |
| 124 |
} |
| 125 |
return f.doc |
| 126 |
} |
| 127 |
|
| 128 |
// IsDeclarationDisabled indicates that the function implementation should be added to the dispatcher, but the |
| 129 |
// declaration should not be exposed for use in expressions. |
| 130 |
func (f *FunctionDecl) IsDeclarationDisabled() bool { |
| 131 |
if f == nil { |
| 132 |
return true |
| 133 |
} |
| 134 |
return f.state == declarationDisabled |
| 135 |
} |
| 136 |
|
| 137 |
// Merge combines an existing function declaration with another. |
| 138 |
// |
| 139 |
// If a function is extended, by say adding new overloads to an existing function, then it is merged with the |
| 140 |
// prior definition of the function at which point its overloads must not collide with pre-existing overloads |
| 141 |
// and its bindings (singleton, or per-overload) must not conflict with previous definitions either. |
| 142 |
func (f *FunctionDecl) Merge(other *FunctionDecl) (*FunctionDecl, error) { |
| 143 |
if f == other { |
| 144 |
return f, nil |
| 145 |
} |
| 146 |
if f == nil || other == nil || f.Name() != other.Name() { |
| 147 |
return nil, fmt.Errorf("cannot merge unrelated functions. %q and %q", f.Name(), other.Name()) |
| 148 |
} |
| 149 |
merged := &FunctionDecl{ |
| 150 |
name: f.Name(), |
| 151 |
overloads: make(map[string]*OverloadDecl, len(f.overloads)), |
| 152 |
singleton: f.singleton, |
| 153 |
overloadOrdinals: make([]string, len(f.overloads)), |
| 154 |
// if one function is expecting type-guards and the other is not, then they |
| 155 |
// must not be disabled. |
| 156 |
disableTypeGuards: f.disableTypeGuards && other.disableTypeGuards, |
| 157 |
// default to the current functions declaration state. |
| 158 |
state: f.state, |
| 159 |
doc: f.doc, |
| 160 |
} |
| 161 |
// If the other state indicates that the declaration should be explicitly enabled or |
| 162 |
// disabled, then update the merged state with the most recent value. |
| 163 |
if other.state != declarationStateUnset { |
| 164 |
merged.state = other.state |
| 165 |
} |
| 166 |
// Allow for non-empty overrides of documentation |
| 167 |
if len(other.doc) != 0 && f.doc != other.doc { |
| 168 |
merged.doc = other.doc |
| 169 |
} |
| 170 |
// baseline copy of the overloads and their ordinals |
| 171 |
copy(merged.overloadOrdinals, f.overloadOrdinals) |
| 172 |
for oID, o := range f.overloads { |
| 173 |
merged.overloads[oID] = o |
| 174 |
} |
| 175 |
// overloads and their ordinals are added from the left |
| 176 |
for _, oID := range other.overloadOrdinals { |
| 177 |
o := other.overloads[oID] |
| 178 |
err := merged.AddOverload(o) |
| 179 |
if err != nil { |
| 180 |
return nil, fmt.Errorf("function declaration merge failed: %v", err) |
| 181 |
} |
| 182 |
} |
| 183 |
if other.singleton != nil { |
| 184 |
if merged.singleton != nil && merged.singleton != other.singleton { |
| 185 |
return nil, fmt.Errorf("function already has a singleton binding: %s", f.Name()) |
| 186 |
} |
| 187 |
merged.singleton = other.singleton |
| 188 |
} |
| 189 |
return merged, nil |
| 190 |
} |
| 191 |
|
| 192 |
// FunctionSubsetter subsets a function declaration or returns nil and false if the function |
| 193 |
// subset was empty. |
| 194 |
type FunctionSubsetter func(fn *FunctionDecl) (*FunctionDecl, bool) |
| 195 |
|
| 196 |
// OverloadSelector selects an overload associated with a given function when it returns true. |
| 197 |
// |
| 198 |
// Used in combination with the Subset method. |
| 199 |
type OverloadSelector func(overload *OverloadDecl) bool |
| 200 |
|
| 201 |
// IncludeOverloads defines an OverloadSelector which allow-lists a set of overloads by their ids. |
| 202 |
func IncludeOverloads(overloadIDs ...string) OverloadSelector { |
| 203 |
return func(overload *OverloadDecl) bool { |
| 204 |
for _, oID := range overloadIDs { |
| 205 |
if overload.id == oID { |
| 206 |
return true |
| 207 |
} |
| 208 |
} |
| 209 |
return false |
| 210 |
} |
| 211 |
} |
| 212 |
|
| 213 |
// ExcludeOverloads defines an OverloadSelector which deny-lists a set of overloads by their ids. |
| 214 |
func ExcludeOverloads(overloadIDs ...string) OverloadSelector { |
| 215 |
return func(overload *OverloadDecl) bool { |
| 216 |
for _, oID := range overloadIDs { |
| 217 |
if overload.id == oID { |
| 218 |
return false |
| 219 |
} |
| 220 |
} |
| 221 |
return true |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
// Subset returns a new function declaration which contains only the overloads with the specified IDs. |
| 226 |
// If the subset function contains no overloads, then nil is returned to indicate the function is not |
| 227 |
// functional. |
| 228 |
func (f *FunctionDecl) Subset(selector OverloadSelector) *FunctionDecl { |
| 229 |
if f == nil { |
| 230 |
return nil |
| 231 |
} |
| 232 |
overloads := make(map[string]*OverloadDecl) |
| 233 |
overloadOrdinals := make([]string, 0, len(f.overloadOrdinals)) |
| 234 |
for _, oID := range f.overloadOrdinals { |
| 235 |
overload := f.overloads[oID] |
| 236 |
if selector(overload) { |
| 237 |
overloads[oID] = overload |
| 238 |
overloadOrdinals = append(overloadOrdinals, oID) |
| 239 |
} |
| 240 |
} |
| 241 |
if len(overloads) == 0 { |
| 242 |
return nil |
| 243 |
} |
| 244 |
subset := &FunctionDecl{ |
| 245 |
name: f.Name(), |
| 246 |
doc: f.doc, |
| 247 |
overloads: overloads, |
| 248 |
singleton: f.singleton, |
| 249 |
disableTypeGuards: f.disableTypeGuards, |
| 250 |
state: f.state, |
| 251 |
overloadOrdinals: overloadOrdinals, |
| 252 |
} |
| 253 |
return subset |
| 254 |
} |
| 255 |
|
| 256 |
// AddOverload ensures that the new overload does not collide with an existing overload signature; |
| 257 |
// however, if the function signatures are identical, the implementation may be rewritten as its |
| 258 |
// difficult to compare functions by object identity. |
| 259 |
func (f *FunctionDecl) AddOverload(overload *OverloadDecl) error { |
| 260 |
if f == nil { |
| 261 |
return fmt.Errorf("nil function cannot add overload: %s", overload.ID()) |
| 262 |
} |
| 263 |
if overload == nil { |
| 264 |
return fmt.Errorf("cannot add nil overload to funciton: %s", f.Name()) |
| 265 |
} |
| 266 |
for oID, o := range f.overloads { |
| 267 |
if oID != overload.ID() && o.SignatureOverlaps(overload) { |
| 268 |
return fmt.Errorf("overload signature collision in function %s: %s collides with %s", f.Name(), oID, overload.ID()) |
| 269 |
} |
| 270 |
if oID == overload.ID() { |
| 271 |
if o.SignatureEquals(overload) && o.IsNonStrict() == overload.IsNonStrict() { |
| 272 |
// Allow redefinition of an overload implementation so long as the signatures match. |
| 273 |
if overload.hasBinding() { |
| 274 |
f.overloads[oID] = overload |
| 275 |
} |
| 276 |
// Allow redefinition of the doc string. |
| 277 |
if len(overload.doc) != 0 && o.doc != overload.doc { |
| 278 |
o.doc = overload.doc |
| 279 |
} |
| 280 |
return nil |
| 281 |
} |
| 282 |
return fmt.Errorf("overload redefinition in function. %s: %s has multiple definitions", f.Name(), oID) |
| 283 |
} |
| 284 |
if overload.HasLateBinding() != o.HasLateBinding() { |
| 285 |
return fmt.Errorf("overload with late binding cannot be added to function %s: cannot mix late and non-late bindings", f.Name()) |
| 286 |
} |
| 287 |
} |
| 288 |
f.overloadOrdinals = append(f.overloadOrdinals, overload.ID()) |
| 289 |
f.overloads[overload.ID()] = overload |
| 290 |
return nil |
| 291 |
} |
| 292 |
|
| 293 |
// OverloadDecls returns the overload declarations in the order in which they were declared. |
| 294 |
func (f *FunctionDecl) OverloadDecls() []*OverloadDecl { |
| 295 |
var emptySet []*OverloadDecl |
| 296 |
if f == nil { |
| 297 |
return emptySet |
| 298 |
} |
| 299 |
overloads := make([]*OverloadDecl, 0, len(f.overloads)) |
| 300 |
for _, oID := range f.overloadOrdinals { |
| 301 |
overloads = append(overloads, f.overloads[oID]) |
| 302 |
} |
| 303 |
return overloads |
| 304 |
} |
| 305 |
|
| 306 |
// HasLateBinding returns true if the function has late bindings. A function cannot mix late bindings with other bindings. |
| 307 |
func (f *FunctionDecl) HasLateBinding() bool { |
| 308 |
if f == nil { |
| 309 |
return false |
| 310 |
} |
| 311 |
for _, oID := range f.overloadOrdinals { |
| 312 |
if f.overloads[oID].HasLateBinding() { |
| 313 |
return true |
| 314 |
} |
| 315 |
} |
| 316 |
return false |
| 317 |
} |
| 318 |
|
| 319 |
// Bindings produces a set of function bindings, if any are defined. |
| 320 |
func (f *FunctionDecl) Bindings() ([]*functions.Overload, error) { |
| 321 |
var emptySet []*functions.Overload |
| 322 |
if f == nil { |
| 323 |
return emptySet, nil |
| 324 |
} |
| 325 |
overloads := []*functions.Overload{} |
| 326 |
nonStrict := false |
| 327 |
hasLateBinding := false |
| 328 |
for _, oID := range f.overloadOrdinals { |
| 329 |
o := f.overloads[oID] |
| 330 |
hasLateBinding = hasLateBinding || o.HasLateBinding() |
| 331 |
if o.hasBinding() { |
| 332 |
overload := &functions.Overload{ |
| 333 |
Operator: o.ID(), |
| 334 |
Unary: o.guardedUnaryOp(f.Name(), f.disableTypeGuards), |
| 335 |
Binary: o.guardedBinaryOp(f.Name(), f.disableTypeGuards), |
| 336 |
Function: o.guardedFunctionOp(f.Name(), f.disableTypeGuards), |
| 337 |
OperandTrait: o.OperandTrait(), |
| 338 |
NonStrict: o.IsNonStrict(), |
| 339 |
} |
| 340 |
overloads = append(overloads, overload) |
| 341 |
nonStrict = nonStrict || o.IsNonStrict() |
| 342 |
} |
| 343 |
} |
| 344 |
if f.singleton != nil { |
| 345 |
if len(overloads) != 0 { |
| 346 |
return nil, fmt.Errorf("singleton function incompatible with specialized overloads: %s", f.Name()) |
| 347 |
} |
| 348 |
if hasLateBinding { |
| 349 |
return nil, fmt.Errorf("singleton function incompatible with late bindings: %s", f.Name()) |
| 350 |
} |
| 351 |
overloads = []*functions.Overload{ |
| 352 |
{ |
| 353 |
Operator: f.Name(), |
| 354 |
Unary: f.singleton.Unary, |
| 355 |
Binary: f.singleton.Binary, |
| 356 |
Function: f.singleton.Function, |
| 357 |
OperandTrait: f.singleton.OperandTrait, |
| 358 |
}, |
| 359 |
} |
| 360 |
// fall-through to return single overload case. |
| 361 |
} |
| 362 |
if len(overloads) == 0 { |
| 363 |
return overloads, nil |
| 364 |
} |
| 365 |
// Single overload. Replicate an entry for it using the function name as well. |
| 366 |
if len(overloads) == 1 { |
| 367 |
if overloads[0].Operator == f.Name() { |
| 368 |
return overloads, nil |
| 369 |
} |
| 370 |
return append(overloads, &functions.Overload{ |
| 371 |
Operator: f.Name(), |
| 372 |
Unary: overloads[0].Unary, |
| 373 |
Binary: overloads[0].Binary, |
| 374 |
Function: overloads[0].Function, |
| 375 |
NonStrict: overloads[0].NonStrict, |
| 376 |
OperandTrait: overloads[0].OperandTrait, |
| 377 |
}), nil |
| 378 |
} |
| 379 |
// All of the defined overloads are wrapped into a top-level function which |
| 380 |
// performs dynamic dispatch to the proper overload based on the argument types. |
| 381 |
bindings := append([]*functions.Overload{}, overloads...) |
| 382 |
funcDispatch := func(args ...ref.Val) ref.Val { |
| 383 |
for _, oID := range f.overloadOrdinals { |
| 384 |
o := f.overloads[oID] |
| 385 |
// During dynamic dispatch over multiple functions, signature agreement checks |
| 386 |
// are preserved in order to assist with the function resolution step. |
| 387 |
switch len(args) { |
| 388 |
case 1: |
| 389 |
if o.unaryOp != nil && o.matchesRuntimeSignature(f.disableTypeGuards, args...) { |
| 390 |
return o.unaryOp(args[0]) |
| 391 |
} |
| 392 |
case 2: |
| 393 |
if o.binaryOp != nil && o.matchesRuntimeSignature(f.disableTypeGuards, args...) { |
| 394 |
return o.binaryOp(args[0], args[1]) |
| 395 |
} |
| 396 |
} |
| 397 |
if o.functionOp != nil && o.matchesRuntimeSignature(f.disableTypeGuards, args...) { |
| 398 |
return o.functionOp(args...) |
| 399 |
} |
| 400 |
// eventually this will fall through to the noSuchOverload below. |
| 401 |
} |
| 402 |
return MaybeNoSuchOverload(f.Name(), args...) |
| 403 |
} |
| 404 |
function := &functions.Overload{ |
| 405 |
Operator: f.Name(), |
| 406 |
Function: funcDispatch, |
| 407 |
NonStrict: nonStrict, |
| 408 |
} |
| 409 |
return append(bindings, function), nil |
| 410 |
} |
| 411 |
|
| 412 |
// MaybeNoSuchOverload determines whether to propagate an error if one is provided as an argument, or |
| 413 |
// to return an unknown set, or to produce a new error for a missing function signature. |
| 414 |
func MaybeNoSuchOverload(funcName string, args ...ref.Val) ref.Val { |
| 415 |
argTypes := make([]string, len(args)) |
| 416 |
var unk *types.Unknown = nil |
| 417 |
for i, arg := range args { |
| 418 |
if types.IsError(arg) { |
| 419 |
return arg |
| 420 |
} |
| 421 |
if types.IsUnknown(arg) { |
| 422 |
unk = types.MergeUnknowns(arg.(*types.Unknown), unk) |
| 423 |
} |
| 424 |
argTypes[i] = arg.Type().TypeName() |
| 425 |
} |
| 426 |
if unk != nil { |
| 427 |
return unk |
| 428 |
} |
| 429 |
signature := strings.Join(argTypes, ", ") |
| 430 |
return types.NewErr("no such overload: %s(%s)", funcName, signature) |
| 431 |
} |
| 432 |
|
| 433 |
// FunctionOpt defines a functional option for mutating a function declaration. |
| 434 |
type FunctionOpt func(*FunctionDecl) (*FunctionDecl, error) |
| 435 |
|
| 436 |
// FunctionDocs configures documentation from a list of strings separated by newlines. |
| 437 |
func FunctionDocs(docs ...string) FunctionOpt { |
| 438 |
return func(fn *FunctionDecl) (*FunctionDecl, error) { |
| 439 |
fn.doc = common.MultilineDescription(docs...) |
| 440 |
return fn, nil |
| 441 |
} |
| 442 |
} |
| 443 |
|
| 444 |
// DisableTypeGuards disables automatically generated function invocation guards on direct overload calls. |
| 445 |
// Type guards remain on during dynamic dispatch for parsed-only expressions. |
| 446 |
func DisableTypeGuards(value bool) FunctionOpt { |
| 447 |
return func(fn *FunctionDecl) (*FunctionDecl, error) { |
| 448 |
fn.disableTypeGuards = value |
| 449 |
return fn, nil |
| 450 |
} |
| 451 |
} |
| 452 |
|
| 453 |
// DisableDeclaration indicates that the function declaration should be disabled, but the runtime function |
| 454 |
// binding should be provided. Marking a function as runtime-only is a safe way to manage deprecations |
| 455 |
// of function declarations while still preserving the runtime behavior for previously compiled expressions. |
| 456 |
func DisableDeclaration(value bool) FunctionOpt { |
| 457 |
return func(fn *FunctionDecl) (*FunctionDecl, error) { |
| 458 |
if value { |
| 459 |
fn.state = declarationDisabled |
| 460 |
} else { |
| 461 |
fn.state = declarationEnabled |
| 462 |
} |
| 463 |
return fn, nil |
| 464 |
} |
| 465 |
} |
| 466 |
|
| 467 |
// SingletonUnaryBinding creates a singleton function definition to be used for all function overloads. |
| 468 |
// |
| 469 |
// Note, this approach works well if operand is expected to have a specific trait which it implements, |
| 470 |
// e.g. traits.ContainerType. Otherwise, prefer per-overload function bindings. |
| 471 |
func SingletonUnaryBinding(fn functions.UnaryOp, traits ...int) FunctionOpt { |
| 472 |
trait := 0 |
| 473 |
for _, t := range traits { |
| 474 |
trait = trait | t |
| 475 |
} |
| 476 |
return func(f *FunctionDecl) (*FunctionDecl, error) { |
| 477 |
if f.singleton != nil { |
| 478 |
return nil, fmt.Errorf("function already has a singleton binding: %s", f.Name()) |
| 479 |
} |
| 480 |
f.singleton = &functions.Overload{ |
| 481 |
Operator: f.Name(), |
| 482 |
Unary: fn, |
| 483 |
OperandTrait: trait, |
| 484 |
} |
| 485 |
return f, nil |
| 486 |
} |
| 487 |
} |
| 488 |
|
| 489 |
// SingletonBinaryBinding creates a singleton function definition to be used with all function overloads. |
| 490 |
// |
| 491 |
// Note, this approach works well if operand is expected to have a specific trait which it implements, |
| 492 |
// e.g. traits.ContainerType. Otherwise, prefer per-overload function bindings. |
| 493 |
func SingletonBinaryBinding(fn functions.BinaryOp, traits ...int) FunctionOpt { |
| 494 |
trait := 0 |
| 495 |
for _, t := range traits { |
| 496 |
trait = trait | t |
| 497 |
} |
| 498 |
return func(f *FunctionDecl) (*FunctionDecl, error) { |
| 499 |
if f.singleton != nil { |
| 500 |
return nil, fmt.Errorf("function already has a singleton binding: %s", f.Name()) |
| 501 |
} |
| 502 |
f.singleton = &functions.Overload{ |
| 503 |
Operator: f.Name(), |
| 504 |
Binary: fn, |
| 505 |
OperandTrait: trait, |
| 506 |
} |
| 507 |
return f, nil |
| 508 |
} |
| 509 |
} |
| 510 |
|
| 511 |
// SingletonFunctionBinding creates a singleton function definition to be used with all function overloads. |
| 512 |
// |
| 513 |
// Note, this approach works well if operand is expected to have a specific trait which it implements, |
| 514 |
// e.g. traits.ContainerType. Otherwise, prefer per-overload function bindings. |
| 515 |
func SingletonFunctionBinding(fn functions.FunctionOp, traits ...int) FunctionOpt { |
| 516 |
trait := 0 |
| 517 |
for _, t := range traits { |
| 518 |
trait = trait | t |
| 519 |
} |
| 520 |
return func(f *FunctionDecl) (*FunctionDecl, error) { |
| 521 |
if f.singleton != nil { |
| 522 |
return nil, fmt.Errorf("function already has a singleton binding: %s", f.Name()) |
| 523 |
} |
| 524 |
f.singleton = &functions.Overload{ |
| 525 |
Operator: f.Name(), |
| 526 |
Function: fn, |
| 527 |
OperandTrait: trait, |
| 528 |
} |
| 529 |
return f, nil |
| 530 |
} |
| 531 |
} |
| 532 |
|
| 533 |
// Overload defines a new global overload with an overload id, argument types, and result type. Through the |
| 534 |
// use of OverloadOpt options, the overload may also be configured with a binding, an operand trait, and to |
| 535 |
// be non-strict. |
| 536 |
// |
| 537 |
// Note: function bindings should be commonly configured with Overload instances whereas operand traits and |
| 538 |
// strict-ness should be rare occurrences. |
| 539 |
func Overload(overloadID string, |
| 540 |
args []*types.Type, resultType *types.Type, |
| 541 |
opts ...OverloadOpt) FunctionOpt { |
| 542 |
return newOverload(overloadID, false, args, resultType, opts...) |
| 543 |
} |
| 544 |
|
| 545 |
// MemberOverload defines a new receiver-style overload (or member function) with an overload id, argument types, |
| 546 |
// and result type. Through the use of OverloadOpt options, the overload may also be configured with a binding, |
| 547 |
// an operand trait, and to be non-strict. |
| 548 |
// |
| 549 |
// Note: function bindings should be commonly configured with Overload instances whereas operand traits and |
| 550 |
// strict-ness should be rare occurrences. |
| 551 |
func MemberOverload(overloadID string, |
| 552 |
args []*types.Type, resultType *types.Type, |
| 553 |
opts ...OverloadOpt) FunctionOpt { |
| 554 |
return newOverload(overloadID, true, args, resultType, opts...) |
| 555 |
} |
| 556 |
|
| 557 |
func newOverload(overloadID string, |
| 558 |
memberFunction bool, args []*types.Type, resultType *types.Type, |
| 559 |
opts ...OverloadOpt) FunctionOpt { |
| 560 |
return func(f *FunctionDecl) (*FunctionDecl, error) { |
| 561 |
overload, err := newOverloadInternal(overloadID, memberFunction, args, resultType, opts...) |
| 562 |
if err != nil { |
| 563 |
return nil, err |
| 564 |
} |
| 565 |
err = f.AddOverload(overload) |
| 566 |
if err != nil { |
| 567 |
return nil, err |
| 568 |
} |
| 569 |
return f, nil |
| 570 |
} |
| 571 |
} |
| 572 |
|
| 573 |
func newOverloadInternal(overloadID string, |
| 574 |
memberFunction bool, args []*types.Type, resultType *types.Type, |
| 575 |
opts ...OverloadOpt) (*OverloadDecl, error) { |
| 576 |
overload := &OverloadDecl{ |
| 577 |
id: overloadID, |
| 578 |
argTypes: args, |
| 579 |
resultType: resultType, |
| 580 |
isMemberFunction: memberFunction, |
| 581 |
} |
| 582 |
var err error |
| 583 |
for _, opt := range opts { |
| 584 |
overload, err = opt(overload) |
| 585 |
if err != nil { |
| 586 |
return nil, err |
| 587 |
} |
| 588 |
} |
| 589 |
return overload, nil |
| 590 |
} |
| 591 |
|
| 592 |
// OverloadDecl contains the definition of a single overload id with a specific signature, and an optional |
| 593 |
// implementation. |
| 594 |
type OverloadDecl struct { |
| 595 |
id string |
| 596 |
doc string |
| 597 |
argTypes []*types.Type |
| 598 |
resultType *types.Type |
| 599 |
isMemberFunction bool |
| 600 |
// hasLateBinding indicates that the function has a binding which is not known at compile time. |
| 601 |
// This is useful for functions which have side-effects or are not deterministically computable. |
| 602 |
hasLateBinding bool |
| 603 |
// nonStrict indicates that the function will accept error and unknown arguments as inputs. |
| 604 |
nonStrict bool |
| 605 |
// operandTrait indicates whether the member argument should have a specific type-trait. |
| 606 |
// |
| 607 |
// This is useful for creating overloads which operate on a type-interface rather than a concrete type. |
| 608 |
operandTrait int |
| 609 |
|
| 610 |
// Function implementation options. Optional, but encouraged. |
| 611 |
// unaryOp is a function binding that takes a single argument. |
| 612 |
unaryOp functions.UnaryOp |
| 613 |
// binaryOp is a function binding that takes two arguments. |
| 614 |
binaryOp functions.BinaryOp |
| 615 |
// functionOp is a catch-all for zero-arity and three-plus arity functions. |
| 616 |
functionOp functions.FunctionOp |
| 617 |
} |
| 618 |
|
| 619 |
// Examples returns a list of string examples for the overload. |
| 620 |
func (o *OverloadDecl) Examples() []string { |
| 621 |
var emptySet []string |
| 622 |
if o == nil || len(o.doc) == 0 { |
| 623 |
return emptySet |
| 624 |
} |
| 625 |
return common.ParseDescriptions(o.doc) |
| 626 |
} |
| 627 |
|
| 628 |
// ID mirrors the overload signature and provides a unique id which may be referenced within the type-checker |
| 629 |
// and interpreter to optimize performance. |
| 630 |
// |
| 631 |
// The ID format is usually one of two styles: |
| 632 |
// global: <functionName>_<argType>_<argTypeN> |
| 633 |
// member: <memberType>_<functionName>_<argType>_<argTypeN> |
| 634 |
func (o *OverloadDecl) ID() string { |
| 635 |
if o == nil { |
| 636 |
return "" |
| 637 |
} |
| 638 |
return o.id |
| 639 |
} |
| 640 |
|
| 641 |
// ArgTypes contains the set of argument types expected by the overload. |
| 642 |
// |
| 643 |
// For member functions ArgTypes[0] represents the member operand type. |
| 644 |
func (o *OverloadDecl) ArgTypes() []*types.Type { |
| 645 |
if o == nil { |
| 646 |
return emptyArgs |
| 647 |
} |
| 648 |
return o.argTypes |
| 649 |
} |
| 650 |
|
| 651 |
// IsMemberFunction indicates whether the overload is a member function |
| 652 |
func (o *OverloadDecl) IsMemberFunction() bool { |
| 653 |
if o == nil { |
| 654 |
return false |
| 655 |
} |
| 656 |
return o.isMemberFunction |
| 657 |
} |
| 658 |
|
| 659 |
// IsNonStrict returns whether the overload accepts errors and unknown values as arguments. |
| 660 |
func (o *OverloadDecl) IsNonStrict() bool { |
| 661 |
if o == nil { |
| 662 |
return false |
| 663 |
} |
| 664 |
return o.nonStrict |
| 665 |
} |
| 666 |
|
| 667 |
// HasLateBinding returns whether the overload has a binding which is not known at compile time. |
| 668 |
func (o *OverloadDecl) HasLateBinding() bool { |
| 669 |
if o == nil { |
| 670 |
return false |
| 671 |
} |
| 672 |
return o.hasLateBinding |
| 673 |
} |
| 674 |
|
| 675 |
// OperandTrait returns the trait mask of the first operand to the overload call, e.g. |
| 676 |
// `traits.Indexer` |
| 677 |
func (o *OverloadDecl) OperandTrait() int { |
| 678 |
if o == nil { |
| 679 |
return 0 |
| 680 |
} |
| 681 |
return o.operandTrait |
| 682 |
} |
| 683 |
|
| 684 |
// ResultType indicates the output type from calling the function. |
| 685 |
func (o *OverloadDecl) ResultType() *types.Type { |
| 686 |
if o == nil { |
| 687 |
// *types.Type is nil-safe |
| 688 |
return nil |
| 689 |
} |
| 690 |
return o.resultType |
| 691 |
} |
| 692 |
|
| 693 |
// TypeParams returns the type parameter names associated with the overload. |
| 694 |
func (o *OverloadDecl) TypeParams() []string { |
| 695 |
typeParams := map[string]struct{}{} |
| 696 |
collectParamNames(typeParams, o.ResultType()) |
| 697 |
for _, arg := range o.ArgTypes() { |
| 698 |
collectParamNames(typeParams, arg) |
| 699 |
} |
| 700 |
params := make([]string, 0, len(typeParams)) |
| 701 |
for param := range typeParams { |
| 702 |
params = append(params, param) |
| 703 |
} |
| 704 |
return params |
| 705 |
} |
| 706 |
|
| 707 |
// SignatureEquals determines whether the incoming overload declaration signature is equal to the current signature. |
| 708 |
// |
| 709 |
// Result type, operand trait, and strict-ness are not considered as part of signature equality. |
| 710 |
func (o *OverloadDecl) SignatureEquals(other *OverloadDecl) bool { |
| 711 |
if o == other { |
| 712 |
return true |
| 713 |
} |
| 714 |
if o.ID() != other.ID() || o.IsMemberFunction() != other.IsMemberFunction() || len(o.ArgTypes()) != len(other.ArgTypes()) { |
| 715 |
return false |
| 716 |
} |
| 717 |
for i, at := range o.ArgTypes() { |
| 718 |
oat := other.ArgTypes()[i] |
| 719 |
if !at.IsEquivalentType(oat) { |
| 720 |
return false |
| 721 |
} |
| 722 |
} |
| 723 |
return o.ResultType().IsEquivalentType(other.ResultType()) |
| 724 |
} |
| 725 |
|
| 726 |
// SignatureOverlaps indicates whether two functions have non-equal, but overloapping function signatures. |
| 727 |
// |
| 728 |
// For example, list(dyn) collides with list(string) since the 'dyn' type can contain a 'string' type. |
| 729 |
func (o *OverloadDecl) SignatureOverlaps(other *OverloadDecl) bool { |
| 730 |
if o.IsMemberFunction() != other.IsMemberFunction() || len(o.ArgTypes()) != len(other.ArgTypes()) { |
| 731 |
return false |
| 732 |
} |
| 733 |
argsOverlap := true |
| 734 |
for i, argType := range o.ArgTypes() { |
| 735 |
otherArgType := other.ArgTypes()[i] |
| 736 |
argsOverlap = argsOverlap && |
| 737 |
(argType.IsAssignableType(otherArgType) || |
| 738 |
otherArgType.IsAssignableType(argType)) |
| 739 |
} |
| 740 |
return argsOverlap |
| 741 |
} |
| 742 |
|
| 743 |
// hasBinding indicates whether the overload already has a definition. |
| 744 |
func (o *OverloadDecl) hasBinding() bool { |
| 745 |
return o != nil && (o.unaryOp != nil || o.binaryOp != nil || o.functionOp != nil) |
| 746 |
} |
| 747 |
|
| 748 |
// guardedUnaryOp creates an invocation guard around the provided unary operator, if one is defined. |
| 749 |
func (o *OverloadDecl) guardedUnaryOp(funcName string, disableTypeGuards bool) functions.UnaryOp { |
| 750 |
if o.unaryOp == nil { |
| 751 |
return nil |
| 752 |
} |
| 753 |
return func(arg ref.Val) ref.Val { |
| 754 |
if !o.matchesRuntimeUnarySignature(disableTypeGuards, arg) { |
| 755 |
return MaybeNoSuchOverload(funcName, arg) |
| 756 |
} |
| 757 |
return o.unaryOp(arg) |
| 758 |
} |
| 759 |
} |
| 760 |
|
| 761 |
// guardedBinaryOp creates an invocation guard around the provided binary operator, if one is defined. |
| 762 |
func (o *OverloadDecl) guardedBinaryOp(funcName string, disableTypeGuards bool) functions.BinaryOp { |
| 763 |
if o.binaryOp == nil { |
| 764 |
return nil |
| 765 |
} |
| 766 |
return func(arg1, arg2 ref.Val) ref.Val { |
| 767 |
if !o.matchesRuntimeBinarySignature(disableTypeGuards, arg1, arg2) { |
| 768 |
return MaybeNoSuchOverload(funcName, arg1, arg2) |
| 769 |
} |
| 770 |
return o.binaryOp(arg1, arg2) |
| 771 |
} |
| 772 |
} |
| 773 |
|
| 774 |
// guardedFunctionOp creates an invocation guard around the provided variadic function binding, if one is provided. |
| 775 |
func (o *OverloadDecl) guardedFunctionOp(funcName string, disableTypeGuards bool) functions.FunctionOp { |
| 776 |
if o.functionOp == nil { |
| 777 |
return nil |
| 778 |
} |
| 779 |
return func(args ...ref.Val) ref.Val { |
| 780 |
if !o.matchesRuntimeSignature(disableTypeGuards, args...) { |
| 781 |
return MaybeNoSuchOverload(funcName, args...) |
| 782 |
} |
| 783 |
return o.functionOp(args...) |
| 784 |
} |
| 785 |
} |
| 786 |
|
| 787 |
// matchesRuntimeUnarySignature indicates whether the argument type is runtime assiganble to the overload's expected argument. |
| 788 |
func (o *OverloadDecl) matchesRuntimeUnarySignature(disableTypeGuards bool, arg ref.Val) bool { |
| 789 |
return matchRuntimeArgType(o.IsNonStrict(), disableTypeGuards, o.ArgTypes()[0], arg) && |
| 790 |
matchOperandTrait(o.OperandTrait(), arg) |
| 791 |
} |
| 792 |
|
| 793 |
// matchesRuntimeBinarySignature indicates whether the argument types are runtime assiganble to the overload's expected arguments. |
| 794 |
func (o *OverloadDecl) matchesRuntimeBinarySignature(disableTypeGuards bool, arg1, arg2 ref.Val) bool { |
| 795 |
return matchRuntimeArgType(o.IsNonStrict(), disableTypeGuards, o.ArgTypes()[0], arg1) && |
| 796 |
matchRuntimeArgType(o.IsNonStrict(), disableTypeGuards, o.ArgTypes()[1], arg2) && |
| 797 |
matchOperandTrait(o.OperandTrait(), arg1) |
| 798 |
} |
| 799 |
|
| 800 |
// matchesRuntimeSignature indicates whether the argument types are runtime assiganble to the overload's expected arguments. |
| 801 |
func (o *OverloadDecl) matchesRuntimeSignature(disableTypeGuards bool, args ...ref.Val) bool { |
| 802 |
if len(args) != len(o.ArgTypes()) { |
| 803 |
return false |
| 804 |
} |
| 805 |
if len(args) == 0 { |
| 806 |
return true |
| 807 |
} |
| 808 |
for i, arg := range args { |
| 809 |
if !matchRuntimeArgType(o.IsNonStrict(), disableTypeGuards, o.ArgTypes()[i], arg) { |
| 810 |
return false |
| 811 |
} |
| 812 |
} |
| 813 |
return matchOperandTrait(o.OperandTrait(), args[0]) |
| 814 |
} |
| 815 |
|
| 816 |
func matchRuntimeArgType(nonStrict, disableTypeGuards bool, argType *types.Type, arg ref.Val) bool { |
| 817 |
if nonStrict && (disableTypeGuards || types.IsUnknownOrError(arg)) { |
| 818 |
return true |
| 819 |
} |
| 820 |
if types.IsUnknownOrError(arg) { |
| 821 |
return false |
| 822 |
} |
| 823 |
return disableTypeGuards || argType.IsAssignableRuntimeType(arg) |
| 824 |
} |
| 825 |
|
| 826 |
func matchOperandTrait(trait int, arg ref.Val) bool { |
| 827 |
return trait == 0 || arg.Type().HasTrait(trait) || types.IsUnknownOrError(arg) |
| 828 |
} |
| 829 |
|
| 830 |
// OverloadOpt is a functional option for configuring a function overload. |
| 831 |
type OverloadOpt func(*OverloadDecl) (*OverloadDecl, error) |
| 832 |
|
| 833 |
// OverloadExamples configures example expressions for the overload. |
| 834 |
func OverloadExamples(examples ...string) OverloadOpt { |
| 835 |
return func(o *OverloadDecl) (*OverloadDecl, error) { |
| 836 |
o.doc = common.MultilineDescription(examples...) |
| 837 |
return o, nil |
| 838 |
} |
| 839 |
} |
| 840 |
|
| 841 |
// UnaryBinding provides the implementation of a unary overload. The provided function is protected by a runtime |
| 842 |
// type-guard which ensures runtime type agreement between the overload signature and runtime argument types. |
| 843 |
func UnaryBinding(binding functions.UnaryOp) OverloadOpt { |
| 844 |
return func(o *OverloadDecl) (*OverloadDecl, error) { |
| 845 |
if o.hasBinding() { |
| 846 |
return nil, fmt.Errorf("overload already has a binding: %s", o.ID()) |
| 847 |
} |
| 848 |
if len(o.ArgTypes()) != 1 { |
| 849 |
return nil, fmt.Errorf("unary function bound to non-unary overload: %s", o.ID()) |
| 850 |
} |
| 851 |
if o.hasLateBinding { |
| 852 |
return nil, fmt.Errorf("overload already has a late binding: %s", o.ID()) |
| 853 |
} |
| 854 |
o.unaryOp = binding |
| 855 |
return o, nil |
| 856 |
} |
| 857 |
} |
| 858 |
|
| 859 |
// BinaryBinding provides the implementation of a binary overload. The provided function is protected by a runtime |
| 860 |
// type-guard which ensures runtime type agreement between the overload signature and runtime argument types. |
| 861 |
func BinaryBinding(binding functions.BinaryOp) OverloadOpt { |
| 862 |
return func(o *OverloadDecl) (*OverloadDecl, error) { |
| 863 |
if o.hasBinding() { |
| 864 |
return nil, fmt.Errorf("overload already has a binding: %s", o.ID()) |
| 865 |
} |
| 866 |
if len(o.ArgTypes()) != 2 { |
| 867 |
return nil, fmt.Errorf("binary function bound to non-binary overload: %s", o.ID()) |
| 868 |
} |
| 869 |
if o.hasLateBinding { |
| 870 |
return nil, fmt.Errorf("overload already has a late binding: %s", o.ID()) |
| 871 |
} |
| 872 |
o.binaryOp = binding |
| 873 |
return o, nil |
| 874 |
} |
| 875 |
} |
| 876 |
|
| 877 |
// FunctionBinding provides the implementation of a variadic overload. The provided function is protected by a runtime |
| 878 |
// type-guard which ensures runtime type agreement between the overload signature and runtime argument types. |
| 879 |
func FunctionBinding(binding functions.FunctionOp) OverloadOpt { |
| 880 |
return func(o *OverloadDecl) (*OverloadDecl, error) { |
| 881 |
if o.hasBinding() { |
| 882 |
return nil, fmt.Errorf("overload already has a binding: %s", o.ID()) |
| 883 |
} |
| 884 |
if o.hasLateBinding { |
| 885 |
return nil, fmt.Errorf("overload already has a late binding: %s", o.ID()) |
| 886 |
} |
| 887 |
o.functionOp = binding |
| 888 |
return o, nil |
| 889 |
} |
| 890 |
} |
| 891 |
|
| 892 |
// LateFunctionBinding indicates that the function has a binding which is not known at compile time. |
| 893 |
// This is useful for functions which have side-effects or are not deterministically computable. |
| 894 |
func LateFunctionBinding() OverloadOpt { |
| 895 |
return func(o *OverloadDecl) (*OverloadDecl, error) { |
| 896 |
if o.hasBinding() { |
| 897 |
return nil, fmt.Errorf("overload already has a binding: %s", o.ID()) |
| 898 |
} |
| 899 |
o.hasLateBinding = true |
| 900 |
return o, nil |
| 901 |
} |
| 902 |
} |
| 903 |
|
| 904 |
// OverloadIsNonStrict enables the function to be called with error and unknown argument values. |
| 905 |
// |
| 906 |
// Note: do not use this option unless absoluately necessary as it should be an uncommon feature. |
| 907 |
func OverloadIsNonStrict() OverloadOpt { |
| 908 |
return func(o *OverloadDecl) (*OverloadDecl, error) { |
| 909 |
o.nonStrict = true |
| 910 |
return o, nil |
| 911 |
} |
| 912 |
} |
| 913 |
|
| 914 |
// OverloadOperandTrait configures a set of traits which the first argument to the overload must implement in order to be |
| 915 |
// successfully invoked. |
| 916 |
func OverloadOperandTrait(trait int) OverloadOpt { |
| 917 |
return func(o *OverloadDecl) (*OverloadDecl, error) { |
| 918 |
o.operandTrait = trait |
| 919 |
return o, nil |
| 920 |
} |
| 921 |
} |
| 922 |
|
| 923 |
// NewConstant creates a new constant declaration. |
| 924 |
func NewConstant(name string, t *types.Type, v ref.Val) *VariableDecl { |
| 925 |
return &VariableDecl{name: name, varType: t, value: v} |
| 926 |
} |
| 927 |
|
| 928 |
// NewVariable creates a new variable declaration. |
| 929 |
func NewVariable(name string, t *types.Type) *VariableDecl { |
| 930 |
return &VariableDecl{name: name, varType: t} |
| 931 |
} |
| 932 |
|
| 933 |
// NewVariableWithDoc creates a new variable declaration with usage documentation. |
| 934 |
func NewVariableWithDoc(name string, t *types.Type, doc string) *VariableDecl { |
| 935 |
return &VariableDecl{name: name, varType: t, doc: doc} |
| 936 |
} |
| 937 |
|
| 938 |
// VariableDecl defines a variable declaration which may optionally have a constant value. |
| 939 |
type VariableDecl struct { |
| 940 |
name string |
| 941 |
doc string |
| 942 |
varType *types.Type |
| 943 |
value ref.Val |
| 944 |
} |
| 945 |
|
| 946 |
// Documentation returns name, type, and description for the variable. |
| 947 |
func (v *VariableDecl) Documentation() *common.Doc { |
| 948 |
if v == nil { |
| 949 |
return nil |
| 950 |
} |
| 951 |
return common.NewVariableDoc(v.Name(), describeCELType(v.Type()), v.Description()) |
| 952 |
} |
| 953 |
|
| 954 |
// Name returns the fully-qualified variable name |
| 955 |
func (v *VariableDecl) Name() string { |
| 956 |
if v == nil { |
| 957 |
return "" |
| 958 |
} |
| 959 |
return v.name |
| 960 |
} |
| 961 |
|
| 962 |
// Description returns the usage documentation for the variable, if set. |
| 963 |
// |
| 964 |
// Good usage instructions provide information about the valid formats, ranges, sizes for the variable type. |
| 965 |
func (v *VariableDecl) Description() string { |
| 966 |
if v == nil { |
| 967 |
return "" |
| 968 |
} |
| 969 |
return v.doc |
| 970 |
} |
| 971 |
|
| 972 |
// Type returns the types.Type value associated with the variable. |
| 973 |
func (v *VariableDecl) Type() *types.Type { |
| 974 |
if v == nil { |
| 975 |
// types.Type is nil-safe |
| 976 |
return nil |
| 977 |
} |
| 978 |
return v.varType |
| 979 |
} |
| 980 |
|
| 981 |
// Value returns the constant value associated with the declaration. |
| 982 |
func (v *VariableDecl) Value() ref.Val { |
| 983 |
if v == nil { |
| 984 |
return nil |
| 985 |
} |
| 986 |
return v.value |
| 987 |
} |
| 988 |
|
| 989 |
// DeclarationIsEquivalent returns true if one variable declaration has the same name and same type as the input. |
| 990 |
func (v *VariableDecl) DeclarationIsEquivalent(other *VariableDecl) bool { |
| 991 |
if v == other { |
| 992 |
return true |
| 993 |
} |
| 994 |
return v.Name() == other.Name() && v.Type().IsEquivalentType(other.Type()) |
| 995 |
} |
| 996 |
|
| 997 |
// TypeVariable creates a new type identifier for use within a types.Provider |
| 998 |
func TypeVariable(t *types.Type) *VariableDecl { |
| 999 |
return NewVariable(t.TypeName(), types.NewTypeTypeWithParam(t)) |
| 1000 |
} |
| 1001 |
|
| 1002 |
// VariableDeclToExprDecl converts a go-native variable declaration into a protobuf-type variable declaration. |
| 1003 |
func VariableDeclToExprDecl(v *VariableDecl) (*exprpb.Decl, error) { |
| 1004 |
return variableDeclToExprDecl(v) |
| 1005 |
} |
| 1006 |
|
| 1007 |
// variableDeclToExprDecl converts a go-native variable declaration into a protobuf-type variable declaration. |
| 1008 |
func variableDeclToExprDecl(v *VariableDecl) (*exprpb.Decl, error) { |
| 1009 |
varType, err := types.TypeToExprType(v.Type()) |
| 1010 |
if err != nil { |
| 1011 |
return nil, err |
| 1012 |
} |
| 1013 |
return chkdecls.NewVarWithDoc(v.Name(), varType, v.doc), nil |
| 1014 |
} |
| 1015 |
|
| 1016 |
// FunctionDeclToExprDecl converts a go-native function declaration into a protobuf-typed function declaration. |
| 1017 |
func FunctionDeclToExprDecl(f *FunctionDecl) (*exprpb.Decl, error) { |
| 1018 |
return functionDeclToExprDecl(f) |
| 1019 |
} |
| 1020 |
|
| 1021 |
// functionDeclToExprDecl converts a go-native function declaration into a protobuf-typed function declaration. |
| 1022 |
func functionDeclToExprDecl(f *FunctionDecl) (*exprpb.Decl, error) { |
| 1023 |
overloads := make([]*exprpb.Decl_FunctionDecl_Overload, len(f.overloads)) |
| 1024 |
for i, oID := range f.overloadOrdinals { |
| 1025 |
o := f.overloads[oID] |
| 1026 |
paramNames := map[string]struct{}{} |
| 1027 |
argTypes := make([]*exprpb.Type, len(o.ArgTypes())) |
| 1028 |
for j, a := range o.ArgTypes() { |
| 1029 |
collectParamNames(paramNames, a) |
| 1030 |
at, err := types.TypeToExprType(a) |
| 1031 |
if err != nil { |
| 1032 |
return nil, err |
| 1033 |
} |
| 1034 |
argTypes[j] = at |
| 1035 |
} |
| 1036 |
collectParamNames(paramNames, o.ResultType()) |
| 1037 |
resultType, err := types.TypeToExprType(o.ResultType()) |
| 1038 |
if err != nil { |
| 1039 |
return nil, err |
| 1040 |
} |
| 1041 |
if len(paramNames) == 0 { |
| 1042 |
if o.IsMemberFunction() { |
| 1043 |
overloads[i] = chkdecls.NewInstanceOverload(oID, argTypes, resultType) |
| 1044 |
} else { |
| 1045 |
overloads[i] = chkdecls.NewOverload(oID, argTypes, resultType) |
| 1046 |
} |
| 1047 |
} else { |
| 1048 |
params := []string{} |
| 1049 |
for pn := range paramNames { |
| 1050 |
params = append(params, pn) |
| 1051 |
} |
| 1052 |
if o.IsMemberFunction() { |
| 1053 |
overloads[i] = chkdecls.NewParameterizedInstanceOverload(oID, argTypes, resultType, params) |
| 1054 |
} else { |
| 1055 |
overloads[i] = chkdecls.NewParameterizedOverload(oID, argTypes, resultType, params) |
| 1056 |
} |
| 1057 |
} |
| 1058 |
doc := common.MultilineDescription(o.Examples()...) |
| 1059 |
overloads[i].Doc = doc |
| 1060 |
} |
| 1061 |
return chkdecls.NewFunctionWithDoc(f.Name(), f.Description(), overloads...), nil |
| 1062 |
} |
| 1063 |
|
| 1064 |
func collectParamNames(paramNames map[string]struct{}, arg *types.Type) { |
| 1065 |
if arg.Kind() == types.TypeParamKind { |
| 1066 |
paramNames[arg.TypeName()] = struct{}{} |
| 1067 |
} |
| 1068 |
for _, param := range arg.Parameters() { |
| 1069 |
collectParamNames(paramNames, param) |
| 1070 |
} |
| 1071 |
} |
| 1072 |
|
| 1073 |
func formatSignature(fnName string, o *OverloadDecl) string { |
| 1074 |
if opName, isOperator := operators.FindReverse(fnName); isOperator { |
| 1075 |
if opName == "" { |
| 1076 |
opName = fnName |
| 1077 |
} |
| 1078 |
return formatOperator(opName, o) |
| 1079 |
} |
| 1080 |
return formatCall(fnName, o) |
| 1081 |
} |
| 1082 |
|
| 1083 |
func formatOperator(opName string, o *OverloadDecl) string { |
| 1084 |
args := o.ArgTypes() |
| 1085 |
argTypes := make([]string, len(o.ArgTypes())) |
| 1086 |
for j, a := range args { |
| 1087 |
argTypes[j] = describeCELType(a) |
| 1088 |
} |
| 1089 |
ret := describeCELType(o.ResultType()) |
| 1090 |
switch len(args) { |
| 1091 |
case 1: |
| 1092 |
return fmt.Sprintf("%s%s -> %s", opName, argTypes[0], ret) |
| 1093 |
case 2: |
| 1094 |
if opName == operators.Index { |
| 1095 |
return fmt.Sprintf("%s[%s] -> %s", argTypes[0], argTypes[1], ret) |
| 1096 |
} |
| 1097 |
return fmt.Sprintf("%s %s %s -> %s", argTypes[0], opName, argTypes[1], ret) |
| 1098 |
default: |
| 1099 |
if opName == operators.Conditional { |
| 1100 |
return fmt.Sprint("bool ? <T> : <T> -> <T>") |
| 1101 |
} |
| 1102 |
return formatCall(opName, o) |
| 1103 |
} |
| 1104 |
} |
| 1105 |
|
| 1106 |
func formatCall(funcName string, o *OverloadDecl) string { |
| 1107 |
args := make([]string, len(o.ArgTypes())) |
| 1108 |
ret := describeCELType(o.ResultType()) |
| 1109 |
for j, a := range o.ArgTypes() { |
| 1110 |
args[j] = describeCELType(a) |
| 1111 |
} |
| 1112 |
if o.IsMemberFunction() { |
| 1113 |
target := args[0] |
| 1114 |
args = args[1:] |
| 1115 |
return fmt.Sprintf("%s.%s(%s) -> %s", target, funcName, strings.Join(args, ", "), ret) |
| 1116 |
} |
| 1117 |
return fmt.Sprintf("%s(%s) -> %s", funcName, strings.Join(args, ", "), ret) |
| 1118 |
} |
| 1119 |
|
| 1120 |
func describeCELType(t *types.Type) string { |
| 1121 |
if t.Kind() == types.TypeKind { |
| 1122 |
return "type" |
| 1123 |
} |
| 1124 |
return t.String() |
| 1125 |
} |
| 1126 |
|
| 1127 |
var ( |
| 1128 |
emptyArgs []*types.Type |
| 1129 |
) |