Get RecordClass of tuple types

This commit is contained in:
Emery Hemingway 2021-07-01 12:48:07 +02:00
parent 2eda0fc9a7
commit 24d974b91f
2 changed files with 17 additions and 14 deletions

View File

@ -43,10 +43,14 @@ proc classOf*(val: Preserve): RecordClass =
RecordClass(label: val.label, arity: val.arity) RecordClass(label: val.label, arity: val.arity)
proc classOf*[T](x: T): RecordClass = proc classOf*[T](x: T): RecordClass =
## Derive the ``RecordClass`` of ``x``.
when not T.hasCustomPragma(record): {.error: "no {.record.} pragma on " & $T.}
result.label = preserves.symbol(T.getCustomPragmaVal(record))
for k, v in x.fieldPairs: inc(result.arity)
proc classOf*(T: typedesc[tuple]): RecordClass =
## Derive the ``RecordClass`` of ``T``. ## Derive the ``RecordClass`` of ``T``.
# TODO: would be nice to get the class of a type without an instance. when not T.hasCustomPragma(record): {.error: "no {.record.} pragma on " & $T.}
when not T.hasCustomPragma(record): RecordClass(
raise newException(Defect, "{.record: \"\".} must be present to determine classOf") label: preserves.symbol(T.getCustomPragmaVal(record)),
else: arity: tupleLen(T))
result.label = preserves.symbol(T.getCustomPragmaVal(record))
for k, v in x.fieldPairs: inc(result.arity)

View File

@ -5,30 +5,29 @@ import bigints, preserves, preserves/records
suite "conversions": suite "conversions":
test "dictionary": test "dictionary":
type Bar = tuple type Bar = object
s: string s: string
type Foobar = object type Foobar = tuple
a, b: int a, b: int
c: Bar c: Bar
let let
c = Foobar(a: 1, b: 2, c: (s: "ku",)) c: Foobar = (a: 1, b: 2, c: Bar(s: "ku",))
b = toPreserve(c) b = toPreserve(c)
a = preserveTo(b, Foobar) a = preserveTo(b, Foobar)
check(a == c) check(a == c)
check(b.kind == pkDictionary) check(b.kind == pkDictionary)
expect Defect:
checkpoint $classOf(c)
test "records": test "records":
type Bar {.record: "bar".} = tuple type Bar {.record: "bar".} = object
s: string s: string
type Foobar {.record: "foo".} = object type Foobar {.record: "foo".} = tuple
a, b: int a, b: int
c: Bar c: Bar
let let
c = Foobar(a: 1, b: 2, c: (s: "ku",)) c: Foobar = (a: 1, b: 2, c: Bar(s: "ku",))
b = toPreserve(c) b = toPreserve(c)
a = preserveTo(b, Foobar) a = preserveTo(b, Foobar)
check(a == c) check(a == c)
check(b.kind == pkRecord) check(b.kind == pkRecord)
check(classOf(c) == RecordClass(label: symbol"foo", arity: 3)) check(classOf(c) == RecordClass(label: symbol"foo", arity: 3))
check(classOf(Foobar) == RecordClass(label: symbol"foo", arity: 3))