@@ -45,8 +45,7 @@ public Expression.Lambda lambda(List<Type> paramTypes, Function<Scope, Expressio
4545 Type .Struct params = Type .Struct .builder ().nullable (false ).addAllFields (paramTypes ).build ();
4646 pushLambdaContext (params );
4747 try {
48- int index = lambdaContext .size () - 1 ;
49- Scope scope = new Scope (index );
48+ Scope scope = new Scope (params );
5049 Expression body = bodyFn .apply (scope );
5150 return ImmutableExpression .Lambda .builder ().parameters (params ).body (body ).build ();
5251 } finally {
@@ -83,14 +82,14 @@ public Expression.Lambda lambdaFromStruct(
8382 * @throws IllegalArgumentException if stepsOut exceeds the current nesting depth
8483 */
8584 public Type .Struct resolveParams (int stepsOut ) {
86- int index = lambdaContext .size () - 1 - stepsOut ;
87- if (index < 0 || index >= lambdaContext .size ()) {
85+ int targetDepth = lambdaContext .size () - stepsOut ;
86+ if (targetDepth <= 0 || targetDepth > lambdaContext .size ()) {
8887 throw new IllegalArgumentException (
8988 String .format (
9089 "Lambda parameter reference with stepsOut=%d is invalid (current depth: %d)" ,
9190 stepsOut , lambdaContext .size ()));
9291 }
93- return lambdaContext .get (index );
92+ return lambdaContext .get (targetDepth - 1 );
9493 }
9594
9695 /**
@@ -115,24 +114,26 @@ private void popLambdaContext() {
115114 * parameter references.
116115 */
117116 public class Scope {
118- private final int index ;
117+ private final Type .Struct params ;
118+ private final int depth ;
119119
120- private Scope (int index ) {
121- this .index = index ;
120+ private Scope (Type .Struct params ) {
121+ this .params = params ;
122+ this .depth = lambdaContext .size ();
122123 }
123124
124125 /**
125126 * Creates a validated reference to a parameter of this lambda. The correct {@code stepsOut}
126- * value is computed automatically.
127+ * value is computed automatically as the difference between the current nesting depth and the
128+ * depth at which this scope was created.
127129 *
128130 * @param paramIndex index of the parameter within this lambda's parameter struct
129131 * @return a {@link FieldReference} pointing to the specified parameter
130132 * @throws IndexOutOfBoundsException if paramIndex is out of bounds
131133 */
132134 public FieldReference ref (int paramIndex ) {
133- int stepsOut = lambdaContext .size () - 1 - index ;
134- return FieldReference .newLambdaParameterReference (
135- paramIndex , lambdaContext .get (index ), stepsOut );
135+ int stepsOut = lambdaContext .size () - depth ;
136+ return FieldReference .newLambdaParameterReference (paramIndex , params , stepsOut );
136137 }
137138 }
138139}
0 commit comments