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

Fix a bug caused by too long return expressions #1256

Merged
merged 12 commits into from Jun 1, 2022
16 changes: 15 additions & 1 deletion kotlinpoet/src/main/java/com/squareup/kotlinpoet/FunSpec.kt
Expand Up @@ -114,7 +114,7 @@ public class FunSpec private constructor(
} else if (!isEmptySetter) {
codeWriter.emitCode("·{\n")
codeWriter.indent()
codeWriter.emitCode(body, ensureTrailingNewline = true)
codeWriter.emitCode(body.returnsWithoutLinebreak(), ensureTrailingNewline = true)
codeWriter.unindent()
codeWriter.emit("}\n")
} else {
Expand Down Expand Up @@ -245,6 +245,20 @@ public class FunSpec private constructor(
return null
}

private fun CodeBlock.returnsWithoutLinebreak(): CodeBlock {
val returnWithSpace = RETURN_EXPRESSION_BODY_PREFIX_SPACE.formatParts[0]
val returnWithNbsp = RETURN_EXPRESSION_BODY_PREFIX_NBSP.formatParts[0]
var originCodeBlockBuilder: CodeBlock.Builder? = null
for ((i, formatPart) in formatParts.withIndex()) {
if (formatPart.startsWith(returnWithSpace)) {
val builder = originCodeBlockBuilder ?: toBuilder()
originCodeBlockBuilder = builder
builder.formatParts[i] = formatPart.replaceFirst(returnWithSpace, returnWithNbsp)
}
}
return originCodeBlockBuilder?.build() ?: this
}

override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null) return false
Expand Down
27 changes: 27 additions & 0 deletions kotlinpoet/src/test/java/com/squareup/kotlinpoet/FunSpecTest.kt
Expand Up @@ -206,6 +206,33 @@ class FunSpecTest {
)
}

@Test fun returnsLongExpression() {
val funSpec = FunSpec.builder("foo")
.returns(String::class)
.addStatement("val placeholder = 1")
.addStatement("return %S", "Loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong")
.build()
val sb = StringBuilder()
// The FunSpec#toString columnLimit is Integer.MAX_VALUE,
// It will not cause problems with returns long expressions.
CodeWriter(sb).use {
zsqw123 marked this conversation as resolved.
Show resolved Hide resolved
funSpec.emit(
codeWriter = it,
enclosingName = null,
implicitModifiers = setOf(KModifier.PUBLIC),
includeKdocTags = false
)
}
assertThat(sb.toString()).isEqualTo(
"""
|public fun foo(): kotlin.String {
| val placeholder = 1
| return "Loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"
|}
|""".trimMargin()
)
}

@Test fun functionParamWithKdoc() {
val funSpec = FunSpec.builder("foo")
.addParameter(
Expand Down