This repository has been archived by the owner on Jul 8, 2022. It is now read-only.
/
StrReader.kt
322 lines (276 loc) · 9.44 KB
/
StrReader.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package com.soywiz.korio.util
import com.soywiz.kds.iterators.*
import com.soywiz.korio.lang.*
import kotlin.collections.List
import kotlin.collections.MutableMap
import kotlin.collections.arrayListOf
import kotlin.collections.distinct
import kotlin.collections.joinToString
import kotlin.collections.linkedMapOf
import kotlin.collections.map
import kotlin.collections.reversed
import kotlin.collections.set
import kotlin.collections.sorted
import kotlin.collections.toCollection
import kotlin.collections.toList
import kotlin.collections.toTypedArray
import kotlin.math.*
class StrReader(val str: String, val file: String = "file", var pos: Int = 0) {
companion object {
fun literals(vararg lits: String): Literals = Literals.fromList(lits.toList().toTypedArray())
}
val length: Int = this.str.length
val available: Int get() = length - this.pos
val eof: Boolean get() = (this.pos >= this.str.length)
val hasMore: Boolean get() = (this.pos < this.str.length)
fun reset() = run { this.pos = 0 }
fun createRange(range: IntRange): TRange = createRange(range.start, range.endInclusive + 1)
fun createRange(start: Int = this.pos, end: Int = this.pos): TRange = TRange(start, end, this)
fun readRange(length: Int): TRange {
val range = TRange(this.pos, this.pos + length, this)
this.pos += length
return range
}
inline fun slice(action: () -> Unit): String? {
val start = this.pos
action()
val end = this.pos
return if (end > start) this.slice(start, end) else null
}
fun slice(start: Int, end: Int): String = this.str.substring(start, end)
fun peek(count: Int): String = substr(this.pos, count)
fun peek(): Char = if (hasMore) this.str[this.pos] else '\u0000'
fun peekChar(): Char = if (hasMore) this.str[this.pos] else '\u0000'
fun read(count: Int): String = this.peek(count).apply { skip(count) }
fun skipUntil(char: Char) {
val skipPos = this.str.indexOf(char, pos)
pos = (if (skipPos >= 0) skipPos else length)
}
fun skipUntilIncluded(char: Char) {
skipUntil(char)
if (!eof && peekChar() == char) skip(1)
}
//inline fun skipWhile(check: (Char) -> Boolean) = run { while (check(this.peekChar())) this.skip(1) }
inline fun skipWhile(filter: (Char) -> Boolean) = run { while (hasMore && filter(this.peekChar())) this.readChar() }
inline fun skipUntil(filter: (Char) -> Boolean) =
run { while (hasMore && !filter(this.peekChar())) this.readChar() }
inline fun matchWhile(check: (Char) -> Boolean): String? = slice { skipWhile(check) }
fun readUntil(char: Char) = this.slice { skipUntil(char) }
fun readUntilIncluded(char: Char) = this.slice { skipUntilIncluded(char) }
inline fun readWhile(filter: (Char) -> Boolean) = this.slice { skipWhile(filter) } ?: ""
inline fun readUntil(filter: (Char) -> Boolean) = this.slice { skipUntil(filter) } ?: ""
fun unread(count: Int = 1) = this.apply { this.pos -= count; }
fun readChar(): Char = if (hasMore) this.str[posSkip(1)] else '\u0000'
fun read(): Char = if (hasMore) this.str[posSkip(1)] else '\u0000'
// @TODO: https://youtrack.jetbrains.com/issue/KT-29577
private fun posSkip(count: Int): Int {
val out = this.pos
this.pos += count
return out
}
fun readRemaining(): String = read(available)
fun readExpect(expected: String): String {
val readed = this.read(expected.length)
if (readed != expected) throw IllegalArgumentException("Expected '$expected' but found '$readed' at $pos")
return readed
}
fun skipExpect(expected: Char) {
val readed = this.readChar()
if (readed != expected) throw IllegalArgumentException("Expected '$expected' but found '$readed' at $pos")
}
fun expect(expected: Char) = readExpect("$expected")
fun skip(count: Int = 1) = this.apply { this.pos += count; }
private fun substr(pos: Int, length: Int): String {
return this.str.substring(min(pos, this.length), min(pos + length, this.length))
}
fun tryLit(lit: String): String? {
if (substr(this.pos, lit.length) != lit) return null
this.pos += lit.length
return lit
}
fun tryLitRange(lit: String): TRange? =
if (substr(this.pos, lit.length) == lit) this.readRange(lit.length) else null
fun matchLit(lit: String): String? = tryLit(lit)
fun matchLitRange(lit: String): TRange? = tryLitRange(lit)
fun matchLitListRange(lits: Literals): TRange? {
lits.lengths.fastForEach { len ->
if (lits.contains(substr(this.pos, len))) return this.readRange(len)
}
return null
}
fun skipSpaces() = this.apply { this.skipWhile { it.isWhitespaceFast() } }
fun matchIdentifier() = matchWhile { it.isLetterDigitOrUnderscore() || it == '-' || it == '~' || it == ':' }
fun matchSingleOrDoubleQuoteString(): String? {
return when (this.peekChar()) {
'\'', '"' -> {
this.slice {
val quoteType = this.readChar()
this.readUntil(quoteType)
this.readChar()
}
}
else -> null
}
}
fun tryRegex(v: Regex): String? {
val result = v.find(this.str.substring(this.pos)) ?: return null
val m = result.groups[0]!!.value
this.pos += m.length
return m
}
fun tryRegexRange(v: Regex): TRange? {
val result = v.find(this.str.substring(this.pos)) ?: return null
return this.readRange(result.groups[0]!!.value.length)
}
fun matchStartEnd(start: String, end: String): String? {
if (substr(this.pos, start.length) != start) return null
val startIndex = this.pos
val index = this.str.indexOf(end, this.pos)
if (index < 0) return null
//trace(index);
this.pos = index + end.length
return this.slice(startIndex, this.pos)
}
fun clone(): StrReader = StrReader(str, file, pos)
fun tryRead(str: String): Boolean {
if (peek(str.length) == str) {
skip(str.length)
return true
}
return false
}
class Literals(
private val lits: Array<String>,
private val map: MutableMap<String, Boolean>,
val lengths: Array<Int>
) {
companion object {
fun invoke(vararg lits: String): Literals =
fromList(lits.toCollection(arrayListOf<String>()).toTypedArray())
//fun invoke(lits:Array<String>): Literals = fromList(lits)
fun fromList(lits: Array<String>): Literals {
val lengths = lits.map { it.length }.sorted().reversed().distinct().toTypedArray()
val map = linkedMapOf<String, Boolean>()
lits.fastForEach { lit ->
map[lit] = true
}
return Literals(lits, map, lengths)
}
}
fun contains(lit: String) = map.containsKey(lit)
fun matchAt(str: String, offset: Int): String? {
lengths.fastForEach { len ->
val id = str.substr(offset, len)
if (contains(id)) return id
}
return null
}
override fun toString() = "Literals(${lits.joinToString(" ")})"
}
class TRange(val min: Int, val max: Int, val reader: StrReader) {
companion object {
fun combine(a: TRange, b: TRange): TRange {
return TRange(min(a.min, b.min), max(a.max, b.max), a.reader)
}
fun combineList(list: List<TRange>): TRange? {
if (list.isEmpty()) return null
val first = list[0]
var min = first.min
var max = first.max
list.fastForEach { i ->
min = min(min, i.min)
max = max(max, i.max)
}
return TRange(min, max, first.reader)
}
fun createDummy() = TRange(0, 0, StrReader(""))
}
fun contains(index: Int): Boolean = index >= this.min && index <= this.max
override fun toString() = "$min:$max"
val file: String get() = this.reader.file
val text: String get () = this.reader.slice(this.min, this.max)
fun startEmptyRange(): TRange = TRange(this.min, this.min, this.reader)
fun endEmptyRange(): TRange = TRange(this.max, this.max, this.reader)
fun displace(offset: Int): TRange = TRange(this.min + offset, this.max + offset, this.reader)
}
fun readStringLit(reportErrors: Boolean = true): String {
val out = StringBuilder()
val quotec = read()
when (quotec) {
'"', '\'' -> Unit
else -> invalidOp("Invalid string literal")
}
var closed = false
while (hasMore) {
val c = read()
if (c == '\\') {
val cc = read()
out.append(
when (cc) {
'\\' -> '\\'; '/' -> '/'; '\'' -> '\''; '"' -> '"'
'b' -> '\b'; 'f' -> '\u000c'; 'n' -> '\n'; 'r' -> '\r'; 't' -> '\t'
'u' -> read(4).toInt(0x10).toChar()
else -> throw IOException("Invalid char '$cc'")
}
)
} else if (c == quotec) {
closed = true
break
} else {
out.append(c)
}
}
if (!closed && reportErrors) {
throw RuntimeException("String literal not closed! '${this.str}'")
}
return out.toString()
}
fun tryReadInt(default: Int): Int {
var digitCount = 0
var integral = 0
var mult = 1
loop@ while (!eof) {
when (val c = peek()) {
'-' -> {
skip(1)
mult *= -1
}
in '0'..'9' -> {
val digit = c - '0'
skip(1)
digitCount++
integral *= 10
integral += digit
}
else -> {
break@loop
}
}
}
return if (digitCount == 0) default else integral
}
fun tryReadNumber(default: Double = Double.NaN): Double {
val start = pos
skipWhile {
@Suppress("ConvertTwoComparisonsToRangeCheck")
(it >= '0' && it <= '9') || (it == '+') || (it == '-') || (it == 'e') || (it == 'E') || (it == '.')
}
val end = pos
if (end == start) return default
return NumberParser.parseDouble(this.str, start, end)
}
fun tryExpect(str: String): Boolean {
for (n in 0 until str.length) {
if (this.peekOffset(n) != str[n]) return false
}
skip(str.length)
return true
}
fun tryExpect(str: Char): Boolean {
if (peekChar() != str) return false
skip(1)
return true
}
fun peekOffset(offset: Int = 0): Char = this.str.getOrElse(pos + offset) { '\u0000' }
}
fun String.reader(file: String = "file", pos: Int = 0): StrReader = StrReader(this, file, pos)