Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(ast): add support for LambdaExpr to infer type from return expr type #1011

Merged
merged 5 commits into from
Jul 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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