Fix infinite recursion when using json.to on ref with cycle.
This commit is contained in:
parent
8d61262372
commit
2bb2e6975e
3 changed files with 32 additions and 3 deletions
|
|
@ -1651,6 +1651,13 @@ import options
|
||||||
proc workaroundMacroNone[T](): Option[T] =
|
proc workaroundMacroNone[T](): Option[T] =
|
||||||
none(T)
|
none(T)
|
||||||
|
|
||||||
|
proc depth(n: NimNode, current = 0): int =
|
||||||
|
result = 1
|
||||||
|
for child in n:
|
||||||
|
let d = 1 + child.depth(current + 1)
|
||||||
|
if d > result:
|
||||||
|
result = d
|
||||||
|
|
||||||
proc createConstructor(typeSym, jsonNode: NimNode): NimNode =
|
proc createConstructor(typeSym, jsonNode: NimNode): NimNode =
|
||||||
## Accepts a type description, i.e. "ref Type", "seq[Type]", "Type" etc.
|
## Accepts a type description, i.e. "ref Type", "seq[Type]", "Type" etc.
|
||||||
##
|
##
|
||||||
|
|
@ -1660,6 +1667,9 @@ proc createConstructor(typeSym, jsonNode: NimNode): NimNode =
|
||||||
# echo("--createConsuctor-- \n", treeRepr(typeSym))
|
# echo("--createConsuctor-- \n", treeRepr(typeSym))
|
||||||
# echo()
|
# echo()
|
||||||
|
|
||||||
|
if depth(jsonNode) > 150:
|
||||||
|
error("The `to` macro does not support ref objects with cycles.", jsonNode)
|
||||||
|
|
||||||
case typeSym.kind
|
case typeSym.kind
|
||||||
of nnkBracketExpr:
|
of nnkBracketExpr:
|
||||||
var bracketName = ($typeSym[0]).normalize
|
var bracketName = ($typeSym[0]).normalize
|
||||||
|
|
|
||||||
|
|
@ -354,6 +354,4 @@ when isMainModule:
|
||||||
let dataDeser = to(dataParsed, Test)
|
let dataDeser = to(dataParsed, Test)
|
||||||
doAssert dataDeser.name == "FooBar"
|
doAssert dataDeser.name == "FooBar"
|
||||||
doAssert dataDeser.fallback.kind == JFloat
|
doAssert dataDeser.fallback.kind == JFloat
|
||||||
doAssert dataDeser.fallback.getFloat() == 56.42
|
doAssert dataDeser.fallback.getFloat() == 56.42
|
||||||
|
|
||||||
# TODO: Cycles lead to infinite loops.
|
|
||||||
21
tests/stdlib/tjsonmacro_reject2.nim
Normal file
21
tests/stdlib/tjsonmacro_reject2.nim
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
discard """
|
||||||
|
file: "tjsonmacro_reject2.nim"
|
||||||
|
line: 10
|
||||||
|
errormsg: "The `to` macro does not support ref objects with cycles."
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
|
||||||
|
type
|
||||||
|
Misdirection = object
|
||||||
|
cycle: Cycle
|
||||||
|
|
||||||
|
Cycle = ref object
|
||||||
|
foo: string
|
||||||
|
cycle: Misdirection
|
||||||
|
|
||||||
|
let data = """
|
||||||
|
{"cycle": null}
|
||||||
|
"""
|
||||||
|
|
||||||
|
let dataParsed = parseJson(data)
|
||||||
|
let dataDeser = to(dataParsed, Cycle)
|
||||||
Loading…
Add table
Add a link
Reference in a new issue