Skip to content

Commit

Permalink
Support when statements in records that reuse the same field name in …
Browse files Browse the repository at this point in the history
…different branches
  • Loading branch information
zah committed Jan 6, 2021
1 parent 217d78a commit 4e2ffe3
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 12 deletions.
12 changes: 7 additions & 5 deletions serialization/object_serialization.nim
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ macro enumAllSerializedFieldsImpl(T: type, body: untyped): untyped =

let
fieldType = field.typ
FieldTypeSym = getTypeInst(fieldType)
fieldIdent = field.name
realFieldName = newLit($fieldIdent.skipPragma)
serializedFieldName = field.readPragma("serializedFieldName")
Expand Down Expand Up @@ -132,14 +133,15 @@ macro enumAllSerializedFieldsImpl(T: type, body: untyped): untyped =
result.add quote do:
block:
when compiles(type(`field`)):
`fieldNameDefs`

type FieldType {.inject, used.} = type(`field`)

template fieldCaseDiscriminator: auto {.used.} = `discriminator`
template fieldCaseBranches: auto {.used.} = `branches`
when FieldType is `FieldTypeSym`:
`fieldNameDefs`

template fieldCaseDiscriminator: auto {.used.} = `discriminator`
template fieldCaseBranches: auto {.used.} = `branches`

`body`
`body`

i += 1

Expand Down
36 changes: 29 additions & 7 deletions tests/test_object_serialization.nim
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,41 @@ import
../serialization/object_serialization,
../serialization/testing/generic_suite

suite "object serialization":
setup:
var fieldsList = newSeq[string]()
type
Untrusted = object
Trusted = object

test "custom fields order":
enumAllSerializedFields(Simple):
fieldsList.add(name(FieldType) & " " & fieldName & fieldCaseDiscriminator)
Signature = object
p: int
k: float

check fieldsList == @["Meter distance", "int x", "string y"]
TrustedSignature = object
data: string

SignatureHolder[TrustLevel] = object
when TrustLevel is Trusted:
sig: TrustedSignature
origin: string
else:
sig: Signature

func collectFields(T: type): seq[string] =
enumAllSerializedFields(T):
result.add(name(FieldType) & " " & fieldName & fieldCaseDiscriminator)

suite "object serialization":
test "custom fields order":
check collectFields(Simple) == @["Meter distance", "int x", "string y"]

test "tuples handling":
var fieldsList = newSeq[string]()

enumAllSerializedFields(HoldsTuples):
fieldsList.add(fieldName & ": " & $isTuple(FieldType))

check fieldsList == @["t1: true", "t2: true", "t3: true"]

test "when statements":
check collectFields(SignatureHolder[Trusted]) == @["TrustedSignature sig", "string origin"]
check collectFields(SignatureHolder[Untrusted]) == @["Signature sig"]

0 comments on commit 4e2ffe3

Please sign in to comment.