Skip to content

Function declaration with direct return and multiple statements throws IllegalStateException #1979

Open
@fourlastor

Description

@fourlastor

Describe the bug

I tried generating a function where there are multiple addStatement calls, the first of which is a return, but somehow the first opening statement symbol is lost when calling toString() on the function spec, and the generation fails with the following exception:

java.lang.IllegalStateException: Can't close a statement that hasn't been opened (closing » is not preceded by an
opening «).
Current code block:
- Format parts: [1, \n, », «, .plus(2), \n]
- Arguments: []

Note how the format parts are missing the initial «.

To Reproduce

  @Test fun returnExpressionMultipleStatements() {
    val spec = FunSpec.builder("three")
      .returns(INT)
      .addStatement("return 1")
      .addStatement(".plus(2)")
      .build()

    assertThat(spec.toString()).isEqualTo(
      """
      |public fun three(): kotlin.Int =
      | 1
      | .plus(2)
      """.trimIndent()
    )
  }

Note that this can be worked around changing addStatement to addCode for the first statement (the one containing the return), however this makes the indentation a bit confusing in the final result, also not having a return in the first statement would make this compile (on a Unit function, for example)

Expected behavior

The function is generated without throwing.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions