tcasestmtmacro.nim 685 B

123456789101112131415161718192021222324252627282930313233343536
  1. discard """
  2. output: '''
  3. yes
  4. '''
  5. """
  6. {.experimental: "caseStmtMacros".}
  7. import macros
  8. macro `case`(n: tuple): untyped =
  9. result = newTree(nnkIfStmt)
  10. let selector = n[0]
  11. for i in 1 ..< n.len:
  12. let it = n[i]
  13. case it.kind
  14. of nnkElse, nnkElifBranch, nnkElifExpr, nnkElseExpr:
  15. result.add it
  16. of nnkOfBranch:
  17. for j in 0..it.len-2:
  18. let cond = newCall("==", selector, it[j])
  19. result.add newTree(nnkElifBranch, cond, it[^1])
  20. else:
  21. error "custom 'case' for tuple cannot handle this node", it
  22. var correct = false
  23. case ("foo", 78)
  24. of ("foo", 78):
  25. correct = true
  26. echo "yes"
  27. of ("bar", 88): echo "no"
  28. else: discard
  29. doAssert correct