fix json; v0.13

This commit is contained in:
alexander.nutz
2024-04-03 07:47:48 +02:00
parent 25086a3c7e
commit 469d5fcb8c
4 changed files with 46 additions and 5 deletions

View File

@@ -12,7 +12,7 @@ repositories {
} }
dependencies { dependencies {
implementation("me.alex_s168:blitz:0.12") implementation("me.alex_s168:blitz:0.13")
} }
``` ```

View File

@@ -5,7 +5,7 @@ plugins {
} }
group = "me.alex_s168" group = "me.alex_s168"
version = "0.12" version = "0.13"
repositories { repositories {
mavenCentral() mavenCentral()

View File

@@ -12,8 +12,8 @@ object JSON {
} }
val jsonString = parser { val jsonString = parser {
it.require("\"") it.stringWithEscape()
?.untilRequire("\"") { str -> Str(str) } ?.mapSecond { Str(it) }
} }
val jsonArray = parser { val jsonArray = parser {
@@ -30,6 +30,8 @@ object JSON {
val jsonBool = parser { it.require("true")?.to(Bool(true)) } or val jsonBool = parser { it.require("true")?.to(Bool(true)) } or
parser { it.require("false")?.to(Bool(false)) } parser { it.require("false")?.to(Bool(false)) }
val jsonNull = parser { it.require("null")?.to(Nul()) }
val jsonObj = parser { val jsonObj = parser {
it.require("{") it.require("{")
?.array(",") { elem -> ?.array(",") { elem ->
@@ -47,7 +49,7 @@ object JSON {
} }
init { init {
jsonElement = (jsonArray or jsonNum or jsonString or jsonObj or jsonBool).trim() jsonElement = (jsonArray or jsonNum or jsonString or jsonObj or jsonBool or jsonNull).trim()
} }
interface Element { interface Element {
@@ -62,6 +64,7 @@ object JSON {
fun isStr() = this is Str fun isStr() = this is Str
fun isObj() = this is Obj fun isObj() = this is Obj
fun isBool() = this is Bool fun isBool() = this is Bool
fun isNul() = this is Nul
} }
data class Array(val value: List<Element>): Element { data class Array(val value: List<Element>): Element {
@@ -90,6 +93,8 @@ object JSON {
value.toString() value.toString()
} }
class Nul: Element
fun parse(string: String): Element? = fun parse(string: String): Element? =
jsonElement(Parsable(string))?.second jsonElement(Parsable(string))?.second
} }

View File

@@ -0,0 +1,36 @@
package blitz.parse.comb
fun Parsable.stringWithEscape(): Pair<Parsable, String>? {
var escaped = false
var index = 0
val out = StringBuilder()
for (c in str) {
if (index == 0) {
if (c != '"')
return null
} else {
if (escaped) {
escaped = false
when (c) {
'"' -> out.append('"')
'\\' -> out.append('\\')
'n' -> out.append('\n')
'r' -> out.append('\r')
'b' -> out.append('\b')
't' -> out.append('\t')
else -> return null
}
} else if (c == '"')
break
else if (c == '\\')
escaped = true
else {
out.append(c)
}
}
index ++
}
if (escaped)
return null
return Parsable(str.substring(index + 1), loc?.plus(index + 1)) to out.toString()
}