matrix stuff

This commit is contained in:
alex-s168
2024-04-02 20:25:45 +02:00
parent 54dde5f1f7
commit 9a571a072d
4 changed files with 114 additions and 7 deletions

View File

@@ -4,15 +4,18 @@ import blitz.parse.comb.*
object JSON {
lateinit var jsonElement: Parser<Element>
val jsonNum = parser {
it.map(NumParse.float)?.mapSecond { n ->
Number(n)
}
}
val jsonString = parser {
it.require("\"")
?.untilRequire("\"") { str -> Str(str) }
}
val jsonArray = parser {
it.require("[")
?.array(",") { elem ->
@@ -23,6 +26,10 @@ object JSON {
?.require("]")
?.mapSecond { x -> Array(x) }
}
val jsonBool = parser { it.require("true")?.to(Bool(true)) } or
parser { it.require("false")?.to(Bool(false)) }
val jsonObj = parser {
it.require("{")
?.array(",") { elem ->
@@ -40,7 +47,7 @@ object JSON {
}
init {
jsonElement = (jsonArray or jsonNum or jsonString or jsonObj).trim()
jsonElement = (jsonArray or jsonNum or jsonString or jsonObj or jsonBool).trim()
}
interface Element {
@@ -48,11 +55,13 @@ object JSON {
val num get() = (this as Number).value
val str get() = (this as Str).value
val obj get() = (this as Obj).value
val bool get() = (this as Bool).value
fun isArr() = this is Array
fun isNum() = this is Number
fun isStr() = this is Str
fun isObj() = this is Obj
fun isBool() = this is Bool
}
data class Array(val value: List<Element>): Element {
@@ -75,6 +84,12 @@ object JSON {
value.map { (k, v) -> "\"$k\": $v" }.joinToString(separator = ", ", prefix = "{", postfix = "}")
}
data class Bool(val value: Boolean): Element {
override fun toString(): String =
value.toString()
}
fun parse(string: String): Element? =
jsonElement(Parsable(string))?.second
}