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 authored Jul 11, 2022
1 parent dfe7e74 commit b24892d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 b24892d

Please sign in to comment.