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.

  1. import macros
  2. macro case_token(args: varargs[untyped]): untyped =
  3. echo args.treeRepr
  4. # creates a lexical analyzer from regular expressions
  5. # ... (implementation is an exercise for the reader ;-)
  6. discard
  7. case_token: # this colon tells the parser it is a macro statement
  8. of r"[A-Za-z_]+[A-Za-z_0-9]*":
  9. return tkIdentifier
  10. of r"0-9+":
  11. return tkInteger
  12. of r"[\+\-\*\?]+":
  13. return tkOperator
  14. else:
  15. 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:

  1. Use an ordinary proc/iterator, if possible.
  2. Else: Use a generic proc/iterator, if possible.
  3. Else: Use a template, if possible.
  4. Else: Use a macro.