Skip to content

Commit

Permalink
Report an error on unclosed comments
Browse files Browse the repository at this point in the history
Otherwise formatting succeeds and moves all subsequent code into the comment too. This is especially bad for nested comments, which have a surprising syntax.
  • Loading branch information
nreid260 committed Nov 7, 2024
1 parent 3f10f99 commit 4a730f7
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
5 changes: 5 additions & 0 deletions core/src/main/java/com/facebook/ktfmt/format/Tokenizer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.facebook.ktfmt.format

import java.util.regex.Pattern
import org.jetbrains.kotlin.com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.com.intellij.psi.PsiComment
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
Expand Down Expand Up @@ -53,6 +54,10 @@ class Tokenizer(private val fileText: String, val file: KtFile) : KtTreeVisitorV
val originalText = fileText.substring(startIndex, endIndex)
when (element) {
is PsiComment -> {
if (element.text.startsWith("/*") && !element.text.endsWith("*/")) {
throw ParseError(
"Unclosed comment", StringUtil.offsetToLineColumn(fileText, element.startOffset))
}
toks.add(
KotlinTok(
index = index,
Expand Down
60 changes: 60 additions & 0 deletions core/src/test/java/com/facebook/ktfmt/format/TokenizerTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.facebook.ktfmt.format

import com.google.common.truth.Truth.assertThat
import kotlin.test.assertFailsWith
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
Expand Down Expand Up @@ -218,4 +219,63 @@ class TokenizerTest {
23)
.inOrder()
}

@Test
fun `Unclosed comment obvious`() {
assertParseError(
"""
|package a.b
|/*
|class A {}
|"""
.trimMargin(),
"2:1: error: Unclosed comment")
}

@Test
fun `Unclosed comment too short`() {
assertParseError(
"""
|package a.b
|/*/
|class A {}
|"""
.trimMargin(),
"2:1: error: Unclosed comment")
}

@Test
fun `Unclosed comment nested`() {
assertParseError(
"""
|package a.b
|/* /* */
|class A {}
|"""
.trimMargin(),
"2:1: error: Unclosed comment")
}

@Test
fun `Unclosed comment nested EOF`() {
// TODO: https://youtrack.jetbrains.com/issue/KT-72887 - This should be an error.
assertParseError(
"""
|package a.b
|class A {}
|/* /* */"""
.trimMargin(),
null)
}

private fun assertParseError(code: String, message: String?) {
val file = Parser.parse(code)
val tokenizer = Tokenizer(code, file)
if (message == null) {
file.accept(tokenizer)
} else {
val e = assertFailsWith<ParseError> { file.accept(tokenizer) }
assertThat(e).hasMessageThat().isEqualTo(message)
}
}
}

0 comments on commit 4a730f7

Please sign in to comment.