mirror of
https://github.com/GayPizzaSpecifications/pork.git
synced 2025-08-02 12:50:55 +00:00
Optional whitespace preservation.
This commit is contained in:
parent
903f730d51
commit
77a9136be7
19
src/main/kotlin/gay/pizza/pork/parse/Highlighter.kt
Normal file
19
src/main/kotlin/gay/pizza/pork/parse/Highlighter.kt
Normal file
@ -0,0 +1,19 @@
|
||||
package gay.pizza.pork.parse
|
||||
|
||||
abstract class Highlighter(source: TokenSource) : TokenProcessor(source) {
|
||||
override fun process(token: Token) {
|
||||
when {
|
||||
token.type.keyword != null -> {
|
||||
keyword(token)
|
||||
}
|
||||
token.type == TokenType.Symbol -> {
|
||||
symbol(token)
|
||||
}
|
||||
else -> other(token)
|
||||
}
|
||||
}
|
||||
|
||||
abstract fun keyword(token: Token)
|
||||
abstract fun symbol(token: Token)
|
||||
abstract fun other(token: Token)
|
||||
}
|
@ -1,6 +1,6 @@
|
||||
package gay.pizza.pork.parse
|
||||
|
||||
class PorkTokenizer(val source: CharSource) {
|
||||
class PorkTokenizer(val source: CharSource, val preserveWhitespace: Boolean = false) {
|
||||
private var tokenStart: Int = 0
|
||||
|
||||
private fun isSymbol(c: Char): Boolean =
|
||||
@ -40,10 +40,14 @@ class PorkTokenizer(val source: CharSource) {
|
||||
return Token(TokenType.IntLiteral, number)
|
||||
}
|
||||
|
||||
private fun skipWhitespace() {
|
||||
while (isWhitespace(source.peek())) {
|
||||
source.next()
|
||||
private fun readWhitespace(): Token {
|
||||
val whitespace = buildString {
|
||||
while (isWhitespace(source.peek())) {
|
||||
val char = source.next()
|
||||
append(char)
|
||||
}
|
||||
}
|
||||
return Token(TokenType.Whitespace, whitespace)
|
||||
}
|
||||
|
||||
fun next(): Token {
|
||||
@ -57,7 +61,10 @@ class PorkTokenizer(val source: CharSource) {
|
||||
}
|
||||
|
||||
if (isWhitespace(char)) {
|
||||
skipWhitespace()
|
||||
val whitespace = readWhitespace()
|
||||
if (preserveWhitespace) {
|
||||
return whitespace
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
|
15
src/main/kotlin/gay/pizza/pork/parse/TokenProcessor.kt
Normal file
15
src/main/kotlin/gay/pizza/pork/parse/TokenProcessor.kt
Normal file
@ -0,0 +1,15 @@
|
||||
package gay.pizza.pork.parse
|
||||
|
||||
abstract class TokenProcessor(val source: TokenSource) {
|
||||
fun processAll() {
|
||||
while (true) {
|
||||
val token = source.next()
|
||||
process(token)
|
||||
if (token.type == TokenType.EndOfFile) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
abstract fun process(token: Token)
|
||||
}
|
@ -21,6 +21,7 @@ enum class TokenType(val char: Char? = null, val keyword: String? = null) {
|
||||
If(keyword = "if"),
|
||||
Then(keyword = "then"),
|
||||
Else(keyword = "else"),
|
||||
Whitespace,
|
||||
EndOfFile;
|
||||
|
||||
companion object {
|
||||
|
Loading…
Reference in New Issue
Block a user