1616
1717import static com .google .common .base .Preconditions .checkArgument ;
1818import static com .google .common .base .Preconditions .checkNotNull ;
19+ import static com .google .common .collect .ImmutableList .toImmutableList ;
1920
2021import com .google .common .collect .ImmutableList ;
2122import com .google .common .primitives .UnsignedLong ;
@@ -58,6 +59,7 @@ public enum Function {
5859 HAS_VALUE ("hasValue" ),
5960 OPTIONAL_NONE ("optional.none" ),
6061 OPTIONAL_OF ("optional.of" ),
62+ OPTIONAL_ELIDE ("optional.elide" ),
6163 OPTIONAL_OF_NON_ZERO_VALUE ("optional.ofNonZeroValue" ),
6264 OR ("or" ),
6365 OR_VALUE ("orValue" );
@@ -117,6 +119,10 @@ public void setCheckerOptions(CelCheckerBuilder checkerBuilder) {
117119 CelFunctionDecl .newFunctionDeclaration (
118120 Function .HAS_VALUE .getFunction (),
119121 CelOverloadDecl .newMemberOverload ("optional_hasValue" , SimpleType .BOOL , optionalTypeV )),
122+ CelFunctionDecl .newFunctionDeclaration (
123+ Function .OPTIONAL_ELIDE .getFunction (),
124+ CelOverloadDecl .newGlobalOverload (
125+ "optional_elide_list" , listTypeV , ListType .create (optionalTypeV ))),
120126 // Note: Implementation of "or" and "orValue" are special-cased inside the interpreter.
121127 // Hence, their bindings are not provided here.
122128 CelFunctionDecl .newFunctionDeclaration (
@@ -165,6 +171,7 @@ public void setCheckerOptions(CelCheckerBuilder checkerBuilder) {
165171 }
166172
167173 @ Override
174+ @ SuppressWarnings ("unchecked" )
168175 public void setRuntimeOptions (CelRuntimeBuilder runtimeBuilder ) {
169176 runtimeBuilder .addFunctionBindings (
170177 CelRuntime .CelFunctionBinding .from ("optional_of" , Object .class , Optional ::of ),
@@ -177,6 +184,8 @@ public void setRuntimeOptions(CelRuntimeBuilder runtimeBuilder) {
177184 }
178185 return Optional .of (val );
179186 }),
187+ CelRuntime .CelFunctionBinding .from (
188+ "optional_elide_list" , Collection .class , CelOptionalLibrary ::elideOptionalCollection ),
180189 CelRuntime .CelFunctionBinding .from (
181190 "optional_none" , ImmutableList .of (), val -> Optional .empty ()),
182191 CelRuntime .CelFunctionBinding .from (
@@ -185,6 +194,10 @@ public void setRuntimeOptions(CelRuntimeBuilder runtimeBuilder) {
185194 "optional_hasValue" , Object .class , val -> ((Optional <?>) val ).isPresent ()));
186195 }
187196
197+ private static ImmutableList <Object > elideOptionalCollection (Collection <Optional <Object >> list ) {
198+ return list .stream ().filter (Optional ::isPresent ).map (Optional ::get ).collect (toImmutableList ());
199+ }
200+
188201 // TODO: This will need to be adapted to handle an intermediate CelValue instead,
189202 // akin to Zeroer interface in Go. Currently, it is unable to handle zero-values for a
190203 // user-defined custom type.
0 commit comments