trmacros_various.nim 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. discard """
  2. output: '''
  3. 12false3ha
  4. 21
  5. optimized
  6. '''
  7. """
  8. import macros, pegs
  9. block arglist:
  10. proc f(x: varargs[string, `$`]) = discard
  11. template optF{f(x)}(x: varargs[untyped]) =
  12. writeLine(stdout, x)
  13. f 1, 2, false, 3, "ha"
  14. block tcse:
  15. template cse{f(a, a, x)}(a: typed{(nkDotExpr|call|nkBracketExpr)&noSideEffect},
  16. f: typed, x: varargs[typed]): untyped =
  17. let aa = a
  18. f(aa, aa, x)+4
  19. var
  20. a: array[0..10, int]
  21. i = 3
  22. doAssert a[i] + a[i] == 4
  23. block hoist:
  24. template optPeg{peg(pattern)}(pattern: string{lit}): Peg =
  25. var gl {.global, gensym.} = peg(pattern)
  26. gl
  27. doAssert match("(a b c)", peg"'(' @ ')'")
  28. doAssert match("W_HI_Le", peg"\y 'while'")
  29. block tmatrix:
  30. type
  31. TMat = object
  32. dummy: int
  33. proc `*`(a, b: TMat): TMat = nil
  34. proc `+`(a, b: TMat): TMat = nil
  35. proc `-`(a, b: TMat): TMat = nil
  36. proc `$`(a: TMat): string = result = $a.dummy
  37. proc mat21(): TMat =
  38. result.dummy = 21
  39. macro optOps{ (`+`|`-`|`*`) ** a }(a: TMat): untyped =
  40. result = newCall(bindSym"mat21")
  41. #macro optPlus{ `+` * a }(a: varargs[TMat]): expr =
  42. # result = newIntLitNode(21)
  43. var x, y, z: TMat
  44. echo x + y * z - x
  45. block tnoalias:
  46. template optslice{a = b + c}(a: untyped{noalias}, b, c: untyped): typed =
  47. a = b
  48. inc a, c
  49. var
  50. x = 12
  51. y = 10
  52. z = 13
  53. x = y+z
  54. doAssert x == 23
  55. block tnoendlessrec:
  56. # test that an endless recursion is avoided:
  57. template optLen{len(x)}(x: typed): int = len(x)
  58. var s = "lala"
  59. doAssert len(s) == 4
  60. block tstatic_t_bug:
  61. # bug #4227
  62. type Vector64[N: static[int]] = array[N, int]
  63. proc `*`[N: static[int]](a: Vector64[N]; b: float64): Vector64[N] =
  64. result = a
  65. proc `+=`[N: static[int]](a: var Vector64[N]; b: Vector64[N]) =
  66. echo "regular"
  67. proc linearCombinationMut[N: static[int]](a: float64, v: var Vector64[N], w: Vector64[N]) {. inline .} =
  68. echo "optimized"
  69. template rewriteLinearCombinationMut{v += `*`(w, a)}(a: float64, v: var Vector64, w: Vector64): auto =
  70. linearCombinationMut(a, v, w)
  71. proc main() =
  72. const scaleVal = 9.0
  73. var a, b: Vector64[7]
  74. a += b * scaleval
  75. main()