Templates, {.emit.}, and backtick interpolation do not work together #4730

mcclure opened this Issue Sep 7, 2016 · 0 comments


None yet

2 participants

mcclure commented Sep 7, 2016

I am running with nim 80fe763 self-built from git. I have only tested the following with nim js; I am not sure how to set up an appropriate nim c test.

I am trying to work around issue #4728. As mentioned in #4729, I can work around the issue with an importcpp pattern for [], but not for []=. I realize that even if importcpp won't cooperate, I can still get the result I want for []= with emit and a template. I put this in a file and compile it with nim js -o:testnim.js -d:release testnim.nim:

type TestType* {.importc.} = ref object of RootObj
    length* {.importc.}: float
proc newTestType*() : TestType {.importcpp:"new Object".}
proc `[]`*(t: TestType, key: float) : float {.importcpp:"#[#]".}

template `[]=`*(t: var TestType, key: float, val: float) =
    {.emit: "`t`[`key`] = `val`;".}

var x1 {.exportc.} = newTestType()
x1[1.0] = 5.0
let x2 {.exportc.} = x1[1.0]

Observed behavior: This produces a file that ends in:

var x1 = new Object();
t[key] = val;var x2 = x1[1.0000000000000000e+000];

Notice the t[key] = val. When run, this produces an error since t is undefined.

Expected behavior: I expect instead of t[key] = val it would have emitted x1[1.0] = 5.0. I expect this because the Nim docs say "A template is a hygienic macro and so opens a new scope. Most symbols are bound from the definition scope of the template" so I expect if I say t in the {.emit.} that refers to t in the template scope.

If there's some architectural reason why {.emit.} and template cannot be used together in this fashion, I expect Nim to notice that what I am doing is unsupported and emit a warning.

Incidentally, if I replace template with proc in the above code sample, everything works fine.

@Araq Araq added a commit that closed this issue Dec 17, 2016
@Araq Araq reworked emit pragma; fixes #4730 b013430
@Araq Araq closed this in b013430 Dec 17, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment