Skip to content
This repository has been 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

Open
fejesjoco opened this issue Jul 12, 2021 · 2 comments

Comments

@fejesjoco
Copy link

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.

@coderstory
Copy link

coderstory commented Jul 28, 2021

            .addStatement(
                "$T lambda = $L",
                ParameterizedTypeName.get(
                    ClassName.get(Supplier.class), ClassName.get(Integer.class)),
                inner**.toString()**)

@WangXiequn
Copy link

#884 I try to do it in this pull request.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants