Skip to content

Support for unmarshalling to reference types #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
auxym opened this issue Oct 25, 2019 · 2 comments
Open

Support for unmarshalling to reference types #1

auxym opened this issue Oct 25, 2019 · 2 comments

Comments

@auxym
Copy link

auxym commented Oct 25, 2019

Is it planned to implement support for unmarshalling to reference (ref object) types? Example based on the README:

import samson

type User = ref object
    name: string
    age: range[0..high(int)]

let input = """
[
    {"name": "John Doe", age: 25},
    {"name": "Jane Doe", age: 22, timezone: "Europe/Stockholm"}
]
"""

let parsed = fromJson5(input, seq[User])

Currently this fails with : "Unsupported type: User".

@auxym
Copy link
Author

auxym commented Oct 25, 2019

I tried a quick (naive) implementation, which at first failed because fieldPairs does not work with refs. I tried my own wrapper for refs, but then that fails somewhere in the hasCustomPragma macro (unexpected node type nnkHiddenDeRef). Here was my attempt:

diff --git a/src/samson.nim b/src/samson.nim
index b11589e..1b41a83 100644
--- a/src/samson.nim
+++ b/src/samson.nim
@@ -14,7 +14,7 @@ export errors
 
 type
 
-  PlainObject = (object) and
+  PlainObject = (object|ref object) and
     (not (Option|Either|Table|OrderedTable|HashSet|OrderedSet|DateTime|Time))
 
   SupportedIntegerTypes = int8|int16|int32|int|int64|uint8|uint16|uint32
@@ -302,6 +302,10 @@ proc dateTimeFromJson(tree: JTree, idx: JnodeIdx,
     else:
       result = parseTime(tree.nodes[idx].strVal, f, local())
 
+iterator fieldPairs[T: ref object](o: var T): (string, var typed) 
+    for f, v in fieldPairs(o[]):
+        yield (f, v)
+
 proc fromJsonImpl(tree: JTree, idx: JNodeIdx, T: typedesc): T =
   template error {.used.} =
     schemaError(T, `$`(tree, idx))

@GULPF
Copy link
Owner

GULPF commented Oct 26, 2019

I usually avoid reference types in Nim and I'm not sure samson should support it. Typically there shouldn't be a reason to use a ref type for serialization/deserialization.

I think you might have hit a compiler bug with you solution, and it seems like there are more compiler issues related to fieldPairs and ref types (I just reported nim-lang/Nim#12523).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants