Handle function type params of the form @Annotation (<lambda>) (#189)

Summary:
This fixes https://github.com/facebookincubator/ktfmt/issues/186

Pull Request resolved: https://github.com/facebookincubator/ktfmt/pull/189

Test Plan:
1. buck test ktfmt_tests
2. ktfmt_diff came up empty

Reviewed By: hick209

Differential Revision: D26983065

Pulled By: cgrushko

fbshipit-source-id: a321dcd84dd84efb4c58fcb2bd76f90e3413cb26
diff --git a/core/src/main/java/com/facebook/ktfmt/KotlinInputAstVisitorBase.kt b/core/src/main/java/com/facebook/ktfmt/KotlinInputAstVisitorBase.kt
index a6db630..927ab40 100644
--- a/core/src/main/java/com/facebook/ktfmt/KotlinInputAstVisitorBase.kt
+++ b/core/src/main/java/com/facebook/ktfmt/KotlinInputAstVisitorBase.kt
@@ -173,14 +173,24 @@
   /** Example `Int`, `(String)` or `() -> Int` */
   override fun visitTypeReference(typeReference: KtTypeReference) {
     builder.sync(typeReference)
-    val hasParentheses = typeReference.hasParentheses()
-    if (hasParentheses) {
-      builder.token("(")
-    }
-    typeReference.modifierList?.accept(this)
-    typeReference.typeElement?.accept(this)
-    if (hasParentheses) {
-      builder.token(")")
+    // Normally we'd visit the children nodes through accessors on 'typeReference', and  we wouldn't
+    // loop over children.
+    // But, in this case the modifier list can either be inside the parenthesis:
+    // ... (@Composable (x) -> Unit)
+    // or outside of them:
+    // ... @Composable ((x) -> Unit)
+    val modifierList = typeReference.modifierList
+    val typeElement = typeReference.typeElement
+    for (child in typeReference.node.children()) {
+      if (child.psi == modifierList) {
+        modifierList?.accept(this)
+      } else if (child.psi == typeElement) {
+        typeElement?.accept(this)
+      } else if (child.elementType == KtTokens.LPAR) {
+        builder.token("(")
+      } else if (child.elementType == KtTokens.RPAR) {
+        builder.token(")")
+      }
     }
   }
 
diff --git a/core/src/test/java/com/facebook/ktfmt/FormatterKtTest.kt b/core/src/test/java/com/facebook/ktfmt/FormatterKtTest.kt
index c37a37d..39c7d90 100644
--- a/core/src/test/java/com/facebook/ktfmt/FormatterKtTest.kt
+++ b/core/src/test/java/com/facebook/ktfmt/FormatterKtTest.kt
@@ -3531,6 +3531,29 @@
       |""".trimMargin())
 
   @Test
+  fun `annotations on function types`() =
+      assertFormatted(
+          """
+      |fun foo(bar: @StringRes Int) {}
+      |
+      |fun foo(error: @Composable ((x) -> Unit)) {}
+      |
+      |fun foo(error: (@Composable (x) -> Unit)) {}
+      |
+      |fun foo(
+      |    error:
+      |        @field:[Inject Named("WEB_VIEW")]
+      |        ((x) -> Unit)
+      |) {}
+      |
+      |fun foo(
+      |    error:
+      |        (@field:[Inject Named("WEB_VIEW")]
+      |        (x) -> Unit)
+      |) {}
+      |""".trimMargin())
+
+  @Test
   fun `handle annotations with use-site targets`() =
       assertFormatted(
           """