2121import dev .cel .expr .Type ;
2222import com .google .common .annotations .VisibleForTesting ;
2323import com .google .common .base .Preconditions ;
24+ import com .google .common .cache .CacheBuilder ;
25+ import com .google .common .cache .CacheLoader ;
26+ import com .google .common .cache .LoadingCache ;
2427import com .google .common .collect .ImmutableList ;
2528import com .google .common .collect .ImmutableMap ;
2629import com .google .common .collect .ImmutableSet ;
5861import java .util .List ;
5962import java .util .Map ;
6063import java .util .Optional ;
64+ import java .util .concurrent .ConcurrentHashMap ;
65+ import java .util .concurrent .ConcurrentMap ;
6166import org .jspecify .annotations .Nullable ;
6267
6368/**
@@ -117,6 +122,20 @@ public class Env {
117122 .enableNamespacedDeclarations (false )
118123 .build ();
119124
125+ /**
126+ * Standard declarations derived from {@link CelOptions}, keyed by {@link
127+ * #standardDeclarationsKey}.
128+ */
129+ private static final ConcurrentMap <Integer , CelStandardDeclarations > STANDARD_DECLARATIONS =
130+ new ConcurrentHashMap <>();
131+
132+ /**
133+ * Immutable scopes holding standard declarations, keyed by the identity of the declarations they
134+ * hold. Empty when adding the declarations reported errors.
135+ */
136+ private static final LoadingCache <CelStandardDeclarations , Optional <DeclGroup >> STANDARD_SCOPES =
137+ CacheBuilder .newBuilder ().weakKeys ().build (CacheLoader .from (Env ::buildStandardScope ));
138+
120139 /**
121140 * @deprecated Do not use. This exists for compatibility reasons. Migrate to CEL-Java fluent APIs.
122141 * See {@code CelCompilerFactory}.
@@ -208,13 +227,74 @@ static Env standard(
208227 CelOptions celOptions ) {
209228 Env env = Env .unconfigured (errors , celTypeProvider , legacyTypeProvider , celOptions );
210229 // Isolate the standard declarations into their own scope for forward compatibility.
211- celStandardDeclaration .functionDecls ().forEach (env ::add );
212- celStandardDeclaration .identifierDecls ().forEach (env ::add );
230+ env .addStandardDeclarations (celStandardDeclaration );
231+
232+ env .enterScope ();
233+ return env ;
234+ }
235+
236+ /**
237+ * Returns the standard declarations derived from {@code celOptions}, shared by all options
238+ * deriving the same declarations.
239+ */
240+ static CelStandardDeclarations standardDeclarations (CelOptions celOptions ) {
241+ return STANDARD_DECLARATIONS .computeIfAbsent (
242+ standardDeclarationsKey (celOptions ), unused -> newStandardDeclarations (celOptions ));
243+ }
244+
245+ /** Must account for every option read by {@link #newStandardDeclarations}. */
246+ private static int standardDeclarationsKey (CelOptions celOptions ) {
247+ return (celOptions .enableUnsignedLongs () ? 1 : 0 ) | (celOptions .enableTimestampEpoch () ? 2 : 0 );
248+ }
249+
250+ /**
251+ * Returns an immutable scope holding {@code celStandardDeclarations}, built once and shared by
252+ * environments created with {@link #fromStandardScope}. Returns {@code null} if adding the
253+ * declarations reported errors.
254+ */
255+ static @ Nullable DeclGroup standardScope (CelStandardDeclarations celStandardDeclarations ) {
256+ return STANDARD_SCOPES .getUnchecked (celStandardDeclarations ).orElse (null );
257+ }
258+
259+ private static Optional <DeclGroup > buildStandardScope (
260+ CelStandardDeclarations celStandardDeclarations ) {
261+ Errors errors = new Errors ("" , "" );
262+ // Adding declarations does not depend on the type providers or options.
263+ Env env = Env .unconfigured (errors , EMPTY_TYPE_PROVIDER , null , CelOptions .DEFAULT );
264+ env .addStandardDeclarations (celStandardDeclarations );
265+ if (errors .getErrorCount () > 0 ) {
266+ return Optional .empty ();
267+ }
268+ return Optional .of (env .getDeclGroup ().immutableCopy ());
269+ }
213270
271+ /**
272+ * Creates an {@code Env} value configured with a standard scope returned by {@link
273+ * #standardScope}. Equivalent to {@link #standard} without having to add the standard
274+ * declarations again.
275+ */
276+ static Env fromStandardScope (
277+ DeclGroup standardScope ,
278+ Errors errors ,
279+ CelTypeProvider celTypeProvider ,
280+ @ Nullable TypeProvider legacyTypeProvider ,
281+ CelOptions celOptions ) {
282+ Env env =
283+ new Env (
284+ errors ,
285+ celTypeProvider ,
286+ legacyTypeProvider ,
287+ DeclGroup .layeredOn (standardScope ),
288+ celOptions );
214289 env .enterScope ();
215290 return env ;
216291 }
217292
293+ private void addStandardDeclarations (CelStandardDeclarations celStandardDeclarations ) {
294+ celStandardDeclarations .functionDecls ().forEach (this ::add );
295+ celStandardDeclarations .identifierDecls ().forEach (this ::add );
296+ }
297+
218298 @ Deprecated
219299 public static Env standard (
220300 CelStandardDeclarations celStandardDeclaration ,
@@ -993,21 +1073,28 @@ public static class DeclGroup {
9931073 private final Map <String , CelVarDecl > idents ;
9941074 private final Map <String , CelFunctionDecl > functions ;
9951075
1076+ /**
1077+ * Immutable group whose declarations are visible through this one, unless this group holds a
1078+ * declaration with the same name.
1079+ */
1080+ private final @ Nullable DeclGroup base ;
1081+
9961082 /**
9971083 * Get an immutable map of the identifiers in the {@code DeclGroup} keyed by declaration name.
9981084 */
9991085 public ImmutableMap <String , CelVarDecl > getIdents () {
1000- return ImmutableMap .copyOf (idents );
1086+ return base == null ? ImmutableMap .copyOf (idents ) : merge ( base . idents , idents );
10011087 }
10021088
10031089 /** Get an immutable map of the functions in the {@code DeclGroup} keyed by declaration name. */
10041090 public ImmutableMap <String , CelFunctionDecl > getFunctions () {
1005- return ImmutableMap .copyOf (functions );
1091+ return base == null ? ImmutableMap .copyOf (functions ) : merge ( base . functions , functions );
10061092 }
10071093
10081094 /** Get an identifier declaration by {@code name}. Returns {@code null} if absent. */
10091095 public @ Nullable CelVarDecl getIdent (String name ) {
1010- return idents .get (name );
1096+ CelVarDecl ident = idents .get (name );
1097+ return ident == null && base != null ? base .getIdent (name ) : ident ;
10111098 }
10121099
10131100 /** Put an identifier declaration into the {@code DeclGroup}. */
@@ -1017,17 +1104,52 @@ public void putIdent(CelVarDecl ident) {
10171104
10181105 /** Get a function declaration by {@code name}. Returns {@code null} if absent. */
10191106 public @ Nullable CelFunctionDecl getFunction (String name ) {
1020- return functions .get (name );
1107+ CelFunctionDecl function = functions .get (name );
1108+ return function == null && base != null ? base .getFunction (name ) : function ;
10211109 }
10221110
10231111 /** Put a function declaration into the {@code DeclGroup}. */
10241112 public void putFunction (CelFunctionDecl function ) {
10251113 functions .put (function .name (), function );
10261114 }
10271115
1116+ /**
1117+ * Returns an immutable copy of this {@code DeclGroup}, which can be safely shared across
1118+ * environments and threads.
1119+ */
1120+ private DeclGroup immutableCopy () {
1121+ return new DeclGroup (
1122+ ImmutableMap .copyOf (idents ), ImmutableMap .copyOf (functions ), /* base= */ null );
1123+ }
1124+
1125+ /**
1126+ * Returns a new mutable {@code DeclGroup} exposing the declarations of the immutable {@code
1127+ * base} group, where new declarations are only added to the new group.
1128+ */
1129+ private static DeclGroup layeredOn (DeclGroup base ) {
1130+ Preconditions .checkArgument (base .base == null , "base group must not be layered" );
1131+ return new DeclGroup (new HashMap <>(), new HashMap <>(), base );
1132+ }
1133+
1134+ private static <V > ImmutableMap <String , V > merge (
1135+ Map <String , V > base , Map <String , V > overrides ) {
1136+ return ImmutableMap .<String , V >builderWithExpectedSize (base .size () + overrides .size ())
1137+ .putAll (base )
1138+ .putAll (overrides )
1139+ .buildKeepingLast ();
1140+ }
1141+
10281142 private DeclGroup () {
1029- this .idents = new HashMap <>();
1030- this .functions = new HashMap <>();
1143+ this (new HashMap <>(), new HashMap <>(), /* base= */ null );
1144+ }
1145+
1146+ private DeclGroup (
1147+ Map <String , CelVarDecl > idents ,
1148+ Map <String , CelFunctionDecl > functions ,
1149+ @ Nullable DeclGroup base ) {
1150+ this .idents = idents ;
1151+ this .functions = functions ;
1152+ this .base = base ;
10311153 }
10321154 }
10331155
0 commit comments