mirror of
https://github.com/nim-lang/Nim.git
synced 2026-04-18 13:30:33 +00:00
Merge pull request #4819 from andreaferretti/usefulmacros
Some useful macros
This commit is contained in:
@@ -890,6 +890,30 @@ proc boolVal*(n: NimNode): bool {.compileTime, noSideEffect.} =
|
||||
if n.kind == nnkIntLit: n.intVal != 0
|
||||
else: n == bindSym"true" # hacky solution for now
|
||||
|
||||
macro expandMacros*(body: typed): untyped =
|
||||
## Expands one level of macro - useful for debugging.
|
||||
## Can be used to inspect what happens when a macro call is expanded,
|
||||
## without altering its result.
|
||||
##
|
||||
## For instance,
|
||||
##
|
||||
## .. code-block:: nim
|
||||
## import future, macros
|
||||
##
|
||||
## let
|
||||
## x = 10
|
||||
## y = 20
|
||||
## expandMacros:
|
||||
## dump(x + y)
|
||||
##
|
||||
## will actually dump `x + y`, but at the same time will print at
|
||||
## compile time the expansion of the ``dump`` macro, which in this
|
||||
## case is ``debugEcho ["x + y", " = ", x + y]``.
|
||||
template inner(x: untyped): untyped = x
|
||||
|
||||
result = getAst(inner(body))
|
||||
echo result.toStrLit
|
||||
|
||||
when not defined(booting):
|
||||
template emit*(e: static[string]): untyped {.deprecated.} =
|
||||
## accepts a single string argument and treats it as nim code
|
||||
|
||||
@@ -177,3 +177,24 @@ macro `[]`*(lc: ListComprehension, comp, typ: untyped): untyped =
|
||||
newIdentNode("@"),
|
||||
newNimNode(nnkBracket))),
|
||||
result))))
|
||||
|
||||
|
||||
macro dump*(x: typed): untyped =
|
||||
## Dumps the content of an expression, useful for debugging.
|
||||
## It accepts any expression and prints a textual representation
|
||||
## of the tree representing the expression - as it would appear in
|
||||
## source code - together with the value of the expression.
|
||||
##
|
||||
## As an example,
|
||||
##
|
||||
## .. code-block:: nim
|
||||
## let
|
||||
## x = 10
|
||||
## y = 20
|
||||
## dump(x + y)
|
||||
##
|
||||
## will print ``x + y = 30``.
|
||||
let s = x.toStrLit
|
||||
let r = quote do:
|
||||
debugEcho `s`, " = ", `x`
|
||||
return r
|
||||
13
tests/macros/tdump.nim
Normal file
13
tests/macros/tdump.nim
Normal file
@@ -0,0 +1,13 @@
|
||||
discard """
|
||||
output: '''x = 10
|
||||
x + y = 30
|
||||
'''
|
||||
"""
|
||||
|
||||
import future
|
||||
|
||||
let
|
||||
x = 10
|
||||
y = 20
|
||||
dump x
|
||||
dump(x + y)
|
||||
Reference in New Issue
Block a user