Skip to content

Commit

Permalink
fix json; v0.13
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander.nutz committed Apr 3, 2024
1 parent 25086a3 commit 469d5fc
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 5 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ repositories {
}

dependencies {
implementation("me.alex_s168:blitz:0.12")
implementation("me.alex_s168:blitz:0.13")
}
```

Expand Down
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ plugins {
}

group = "me.alex_s168"
version = "0.12"
version = "0.13"

repositories {
mavenCentral()
Expand Down
11 changes: 8 additions & 3 deletions src/main/kotlin/blitz/parse/JSON.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ object JSON {
}

val jsonString = parser {
it.require("\"")
?.untilRequire("\"") { str -> Str(str) }
it.stringWithEscape()
?.mapSecond { Str(it) }
}

val jsonArray = parser {
Expand All @@ -30,6 +30,8 @@ object JSON {
val jsonBool = parser { it.require("true")?.to(Bool(true)) } or
parser { it.require("false")?.to(Bool(false)) }

val jsonNull = parser { it.require("null")?.to(Nul()) }

val jsonObj = parser {
it.require("{")
?.array(",") { elem ->
Expand All @@ -47,7 +49,7 @@ object JSON {
}

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 {
Expand All @@ -62,6 +64,7 @@ object JSON {
fun isStr() = this is Str
fun isObj() = this is Obj
fun isBool() = this is Bool
fun isNul() = this is Nul
}

data class Array(val value: List<Element>): Element {
Expand Down Expand Up @@ -90,6 +93,8 @@ object JSON {
value.toString()
}

class Nul: Element

fun parse(string: String): Element? =
jsonElement(Parsable(string))?.second
}
36 changes: 36 additions & 0 deletions src/main/kotlin/blitz/parse/comb/Special.kt
Original file line number Diff line number Diff line change
@@ -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()
}

0 comments on commit 469d5fc

Please sign in to comment.