trmacros_various.nim 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. {.noRewrite.}:
  26. var gl {.global, gensym.} = peg(pattern)
  27. gl
  28. doAssert match("(a b c)", peg"'(' @ ')'")
  29. doAssert match("W_HI_Le", peg"\y 'while'")
  30. block tmatrix:
  31. type
  32. TMat = object
  33. dummy: int
  34. proc `*`(a, b: TMat): TMat = nil
  35. proc `+`(a, b: TMat): TMat = nil
  36. proc `-`(a, b: TMat): TMat = nil
  37. proc `$`(a: TMat): string = result = $a.dummy
  38. proc mat21(): TMat =
  39. result.dummy = 21
  40. macro optOps{ (`+`|`-`|`*`) ** a }(a: TMat): untyped =
  41. result = newCall(bindSym"mat21")
  42. #macro optPlus{ `+` * a }(a: varargs[TMat]): expr =
  43. # result = newIntLitNode(21)
  44. var x, y, z: TMat
  45. echo x + y * z - x
  46. block tnoalias:
  47. template optslice{a = b + c}(a: untyped{noalias}, b, c: untyped): typed =
  48. a = b
  49. inc a, c
  50. var
  51. x = 12
  52. y = 10
  53. z = 13
  54. x = y+z
  55. doAssert x == 23
  56. block tnoendlessrec:
  57. # test that an endless recursion is avoided:
  58. template optLen{len(x)}(x: typed): int = len(x)
  59. var s = "lala"
  60. doAssert len(s) == 4
  61. block tstatic_t_bug:
  62. # bug #4227
  63. type Vector64[N: static[int]] = array[N, int]
  64. proc `*`[N: static[int]](a: Vector64[N]; b: float64): Vector64[N] =
  65. result = a
  66. proc `+=`[N: static[int]](a: var Vector64[N]; b: Vector64[N]) =
  67. echo "regular"
  68. proc linearCombinationMut[N: static[int]](a: float64, v: var Vector64[N], w: Vector64[N]) {. inline .} =
  69. echo "optimized"
  70. template rewriteLinearCombinationMut{v += `*`(w, a)}(a: float64, v: var Vector64, w: Vector64): auto =
  71. linearCombinationMut(a, v, w)
  72. proc main() =
  73. const scaleVal = 9.0
  74. var a, b: Vector64[7]
  75. a += b * scaleval
  76. main()