bluenote10/NimSvg

Accessing fields of custom objects returns error

arkanoid87 opened this issue · 1 comments

Accessing field of custom ref objects returns error

type MyNode = ref object
    x: float
    y: float

let nodes = @[MyNode(x: 0.1, y: 0.2), MyNode(x: 0.3, y: 0.4)]

buildSvgFile("tests/foobar.svg"):
    svg(width = 100, height = 100):
        for n in nodes:
            let x = n.x  # error here
            let y = n.y  # error here
            circle(cx = x, cy = y, r = 80, stroke = "teal", `stroke-width` = 4, fill = "#EEF")

Error: undeclared field: 'x' for type nimsvg.Node [declared in /home/jack/.nimble/pkgs/nimsvg-0.2.0/nimsvg.nim(18, 3)]

Ah I see what's happening. That's the generated code (compiling with -d:debugDsl when in doubt):

block:
  var nodes = newSeq[Node]()
  let tmp_16075001 = newNode("svg")
  nodes.add(tmp_16075001)
  tmp_16075001.attributes = `@`([("width", `$`(100)), ("height", `$`(100))])
  tmp_16075001.children = block:
    var nodes = newSeq[Node]()
    for n in nodes:
      let x = n.x
      let y = n.y
      let tmp_16075012 = newNode("circle")
      nodes.add(tmp_16075012)
      tmp_16075012.attributes = `@`([("cx", `$`(x)), ("cy", `$`(y)), ("r", `$`(80)),
                                   ("stroke", `$`("teal")),
                                   ("stroke-width", `$`(4)), ("fill", `$`("#EEF"))])
    nodes 
  nodes

The problem is there is an internal variable called nodes from NimSvg which shadows your nodes variable. Lack of template hygiene is of course not good. Will look into fixing this soon. Until then you can work-around the issue e.g. by calling your variable myNodes.