-
Notifications
You must be signed in to change notification settings - Fork 307
Add a maps extension with maps.merge #1409
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lopster568
wants to merge
1
commit into
cel-expr:master
Choose a base branch
from
lopster568:maps-merge-extension
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| // Copyright 2026 Google LLC | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package ext | ||
|
|
||
| import ( | ||
| "github.com/google/cel-go/cel" | ||
| "github.com/google/cel-go/checker" | ||
| "github.com/google/cel-go/common" | ||
| "github.com/google/cel-go/common/types" | ||
| "github.com/google/cel-go/common/types/ref" | ||
| "github.com/google/cel-go/common/types/traits" | ||
| "github.com/google/cel-go/interpreter" | ||
| ) | ||
|
|
||
| // Maps returns a cel.EnvOption to configure namespaced map functions. | ||
| // | ||
| // CEL has no operator for combining two maps: the `+` operator concatenates | ||
| // strings, bytes, and lists, but is not defined for maps. This library provides | ||
| // map combination as a named function. | ||
| // | ||
| // # Maps.Merge | ||
| // | ||
| // Returns a new map containing the entries of both arguments. When a key is | ||
| // present in both, the value from the second argument wins. Neither input is | ||
| // modified. | ||
| // | ||
| // The merge is shallow: a value that is itself a map is replaced rather than | ||
| // merged recursively. | ||
| // | ||
| // maps.merge(map(K, V), map(K, V)) -> map(K, V) | ||
| // | ||
| // Examples: | ||
| // | ||
| // maps.merge({}, {}) // {} | ||
| // maps.merge({'a': 1}, {'b': 2}) // {'a': 1, 'b': 2} | ||
| // maps.merge({'a': 1}, {'a': 2}) // {'a': 2} | ||
| // maps.merge({'a': {'x': 1}}, {'a': {'y': 2}}) // {'a': {'y': 2}}, values are replaced, not merged | ||
| func Maps(options ...MapsOption) cel.EnvOption { | ||
| l := &mapsLib{} | ||
| for _, o := range options { | ||
| l = o(l) | ||
| } | ||
| return cel.Lib(l) | ||
| } | ||
|
|
||
| // MapsOption declares a functional operator for configuring map extensions. | ||
| type MapsOption func(*mapsLib) *mapsLib | ||
|
|
||
| // MapsVersion sets the library version for map extensions. | ||
| func MapsVersion(version uint32) MapsOption { | ||
| return func(lib *mapsLib) *mapsLib { | ||
| lib.version = version | ||
| return lib | ||
| } | ||
| } | ||
|
|
||
| type mapsLib struct { | ||
| version uint32 | ||
| } | ||
|
|
||
| // LibraryName implements the SingletonLibrary interface method. | ||
| func (mapsLib) LibraryName() string { | ||
| return "cel.lib.ext.maps" | ||
| } | ||
|
|
||
| // CompileOptions implements the Library interface method. | ||
| func (mapsLib) CompileOptions() []cel.EnvOption { | ||
| mapType := cel.MapType(cel.TypeParamType("K"), cel.TypeParamType("V")) | ||
| return []cel.EnvOption{ | ||
| cel.Function("maps.merge", | ||
| cel.Overload("map_maps_merge_map", []*cel.Type{mapType, mapType}, mapType, | ||
| cel.BinaryBinding(mapsMerge))), | ||
| cel.CostEstimatorOptions( | ||
| checker.OverloadCostEstimate("map_maps_merge_map", estimateMapsMergeCost), | ||
| ), | ||
| } | ||
| } | ||
|
|
||
| // ProgramOptions implements the Library interface method. | ||
| func (mapsLib) ProgramOptions() []cel.ProgramOption { | ||
| return []cel.ProgramOption{ | ||
| cel.CostTrackerOptions( | ||
| interpreter.OverloadCostTracker("map_maps_merge_map", trackMapsMergeCost), | ||
| ), | ||
| } | ||
| } | ||
|
|
||
| // estimateMapsMergeCost charges for visiting every entry of both inputs and for | ||
| // allocating the result map. | ||
| func estimateMapsMergeCost(estimator checker.CostEstimator, _ *checker.AstNode, args []checker.AstNode) *checker.CallEstimate { | ||
| if len(args) != 2 { | ||
| return nil | ||
| } | ||
| lhsSize := estimateSize(estimator, args[0]) | ||
| rhsSize := estimateSize(estimator, args[1]) | ||
| entries := lhsSize.Add(rhsSize) | ||
| cost := entries.MultiplyByCostFactor(1).Add(mapAllocCost).Add(callCostEstimate) | ||
| // The result holds at least as many entries as the larger input, when every | ||
| // key collides, and at most the sum of both, when none do. | ||
| resultSize := rangedSizeEstimate(max(lhsSize.Min, rhsSize.Min), entries.Max) | ||
| return callEstimate(cost, &resultSize) | ||
| } | ||
|
|
||
| // trackMapsMergeCost mirrors estimateMapsMergeCost against the actual inputs. | ||
| func trackMapsMergeCost(args []ref.Val, _ ref.Val) *uint64 { | ||
| entries := safeAdd(actualSize(args[0]), actualSize(args[1])) | ||
| cost := safeAdd(callCost, uint64(common.MapCreateBaseCost), entries) | ||
| return &cost | ||
| } | ||
|
|
||
| // mapsMerge returns a new map holding the entries of both inputs, with the | ||
| // values of the second input taking precedence on conflicting keys. | ||
| func mapsMerge(lhs, rhs ref.Val) ref.Val { | ||
| first, ok := lhs.(traits.Mapper) | ||
| if !ok { | ||
| return types.MaybeNoSuchOverloadErr(lhs) | ||
| } | ||
| second, ok := rhs.(traits.Mapper) | ||
| if !ok { | ||
| return types.MaybeNoSuchOverloadErr(rhs) | ||
| } | ||
| merged := make(map[ref.Val]ref.Val, actualSize(first)+actualSize(second)) | ||
| if err := copyEntries(first, merged); err != nil { | ||
| return err | ||
| } | ||
| if err := copyEntries(second, merged); err != nil { | ||
| return err | ||
| } | ||
| return types.NewRefValMap(types.DefaultTypeAdapter, merged) | ||
| } | ||
|
|
||
| // copyEntries writes every entry of m into dst, overwriting entries whose keys | ||
| // are already present. It returns a non-nil ref.Val only when the map yields an | ||
| // error or unknown value. | ||
| func copyEntries(m traits.Mapper, dst map[ref.Val]ref.Val) ref.Val { | ||
| it := m.Iterator() | ||
| for it.HasNext() == types.True { | ||
| key := it.Next() | ||
| if types.IsUnknownOrError(key) { | ||
| return key | ||
| } | ||
| val, _ := m.Find(key) | ||
| if types.IsUnknownOrError(val) { | ||
| return val | ||
| } | ||
| dst[key] = val | ||
| } | ||
| return nil | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Normally, I'd say this is a good idea, but let's just make it a member function instead since sometimes it's hard to remember the direction of the merge when it's a global function.