Case-Of Macro
In Nim it is possible to have a macro with the syntax of a case-of expression just with the difference that all of branches are passed to and processed by the macro implementation. It is then up the macro implementation to transform the of-branches into a valid Nim statement. The following example should show how this feature could be used for a lexical analyzer.
import macros
macro case_token(args: varargs[untyped]): untyped =
echo args.treeRepr
# creates a lexical analyzer from regular expressions
# ... (implementation is an exercise for the reader ;-)
discard
case_token: # this colon tells the parser it is a macro statement
of r"[A-Za-z_]+[A-Za-z_0-9]*":
return tkIdentifier
of r"0-9+":
return tkInteger
of r"[\+\-\*\?]+":
return tkOperator
else:
return tkUnknown
Style note: For code readability, it is the best idea to use the least powerful programming construct that still suffices. So the “check list” is:
- Use an ordinary proc/iterator, if possible.
- Else: Use a generic proc/iterator, if possible.
- Else: Use a template, if possible.
- Else: Use a macro.
当前内容版权归 nim-lang.org 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 nim-lang.org .