mirror of
https://github.com/nim-lang/Nim.git
synced 2025-12-28 17:04:41 +00:00
Fixes #6604. Rejects unnamed tuples with error.
This commit is contained in:
committed by
Dominik Picheta
parent
e0681715dc
commit
d3c9b58c00
@@ -1701,6 +1701,10 @@ proc createConstructor(typeSym, jsonNode: NimNode): NimNode =
|
||||
result = processType(typeSym, obj, jsonNode, false)
|
||||
of nnkTupleTy:
|
||||
result = processType(typeSym, typeSym, jsonNode, false)
|
||||
of nnkPar:
|
||||
# TODO: The fact that `jsonNode` here works to give a good line number
|
||||
# is weird. Specifying typeSym should work but doesn't.
|
||||
error("Use a named tuple instead of: " & $toStrLit(typeSym), jsonNode)
|
||||
else:
|
||||
doAssert false, "Unable to create constructor for: " & $typeSym.kind
|
||||
|
||||
@@ -1828,9 +1832,16 @@ macro to*(node: JsonNode, T: typedesc): untyped =
|
||||
expectKind(typeNode, nnkBracketExpr)
|
||||
doAssert(($typeNode[0]).normalize == "typedesc")
|
||||
|
||||
result = createConstructor(typeNode[1], node)
|
||||
# Create `temp` variable to store the result in case the user calls this
|
||||
# on `parseJson` (see bug #6604).
|
||||
result = newNimNode(nnkStmtListExpr)
|
||||
let temp = genSym(nskLet, "temp")
|
||||
result.add quote do:
|
||||
let `temp` = `node`
|
||||
|
||||
let constructor = createConstructor(typeNode[1], temp)
|
||||
# TODO: Rename postProcessValue and move it (?)
|
||||
result = postProcessValue(result)
|
||||
result.add(postProcessValue(constructor))
|
||||
|
||||
# echo(treeRepr(result))
|
||||
# echo(toStrLit(result))
|
||||
|
||||
@@ -275,4 +275,24 @@ when isMainModule:
|
||||
let parsed = to(j, Thing)
|
||||
doAssert parsed.animal.fur
|
||||
doAssert parsed.animal.legs == 6
|
||||
doAssert parsed.color == Red
|
||||
doAssert parsed.color == Red
|
||||
|
||||
block:
|
||||
type
|
||||
Car = object
|
||||
engine: tuple[name: string, capacity: float]
|
||||
model: string
|
||||
|
||||
let j = """
|
||||
{"engine": {"name": "V8", "capacity": 5.5}, "model": "Skyline"}
|
||||
"""
|
||||
|
||||
var i = 0
|
||||
proc mulTest: JsonNode =
|
||||
i.inc()
|
||||
return parseJson(j)
|
||||
|
||||
let parsed = mulTest().to(Car)
|
||||
doAssert parsed.engine.name == "V8"
|
||||
|
||||
doAssert i == 1
|
||||
18
tests/stdlib/tjsonmacro_reject.nim
Normal file
18
tests/stdlib/tjsonmacro_reject.nim
Normal file
@@ -0,0 +1,18 @@
|
||||
discard """
|
||||
file: "tjsonmacro_reject.nim"
|
||||
line: 11
|
||||
errormsg: "Use a named tuple instead of: (string, float)"
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
type
|
||||
Car = object
|
||||
engine: (string, float)
|
||||
model: string
|
||||
|
||||
let j = """
|
||||
{"engine": {"name": "V8", "capacity": 5.5}, model: "Skyline"}
|
||||
"""
|
||||
let parsed = parseJson(j)
|
||||
echo(to(parsed, Car))
|
||||
Reference in New Issue
Block a user