tcasestmtmacro.nim 649 B

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