ttempl3.nim 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. discard """
  2. action: compile
  3. """
  4. template withOpenFile(f: untyped, filename: string, mode: FileMode,
  5. actions: untyped): untyped =
  6. block:
  7. # test that 'f' is implicitly 'injecting':
  8. var f: File
  9. if open(f, filename, mode):
  10. try:
  11. actions
  12. finally:
  13. close(f)
  14. else:
  15. quit("cannot open for writing: " & filename)
  16. withOpenFile(txt, "ttempl3.txt", fmWrite):
  17. writeLine(txt, "line 1")
  18. txt.writeLine("line 2")
  19. var
  20. myVar: array[0..1, int]
  21. # Test zero argument template:
  22. template ha: untyped = myVar[0]
  23. ha = 1
  24. echo(ha)
  25. # Test identifier generation:
  26. template prefix(name): untyped = `"hu" name`
  27. var `hu "XYZ"` = "yay"
  28. echo prefix(XYZ)
  29. template typedef(name: untyped, typ: typeDesc) {.dirty.} =
  30. type
  31. `T name`* = typ
  32. `P name`* = ref `T name`
  33. typedef(myint, int)
  34. var x: PMyInt
  35. # Test UFCS
  36. type
  37. Foo = object
  38. arg: int
  39. proc initFoo(arg: int): Foo =
  40. result.arg = arg
  41. template create(typ: typeDesc, arg: untyped): untyped = `init typ`(arg)
  42. var ff = Foo.create(12)
  43. echo ff.arg
  44. import macros
  45. # bug #11494
  46. macro staticForEach(arr: untyped, body: untyped): untyped =
  47. result = newNimNode(nnkStmtList)
  48. arr.expectKind(nnkBracket)
  49. for n in arr:
  50. let b = copyNimTree(body)
  51. result.add quote do:
  52. block:
  53. type it {.inject.} = `n`
  54. `b`
  55. template forEveryMatchingEntity*() =
  56. staticForEach([int, string, float]):
  57. var a {.inject.}: it
  58. echo a
  59. forEveryMatchingEntity()