Case statement macros
Macros named `` case `` can provide implementations of case statements for certain types. The following is an example of such an implementation for tuples, leveraging the existing equality operator for tuples (as provided in system.==):
import std/macros
macro `case`(n: tuple): untyped =
result = newTree(nnkIfStmt)
let selector = n[0]
for i in 1 ..< n.len:
let it = n[i]
case it.kind
of nnkElse, nnkElifBranch, nnkElifExpr, nnkElseExpr:
result.add it
of nnkOfBranch:
for j in 0..it.len-2:
let cond = newCall("==", selector, it[j])
result.add newTree(nnkElifBranch, cond, it[^1])
else:
error "custom 'case' for tuple cannot handle this node", it
case ("foo", 78)
of ("foo", 78): echo "yes"
of ("bar", 88): echo "no"
else: discard
case macros are subject to overload resolution. The type of the case statement’s selector expression is matched against the type of the first argument of the case macro. Then the complete case statement is passed in place of the argument and the macro is evaluated.
In other words, the macro needs to transform the full case statement but only the statement’s selector expression is used to determine which macro to call.
当前内容版权归 nim-lang.org 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 nim-lang.org .