facebook / ktfmt

A program that reformats Kotlin source code to comply with the common community standard for Kotlin code conventions.
https://facebook.github.io/ktfmt/
Apache License 2.0
933 stars 78 forks source link

Crash when formatting JetpackCompose code #196

Closed bethcutler closed 3 years ago

bethcutler commented 3 years ago

For this sample code:

import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier

object FooBar {
  fun doFoo(): @Composable (Modifier) -> Unit {
    return { modifier -> println(modifier) }
  }
}

we get an error when formatting:

com.google.googlejavaformat.FormattingError: 6:28: error: expected token: 'Modifier'; generated ( instead

        at com.google.googlejavaformat.OpsBuilder.token(OpsBuilder.java:318)
        at com.facebook.ktfmt.KotlinInputAstVisitorBase.token(KotlinInputAstVisitorBase.kt:2218)
        at com.facebook.ktfmt.KotlinInputAstVisitorBase.token$default(KotlinInputAstVisitorBase.kt:2217)
        at com.facebook.ktfmt.KotlinInputAstVisitorBase.visitFunctionType(KotlinInputAstVisitorBase.kt:2007)
        at org.jetbrains.kotlin.psi.KtVisitorVoid.visitFunctionType(KtVisitorVoid.java:941)
        at org.jetbrains.kotlin.psi.KtVisitorVoid.visitFunctionType(KtVisitorVoid.java:21)
        at org.jetbrains.kotlin.psi.KtFunctionType.accept(KtFunctionType.java:64)
        at org.jetbrains.kotlin.psi.KtElementImplStub.accept(KtElementImplStub.java:60)
        at com.facebook.ktfmt.KotlinInputAstVisitorBase.visitTypeReference(KotlinInputAstVisitorBase.kt:181)
    ...

I have not found a workaround for this issue, and this pattern occurs in a handful of files... so it's a high priority for us.

JavierSegoviaCordoba commented 3 years ago

I haven't played a lot with Compose, but that is not the same as this?

object FooBar {

  @Composable
  fun DoFoo(): (Modifier) -> Unit {
    return { modifier -> println(modifier) }
  }
}
bethcutler commented 3 years ago

I don't know much about Compose either, but I am told that those two locations for the annotation have different meanings.

In any case, this is valid Kotlin code, so the formatter should be able to handle it gracefully.

cgrushko commented 3 years ago

@bethcutler I believe this is a duplicate of https://github.com/facebookincubator/ktfmt/issues/186, fixed in https://github.com/facebookincubator/ktfmt/commit/f6c762acef72cd6e291926474925560d95c1038a and released in https://github.com/facebookincubator/ktfmt/releases/tag/v0.22.

The provided example seems to be working for me, can you give 0.22 a try?