This doesn't work:
template bar() {.dirty.} =
echo a
template foo() =
let a = 5
bar()
foo()
but this does:
template bar() {.dirty.} =
echo a
template foo() {.dirty.} =
let a = 5
bar()
foo()
Is this a bug or I don't understand something about templates?
template bar() =
echo a
template foo() {.dirty.} =
let a = 5
bar()
foo()
echo a
I would expect exactly that behaviour. As templates are hygienic by default, we need dirty pragma for foo() to make variable a visible outside.
The {.dirty.} attribute forces template to copy-paste its code at the call side. It's typically used to make all symbols inject but it also means all the code inside of it is not symbol-checked too, it is deferred until unrolling the whole template, which effectively means it can inject its symbols not only up the hierarchy but also down it, like globals.
At least that's how I perceive the logic behind it.
template bar() {.dirty.} =
echo a
template foo() =
let a {.inject.} = 5
bar()
foo()
Hi Stefan,
It is not required as you say. As I understood it, zielmicha wants to call dirty template from hygienic template.
One more potential solution.
template bar(a) {.dirty.} =
echo a
template foo() =
let a = 5
bar(a)
foo()
At least that's how I perceive the logic behind it.
That is exactly what happens, can we improve the manual with your explanation?
I think maybe this is template bug. These code doesn't compile from @zielmicha.
template bar() {.dirty.} =
echo a
template foo() =
let a = 5
bar()
foo()
But when we turn foo into proc, the code works.
template bar() {.dirty.} =
echo a
proc foo() =
let a = 5
bar()
foo()
So it is doesn't matter if the foo is hygienic or not.