# SPDX-FileCopyrightText: 2021 ☭ Emery Hemingway # SPDX-License-Identifier: Unlicense import bigints import std/[base64, endians, hashes, options, sets, sequtils, streams, tables, typetraits] from std/json import escapeJson, escapeJsonUnquoted from std/macros import hasCustomPragma, getCustomPragmaVal type PreserveKind* = enum pkBoolean, pkFloat, pkDouble, pkSignedInteger, pkBigInteger, pkString, pkByteString, pkSymbol, pkRecord, pkSequence, pkSet, pkDictionary const atomKinds* = {pkBoolean, pkFloat, pkDouble, pkSignedInteger, pkBigInteger, pkString, pkByteString, pkSymbol} compoundKinds* = {pkRecord, pkSequence, pkSet, pkDictionary} type DictEntry = tuple[key: Preserve, val: Preserve] Preserve* {.acyclic.} = object case kind*: PreserveKind of pkBoolean: bool*: bool of pkFloat: float*: float32 of pkDouble: double*: float64 of pkSignedInteger: int*: BiggestInt of pkBigInteger: bigint*: BigInt of pkString: string*: string of pkByteString: bytes*: seq[byte] of pkSymbol: symbol*: string of pkRecord: record*: seq[Preserve] # label is last of pkSequence: sequence*: seq[Preserve] of pkSet: set*: seq[Preserve] # TODO: HashSet of pkDictionary: dict*: seq[DictEntry] # TODO: Tables embedded*: bool proc `==`*(x, y: Preserve): bool = ## Check `x` and `y` for equivalence. if x.kind == y.kind and x.embedded == y.embedded: case x.kind of pkBoolean: result = x.bool == y.bool of pkFloat: result = x.float == y.float of pkDouble: result = x.double == y.double of pkSignedInteger: result = x.int == y.int of pkBigInteger: result = x.bigint == y.bigint of pkString: result = x.string == y.string of pkByteString: result = x.bytes == y.bytes of pkSymbol: result = x.symbol == y.symbol of pkRecord: result = x.record == y.record of pkSequence: for i, val in x.sequence: if y.sequence[i] != val: return false result = true of pkSet: result = x.set == y.set of pkDictionary: result = x.dict == y.dict proc `<`(x, y: string | seq[byte]): bool = for i in 0 .. min(x.high, y.high): if x[i] < y[i]: return true if x[i] != y[i]: return false x.len < y.len proc `<`*(x, y: Preserve): bool = ## Preserves have a total order over Values. Check if `x` is ordered before `y`. if x.embedded != y.embedded: result = y.embedded elif x.kind != y.kind: if x.kind == pkSignedInteger and y.kind == pkBigInteger: result = x.int.initBigInt < y.bigint elif x.kind == pkBigInteger and y.kind == pkSignedInteger: result = x.bigint < y.int.initBigInt else: result = x.kind < y.kind else: case x.kind of pkBoolean: result = (not x.bool) and y.bool of pkFloat: result = x.float < y.float of pkDouble: result = x.double < y.double of pkSignedInteger: result = x.int < y.int of pkBigInteger: result = x.bigint < y.bigint of pkString: result = x.string < y.string of pkByteString: result = x.bytes < y.bytes of pkSymbol: result = x.symbol < y.symbol of pkRecord: if x.record[x.record.high] < y.record[y.record.high]: return true for i in 0..") initRecord(symbol(label), args) proc initSequence*(len = 0): Preserve = ## Create a Preserves sequence value. Preserve(kind: pkSequence, record: newSeq[Preserve](len)) proc initSet*(): Preserve = Preserve(kind: pkSet) ## Create a Preserves set value. proc initDictionary*(): Preserve = Preserve(kind: pkDictionary) ## Create a Preserves dictionary value. proc len*(pr: Preserve): int = ## Return the shallow count of values in ``pr``, that is the number of ## fields in a record, items in a sequence, items in a set, or key-value pairs ## in a dictionary. case pr.kind of pkRecord: pr.record.len.pred of pkSequence: pr.sequence.len of pkSet: pr.set.len of pkDictionary: pr.dict.len else: 0 iterator items*(pr: Preserve): Preserve = ## Shallow iterator over `pr`, yield the fields in a record, ## the items of a sequence, the items of a set, or the pairs ## of a dictionary. case pr.kind of pkRecord: for i in 0..pr.record.high.pred: yield pr.record[i] of pkSequence: for e in pr.sequence.items: yield e of pkSet: for e in pr.set.items: yield e of pkDictionary: for (k, v) in pr.dict.items: yield k # key can be an arbitrary Preserve yield v else: discard func isBoolean*(pr: Preserve): bool {.inline.} = pr.kind == pkBoolean ## Check if ``pr`` is a Preserve boolean. func isFalse*(pr: Preserve): bool = ## Check if ``pr`` is equivalent to the zero-initialized ``Preserve``. pr.kind == pkBoolean and pr.bool == false func isFloat*(pr: Preserve): bool {.inline.} = pr.kind == pkFloat ## Check if ``pr`` is a Preserve float. func isDouble*(pr: Preserve): bool {.inline.} = pr.kind == pkDouble ## Check if ``pr`` is a Preserve double. func isInteger*(pr: Preserve): bool {.inline.} = pr.kind in {pkSignedInteger, pkBigInteger} ## Check if ``pr`` is a Preserve double. func isString*(pr: Preserve): bool {.inline.} = pr.kind == pkString ## Check if ``pr`` is a Preserve text string. func isByteString*(pr: Preserve): bool {.inline.} = pr.kind == pkByteString ## Check if ``pr`` is a Preserves byte string. func isSymbol*(pr: Preserve): bool {.inline.} = pr.kind == pkSymbol ## Check if `pr` is a Preserves symbol. func isSymbol*(pr: Preserve; sym: string): bool {.inline.} = ## Check if ``pr`` is a Preserves symbol of ``sym``. (pr.kind == pkSymbol) and (pr.symbol == sym) func isRecord*(pr: Preserve): bool {.inline.} = (pr.kind == pkRecord) and (pr.record.len > 0) ## Check if ``pr`` is a Preserves record. proc isSequence*(pr: Preserve): bool {.inline.} = pr.kind == pkSequence ## Check if ``pr`` is a Preserves sequence. proc isSet*(pr: Preserve): bool {.inline.} = pr.kind == pkSet ## Check if ``pr`` is a Preserves set. proc isDictionary*(pr: Preserve): bool {.inline.} = pr.kind == pkDictionary ## Check if ``pr`` is a Preserves dictionary. func isEmbedded*(pr: Preserve): bool {.inline.} = pr.embedded ## Check if ``pr`` is an embedded value. proc label*(pr: Preserve): Preserve {.inline.} = ## Return the label of record value. pr.record[pr.record.high] proc arity*(pr: Preserve): int {.inline.} = ## Return the number of fields in record `pr`. pred(pr.record.len) proc fields*(pr: Preserve): seq[Preserve] {.inline.} = ## Return the fields of a record value. pr.record[0..pr.record.high.pred] iterator fields*(pr: Preserve): Preserve = ## Iterate the fields of a record value. for i in 0.. 0: write(n.pred, i shr 8) str.write(i.uint8) write(byteCount, pr.int) of pkBigInteger: doAssert(Negative notin pr.bigint.flags, "negative big integers not implemented") var bytes = newSeqOfCap[uint8](pr.bigint.limbs.len * 4) var begun = false for i in countdown(pr.bigint.limbs.high, 0): let limb = pr.bigint.limbs[i] for j in countdown(24, 0, 8): let b = uint8(limb shr j) begun = begun or (b != 0) if begun: bytes.add(b) if bytes.len <= 16: str.write(0xa0'u8 or bytes.high.uint8) else: str.write(0xb0'u8) str.writeVarint(bytes.len) str.write(cast[string](bytes)) of pkString: str.write(0xb1'u8) str.writeVarint(pr.string.len) str.write(pr.string) of pkByteString: str.write(0xb2'u8) str.writeVarint(pr.bytes.len) str.write(cast[string](pr.bytes)) of pkSymbol: str.write(0xb3'u8) str.writeVarint(pr.symbol.len) str.write(pr.symbol) of pkRecord: assert(pr.record.len > 0) str.write(0xb4'u8) str.write(pr.record[pr.record.high]) for i in 0.. 0x9c: 0xa0 else: 0x90)) of 0xa0: let len = (tag.int and 0x0f) + 1 if len <= 8: result = Preserve(kind: pkSignedInteger, int: s.readUint8().BiggestInt) if (result.int and 0x80) != 0: result.int.dec(0x100) for i in 1.."""))) assert(foo.x == 1) assert(foo.y == 2) type Value = Preserve when T is Value: v = pr result = true elif compiles(fromPreserveHook(v, pr)): result = fromPreserveHook(v, pr) elif T is Bigint: case pr.kind of pkSignedInteger: v = initBigint(pr.int) result = true of pkBigInteger: v = pr.bigint result = true else: disard elif T is bool: if pr.kind == pkBoolean: v = pr.bool result = true elif T is SomeInteger: if pr.kind == pkSignedInteger: v = T(pr.int) result = true elif T is float: if pr.kind == pkFloat: v = pr.float result = true elif T is seq: if T is seq[byte] and pr.kind == pkByteString: v = pr.bytes result = true elif pr.kind == pkSequence: v.setLen(pr.len) result = true for i, e in pr.sequence: result = result and fromPreserve(v[i], e) elif T is float64: case pr.kind of pkFloat: v = pr.float result = true of pkDouble: v = pr.double result = true elif T is object | tuple: case pr.kind of pkRecord: when T.hasCustomPragma(record): if pr.record[pr.record.high].isSymbol T.getCustomPragmaVal(record): result = true var i = 0 for fname, field in v.fieldPairs: if not result or (i == pr.record.high): break result = result and fromPreserve(field, pr.record[i]) inc(i) result = result and (i == pr.record.high) # arity equivalence check= of pkDictionary: result = true var fieldCount = 0 for key, val in v.fieldPairs: inc fieldCount for (pk, pv) in pr.dict.items: var sym = symbol(key) if sym == pk: result = result and fromPreserve(val, pv) break result = result and pr.dict.len == fieldCount else: discard elif T is Ordinal | SomeInteger: if pr.kind == pkSignedInteger: v = (T)pr.int result = true elif T is ref: if pr != symbol("null"): new v result = fromPreserve(v[], pr) elif T is string: if pr.kind == pkString: v = pr.string result = true elif T is distinct: result = fromPreserve(result.distinctBase, pr) else: raiseAssert("no conversion of type Preserve to " & $T) if not result: reset v proc preserveTo*(pr: Preserve; T: typedesc): Option[T] = ## Reverse of `toPreserve`. ## # TODO: {.raises: [].} runnableExamples: import std/options, preserves, preserves/parse type Foo {.record: "foo".} = object x, y: int assert(parsePreserves("""""").preserveTo(Foo).isNone) assert(parsePreserves("""""").preserveTo(Foo).isNone) assert(parsePreserves("""""").preserveTo(Foo).isSome) var v: T if fromPreserve(v, pr): result = some(move v) proc fromPreserveHook*[A,B,E](t: var Table[A,B]|TableRef[A,B]; pr: Preserve): bool = if pr.isDictionary: for k, v in pr.pairs: t[preserveTo(k, A)] = preserveTo(v, B) result = true proc concat(result: var string; pr: Preserve) = if pr.embedded: result.add("#!") case pr.kind: of pkBoolean: case pr.bool of false: result.add "#f" of true: result.add "#t" of pkFloat: result.add($pr.float & "f") of pkDouble: result.add $pr.double of pkSignedInteger: result.add $pr.int of pkBigInteger: result.add $pr.bigint of pkString: result.add escapeJson(pr.string) of pkByteString: for b in pr.bytes: if b.char notin {'\20'..'\21', '#'..'[', ']'..'~'}: result.add("#[") #]# result.add(base64.encode(pr.bytes)) result.add(']') return result.add("#\"") result.add(cast[string](pr.bytes)) result.add('"') of pkSymbol: result.add(escapeJsonUnquoted(pr.symbol)) of pkRecord: assert(pr.record.len > 0) result.add('<') result.concat(pr.record[pr.record.high]) for i in 0..') of pkSequence: result.add('[') for i, val in pr.sequence: if i > 0: result.add(' ') result.concat(val) result.add(']') of pkSet: result.add("#{") for val in pr.set.items: result.concat(val) result.add(' ') if pr.set.len > 1: result.setLen(result.high) result.add('}') of pkDictionary: result.add('{') var i = 0 for (key, value) in pr.dict.items: if i > 0: result.add(' ') result.concat(key) result.add(": ") result.concat(value) inc i result.add('}') proc `$`*(pr: Preserve): string = concat(result, pr) ## Generate the textual representation of ``pr``.