Skip to content

#2 Lexer now fails for control chars in string #3

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

Merged
merged 1 commit into from
Sep 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/main/kotlin/lexer/StringJSONLexer.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package net.quickwrite.lexer

import net.quickwrite.JSONLexerException
import java.util.*
import kotlin.jvm.Throws

class StringJSONLexer(private val content: CharSequence) : JSONLexer {
Expand Down Expand Up @@ -93,6 +94,16 @@ class StringJSONLexer(private val content: CharSequence) : JSONLexer {
continue
}

if(content[position].code in 0x0000..0x001F) {
val hex = content[position].toHex()

throw JSONLexerException(
"The character '$hex' cannot be in a string. " +
"If this character should be in the string, then it should be escaped using '$hex'.",
getPosition(position)
)
}

builder.append(content[position])
position++
}
Expand All @@ -101,11 +112,33 @@ class StringJSONLexer(private val content: CharSequence) : JSONLexer {
throw JSONLexerException("String wasn't correctly terminated", getPosition(content.length - 1))
}

if(content[position].code == 0) {
throw JSONLexerException(
"The character '\\u0000' (Null character) cannot be in a string as it terminates it immediately. " +
"If this character should be in the string, then it should be escaped using '\\u0000'.",
getPosition(position)
)
}

position++

return JSONLexeme(JSONLexemeType.STRING, start, position - start, builder.toString())
}

private fun Char.toHex(): String {
return when(this) {
'\b' -> "\\b"
'\u000C' -> "\\f"
'\n' -> "\\n"
'\r' -> "\\r"
'\t' -> "\\t"
else -> {
val value = Integer.toHexString(this.code).uppercase(Locale.getDefault())
"\\u" + "0".repeat(4 - value.length) + value
}
}
}

private fun parseUDigitNumber(): Char {
var number = 0
val start = position
Expand Down
15 changes: 15 additions & 0 deletions src/test/kotlin/lexer/StringJSONLexerExceptionsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,19 @@ class StringJSONLexerExceptionsTest {
}
}
}

@Test
fun `string control characters test`() {
val inputs = arrayOfNulls<String>(0x001F)

for (i in inputs.indices) {
inputs[i] = "\"${i.toChar()}\""
}

inputs.forEach {
org.junit.jupiter.api.assertThrows<JSONLexerException> {
StringJSONLexer(it!!).getNext()
}
}
}
}
Loading