I was thinking about implementing a macro to interpolate strings at compile time which could also be used as a runtime call. However there are two problems with a prototype implementation like this:
macro expandVars(text: string): expr =
if text.strVal.len < 4:
result = quote do: "short " & `text`
else:
result = quote do: "long " & `text`
proc expandVars(text: string): string =
result = "runtime " & text
const
hey = expandVars("foo")
proc test() =
var temp: string = ""
temp.add("hahah")
let s = expandVars(temp)
echo s
In this case the compiler gets confused and says there is an ambiguous call. If the runtime proc is removed and the macro left, when the compiler reaches the test proc it will complain about temp not having a strVal field, runtime vars are not a PNimrodNode.
Does something like the following exist?
macro staticStr(text: string): string {.compileTime.} =
result = "static " & text
proc runtimeStr(text: string): string =
result = "runtime " & text
macro wrapStr(stuff): string {.magical.} =
if stuff.isStatic: stuff.staticStr else: stuff.runtimeStr
Could you not use some like this:
import strutils
import macros
macro expandVars(text: string{lit}): expr =
if text.strVal.len < 4:
result = quote do: "short " & `text`
else:
result = quote do: "long " & `text`
proc expandVars(text: string): string =
result = "runtime " & text
const
hey = expandVars("foo")
proc test() =
var temp: string = ""
temp.add("hahah")
let s = expandVars(temp)
echo s
test()
echo hey
In case others stumble by, I thought I'd link to the relevant docs. See Parameter constraints in:
http://nim-lang.org/trmacros.html
or: