diff options
author | Zahary Karadjov <zahary@gmail.com> | 2012-02-24 16:24:39 +0200 |
---|---|---|
committer | Zahary Karadjov <zahary@gmail.com> | 2012-02-24 16:25:50 +0200 |
commit | a3f16968a75e3a9b254b6fac7820fea83debd1e8 (patch) | |
tree | 87bd98690618886937ff86de6614b1b3cd6a0c77 /lib | |
parent | 96e7ee91cced216e287b9dadb6eec97147347989 (diff) | |
download | Nim-a3f16968a75e3a9b254b6fac7820fea83debd1e8.tar.gz |
helper templates static, eval and emit for easier compile-time code evaluation
Diffstat (limited to 'lib')
-rwxr-xr-x | lib/core/macros.nim | 13 | ||||
-rwxr-xr-x | lib/system.nim | 14 |
2 files changed, 26 insertions, 1 deletions
diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 4d13a076d..e8a16865e 100755 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -208,7 +208,18 @@ proc getAst*(macroOrTemplate: expr): expr {.magic: "ExpandToAst".} ## ## macro FooMacro() = ## var ast = getAst(BarTemplate()) - + +template emit*(s: expr): stmt = + ## accepts a single sting argument and treats it as nimrod code + ## that should be inserted verbatim in the program + ## Example: + ## + ## emit("echo " & '"' & "hello world".toUpper & '"') + ## + block: + const evaluated = s + eval: result = evaluated.parseStmt + proc expectKind*(n: PNimrodNode, k: TNimrodNodeKind) {.compileTime.} = ## checks that `n` is of kind `k`. If this is not the case, ## compilation aborts with an error message. This is useful for writing diff --git a/lib/system.nim b/lib/system.nim index b75f9022d..bfaa5eb8f 100755 --- a/lib/system.nim +++ b/lib/system.nim @@ -2213,6 +2213,20 @@ proc shallow*(s: var string) {.noSideEffect, inline.} = var s = cast[PGenericSeq](s) s.reserved = s.reserved or seqShallowFlag +template static*(e: expr): expr = + ## evaluates a given expression `e` at compile-time + ## even if it has side effects + block: + const res = e + res + +template eval*(blk: stmt): stmt = + ## executes a block of code at compile time just as if it was a macro + ## optonally, the block can return an AST tree that will replace the + ## eval expression + block: + macro payload(x: stmt): stmt = blk + payload() when defined(initDebugger): initDebugger() |