Add {.unpreservable.} pragma

This commit is contained in:
Emery Hemingway 2021-07-01 12:47:30 +02:00
parent 7b8d48c48a
commit 2eda0fc9a7
1 changed files with 6 additions and 5 deletions

View File

@ -1,7 +1,7 @@
# SPDX-License-Identifier: ISC
import bigints
import std/[base64, endians, json, hashes, macros, sets, streams, tables]
import std/[base64, endians, json, hashes, macros, sets, streams, tables, typetraits]
type
@ -245,9 +245,6 @@ iterator fields*(prs: Preserve): Preserve =
## Iterate the fields of a record value.
for i in 0..<prs.record.high: yield prs.record[i]
proc distinctBase(T: typedesc): typedesc {.magic: "TypeTrait".}
template distinctBase[T](a: T): untyped = distinctBase(type(a))(a)
proc symbol*(s: string): Preserve {.inline.} =
## Symbol constructor.
Preserve(kind: pkSymbol, symbol: s)
@ -463,6 +460,9 @@ template record*(label: string) {.pragma.}
## # <foobar 1 2>
## ```
template unpreservable*() {.pragma.}
## Pragma to forbid a type from being converted by `toPreserve`.
proc toPreserve*[T](x: T): Preserve =
## Serializes `x` to Preserves; uses `toPreserveHook(x: A)` if it's in scope to
## customize serialization.
@ -483,7 +483,8 @@ proc toPreserve*[T](x: T): Preserve =
elif T is float64:
result = Preserve(kind: pkDouble, double: x)
elif T is object | tuple:
when T.hasCustomPragma(record):
when T.hasCustomPragma(unpreservable): {.error.}
elif T.hasCustomPragma(record):
result = Preserve(kind: pkRecord)
for _, f in x.fieldPairs: result.record.add(toPreserve(f))
result.record.add(symbol(T.getCustomPragmaVal(record)))