Hi! Am I doing something stupid here, or is this just a bug?
type
Node = object
case leaf: bool
of true:
val: int
of false:
nodes: seq[Node]
let node = Node(leaf: true, val: 1)
#echo repr node
echo node
It seems like there's nothing wrong with the node itself (judging by the repr output), but echo doesn't like it. This happens both in 0.17.2 and the devel branch.That looks like a recursive data type -- Node can contain a seq[Node] which can contain Nodes which can contain seq[Node]...
I don't think that is what you really want. At least I generated something similar ones, and it was a mistake.
Here's a slightly stripped down version of what I'm really doing:
import tables
type
AtlasRegion = object
x: int
Dir = Table[string, Entry]
Entry = object
case leaf: bool
of true:
regs: seq[AtlasRegion]
of false:
dir: Dir
proc insertReg(root: var Dir, reg: AtlasRegion, path: openArray[string], start: int) =
if start < path.len - 1:
insertReg(root.mgetOrPut(
path[start],
Entry(leaf: false, dir: initTable[string, Entry]())
).dir, reg, path, start + 1)
else:
discard root.mgetOrPut(path[start], Entry(leaf: true, regs: @[reg]))
var dir = initTable[string, Entry]()
insertReg(dir, AtlasRegion(), ["foo", "bar", "baz", "tex"], 0)
echo dir["foo"].dir["bar"].dir["baz"].dir["tex"].regs
So a dir is a table of entries, and an entry can itself be either a dir or a sequence of atlas regions. This is analogous to a simple file system structure, and it's indeed what I want. Also, it seems to work fine, except when trying to print any entry using echo. The example in my first post is a simpler reproduction.Here's an implementation of your suggestion for my second snippet:
proc `$`(entry: Entry): string =
if entry.leaf:
$entry.regs
else:
$entry.dir
This seems to work correctly, which only makes the crash more mysterious. If echo already deals with variant objects out of the box, shouldn't it just generate roughly the same code?