I would like to have some thing like this override/section thingy bellow:
If I have just a section named "redbox" I just want it to act normally with no substitution:
section "redbox":
echo "boring stuff"
But if I have an override block, some where in the code.
override "redbox":
echo "this is great!"
section "redbox":
echo "boring stuff"
It would instead use whats in the override
Pseudocode kind of:
var overrides = newTable[name, untyped]()
template override(name: string, inner: untyped) =
overrides[name] = inner
template section(name: string, inner: untyped) =
if name in overrides:
overrides[name]
else:
inner
How can I make it happen with nim?
This essentially does what you want.
template override(a, b : untyped) : untyped =
template a() : untyped =
b
template section(a, b : untyped) : untyped =
when compiles(a()):
a()
else:
b
override redbox:
echo "this is great!"
section redbox:
echo "boring stuff"
section whatever:
echo "boring stuff2"
As a side effect it creates templates though. So you could call redbox like
redbox()
I thought of another way to solve that doesn't produce side effect templates.
import macros
import tables
var overrides {.compiletime.} = initTable[string,string]()
macro override(a, b: untyped) : untyped =
var x = genSym(nskTemplate)
overrides[a.strVal] = x.strVal
result = quote do:
template `x`() : untyped =
`b`
macro section(a, b : untyped) : untyped =
let aStr = a.strVal
if aStr in overrides:
let templateName = ident(overrides[aStr])
result = quote do:
`templateName`()
else:
result = b
override redbox:
echo "Hello"
section redbox:
echo "Goodbye"
section whatever:
echo "Hello World!"
Do you know if I can make it work with strings? Some how to turn string into a symbol in a template?
template override(a: string, b : untyped) : untyped =
template {a cast from string}() : untyped =
echo a
b
template section(a, b : untyped) : untyped =
when compiles({a cast from string}()):
a()
else:
echo a
b
override "redbox":
echo "Hello"
section "redbox":
echo "Goodbye"
section "whatever":
echo "Hello World!"
Now with string.
import macros
import tables
var overrides {.compiletime.} = initTable[string,string]()
macro override(aStr : static[string], b: untyped) : untyped =
var x = genSym(nskTemplate)
overrides[aStr] = x.strVal
result = quote do:
template `x`() : untyped =
`b`
macro section(aStr : static[string], b : untyped) : untyped =
if aStr in overrides:
let templateName = ident(overrides[aStr])
result = quote do:
`templateName`()
else:
result = b
override "redbox":
echo "Hello"
section "redbox":
echo "Goodbye"
section "whatever":
echo "Hello World!"