-
Notifications
You must be signed in to change notification settings - Fork 123
/
Lexer.kt
216 lines (187 loc) · 7.17 KB
/
Lexer.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package com.beust.klaxon
import com.beust.klaxon.token.*
import java.io.Reader
import java.util.regex.Pattern
/**
* if `lenient` is true, names (the identifiers left of the colon) are allowed to not be surrounded by double quotes.
*/
class Lexer(passedReader: Reader, val lenient: Boolean = false): Iterator<Token> {
var index = 0
var line = 1
private val NUMERIC = Pattern.compile("[-]?[0-9]+")
private val DOUBLE = Pattern.compile(NUMERIC.toString() + "((\\.[0-9]+)?([eE][-+]?[0-9]+)?)")!!
private fun isSpace(c: Char): Boolean {
if (c == '\n') line++
return c == ' ' || c == '\r' || c == '\n' || c == '\t'
}
private val reader = passedReader.buffered()
private var next: Char?
private val isDone: Boolean
get() = next == null
init {
val c = reader.read()
next = if (c == -1) null else c.toChar()
}
private fun nextChar(): Char {
if (isDone) throw IllegalStateException("Cannot get next char: EOF reached")
val c = next!!
next = reader.read().let { if (it == -1) null else it.toChar() }
index++
// log("Next char: '$c' index:$index")
return c
}
private fun peekChar() : Char {
if (isDone) throw IllegalStateException("Cannot peek next char: EOF reached")
return next!!
}
val BOOLEAN_LETTERS = "falsetrue".toSet()
private fun isBooleanLetter(c: Char) : Boolean {
return BOOLEAN_LETTERS.contains(Character.toLowerCase(c))
}
val NULL_LETTERS = "null".toSet()
fun isValueLetter(c: Char) : Boolean {
return c == '-' || c == '+' || c == '.' || c.isDigit() || isBooleanLetter(c)
|| c in NULL_LETTERS
}
private var peeked: Token? = null
fun peek() : Token {
peeked = peeked ?: actualNextToken()
return peeked!!
}
override fun next() = nextToken()
override fun hasNext() = peek() !is EOF
fun nextToken(): Token {
return peeked?.also { peeked = null } ?: actualNextToken()
}
private var expectName = false
private fun actualNextToken() : Token {
if (isDone) {
return EOF
}
val token: Token
var c = nextChar()
val currentValue = StringBuilder()
while (!isDone && isSpace(c)) {
c = nextChar()
}
if ('"' == c || (lenient && expectName)) {
if (lenient) {
currentValue.append(c)
}
loop@
do {
if (isDone) {
throw KlaxonException("Unterminated string")
}
c = if (lenient) peekChar() else nextChar()
when (c) {
'\\' -> {
if (isDone) {
throw KlaxonException("Unterminated string")
}
c = nextChar()
when (c) {
'\\' -> currentValue.append("\\")
'/' -> currentValue.append("/")
'b' -> currentValue.append("\b")
'f' -> currentValue.append("\u000c")
'n' -> {
currentValue.append("\n")
line++
}
'r' -> currentValue.append("\r")
't' -> currentValue.append("\t")
'u' -> {
val unicodeChar = StringBuilder(4)
try {
unicodeChar
.append(nextChar())
.append(nextChar())
.append(nextChar())
.append(nextChar())
} catch(_: IllegalStateException) {
throw KlaxonException("EOF reached in unicode char after: u$unicodeChar")
}
val intValue = try {
java.lang.Integer.parseInt(unicodeChar.toString(), 16)
} catch(e: NumberFormatException) {
throw KlaxonException("Failed to parse unicode char: u$unicodeChar")
}
currentValue.append(intValue.toChar())
}
else -> currentValue.append(c)
}
}
'"' -> break@loop
else ->
if (lenient) {
if (! c.isJavaIdentifierPart()) {
expectName = false
break@loop
} else {
currentValue.append(c)
nextChar()
}
} else {
currentValue.append(c)
}
}
} while (true)
token = Value(currentValue.toString())
} else if ('{' == c) {
token = LEFT_BRACE
expectName = true
} else if ('}' == c) {
token = RIGHT_BRACE
expectName = false
} else if ('[' == c) {
token = LEFT_BRACKET
expectName = false
} else if (']' == c) {
token = RIGHT_BRACKET
expectName = false
} else if (':' == c) {
token = COLON
expectName = false
} else if (',' == c) {
token = COMMA
expectName = true
} else if (!isDone) {
while (isValueLetter(c)) {
currentValue.append(c)
if (isDone || !isValueLetter(peekChar())) {
break
} else {
c = nextChar()
}
}
val v = currentValue.toString()
if (NUMERIC.matcher(v).matches()) {
token = try {
Value(java.lang.Integer.parseInt(v))
} catch (e: NumberFormatException){
try {
Value(java.lang.Long.parseLong(v))
} catch(e: NumberFormatException) {
Value(java.math.BigInteger(v))
}
}
} else if (DOUBLE.matcher(v).matches()) {
token = Value(java.lang.Double.parseDouble(v))
} else if ("true" == v.toLowerCase()) {
token = Value(true)
} else if ("false" == v.toLowerCase()) {
token = Value(false)
} else if (v == "null") {
token = Value(null)
} else {
throw KlaxonException("Unexpected character at position ${index-1}"
+ ": '$c' (ASCII: ${c.toInt()})'")
}
} else {
token = EOF
}
return token
}
private fun log(s: String) { if (Debug.verbose) println(s) }
}