Skip to content

Commit

Permalink
feat(ast): add support for LambdaExpr to infer type from return expr …
Browse files Browse the repository at this point in the history
…type (#1011)

This will enable it to be assigned to an appropriate variable

Before this change: cannot assign a lambda expression to a variable because its type is always VOID.

After this change: lambda expression builder will infer type from returnExpr’s expression type. Allowing it to be assigned to an appropriate variable. Because returnExpr is a required field, its type should always be accessible.

Example: a naive sample usage is provided in JavaWriterVisitorTest.java as test.
  • Loading branch information
zhumin8 committed Jul 11, 2022
1 parent 6e02c70 commit a179558
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
Expand Up @@ -27,9 +27,7 @@
public abstract class LambdaExpr implements Expr {
@Override
public TypeNode type() {
// TODO(v2): Support set of FunctionalInterface parameterized on the args and return type,
// which would enable assignment to an appropriate variable.
return TypeNode.VOID;
return returnExpr().expr().type();
}

public abstract ImmutableList<VariableExpr> arguments();
Expand Down
Expand Up @@ -14,6 +14,7 @@

package com.google.api.generator.engine.ast;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;

import java.util.Arrays;
Expand All @@ -27,6 +28,15 @@ public void validLambdaExpr_noArguments() {
.build();
}

@Test
public void validLambdaExpr_inferTypeFromReturnExpr() {
LambdaExpr lambdaExpr =
LambdaExpr.builder()
.setReturnExpr(ValueExpr.withValue(StringObjectValue.withValue("foo")))
.build();
assertEquals(TypeNode.STRING, lambdaExpr.type());
}

@Test
public void validLambdaExpr_severalArguments() {
VariableExpr argOneVarExpr =
Expand Down
Expand Up @@ -2345,6 +2345,23 @@ public void writeLambdaExpr_noParameters() {
assertEquals("() -> \"foo\"", writerVisitor.write());
}

@Test
public void writeLambdaExpr_assignToVariable() {
LambdaExpr lambdaExpr =
LambdaExpr.builder()
.setReturnExpr(ValueExpr.withValue(StringObjectValue.withValue("foo")))
.build();
AssignmentExpr assignmentExpr =
AssignmentExpr.builder()
.setVariableExpr(
VariableExpr.withVariable(
Variable.builder().setName("word").setType(TypeNode.STRING).build()))
.setValueExpr(lambdaExpr)
.build();
assignmentExpr.accept(writerVisitor);
assertEquals("word = () -> \"foo\"", writerVisitor.write());
}

@Test
public void writeLambdaExpr_oneParameter() {
VariableExpr argVarExpr =
Expand Down

0 comments on commit a179558

Please sign in to comment.