Skip to content
This repository was archived by the owner on Oct 10, 2024. It is now read-only.
This repository was archived by the owner on Oct 10, 2024. It is now read-only.

Assignment->lambda->statement fails with "statement enter $[ followed by statement enter $[" #848

@fejesjoco

Description

@fejesjoco

Repro sample:

  public static void main(String[] args) {
    CodeBlock inner =
        CodeBlock.builder()
            .beginControlFlow("() ->")
            .addStatement("return 42")
            .endControlFlow()
            .build();
    System.err.println("<<<" + inner + ">>>");
    CodeBlock outer1 =
        CodeBlock.builder()
            .add(
                "$T lambda = $L;",
                ParameterizedTypeName.get(
                    ClassName.get(Supplier.class), ClassName.get(Integer.class)),
                inner)
            .build();
    System.err.println("<<<" + outer1 + ">>>");
    CodeBlock outer2 =
        CodeBlock.builder()
            .addStatement(
                "$T lambda = $L",
                ParameterizedTypeName.get(
                    ClassName.get(Supplier.class), ClassName.get(Integer.class)),
                inner)
            .build();
    System.err.println("<<<" + outer2 + ">>>");
  }

The first two prints work, the third fails:

<<<() -> {
  return 42;
}
>>>
<<<java.util.function.Supplier<java.lang.Integer> lambda = () -> {
  return 42;
}
;>>>
Exception in thread "main" java.lang.IllegalStateException: statement enter $[ followed by statement enter $[
	at com.squareup.javapoet.Util.checkState(Util.java:62)
	at com.squareup.javapoet.CodeWriter.emit(CodeWriter.java:284)
	at com.squareup.javapoet.CodeWriter.emit(CodeWriter.java:229)
	at com.squareup.javapoet.CodeWriter.emitLiteral(CodeWriter.java:365)
	at com.squareup.javapoet.CodeWriter.emit(CodeWriter.java:240)
	at com.squareup.javapoet.CodeWriter.emit(CodeWriter.java:229)
	at com.squareup.javapoet.CodeBlock.toString(CodeBlock.java:97)
	at java.base/java.lang.String.valueOf(String.java:2958)

I think this should work, because the assignment is a statement, and because of the lambda syntax the rvalue can also contain statements. But it seems like Javapoet is confused by statements within each other.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions