trmacros_various2.nim 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. discard """
  2. output: '''
  3. 0
  4. -2
  5. 48
  6. hel
  7. lo
  8. my awesome concat
  9. '''
  10. """
  11. block tnoalias2:
  12. # bug #206
  13. template optimizeOut{testFunc(a, b)}(a: int, b: int{alias}): untyped = 0
  14. proc testFunc(a, b: int): int = result = a + b
  15. var testVar = 1
  16. echo testFunc(testVar, testVar)
  17. template ex{a = b + c}(a : int{noalias}, b, c : int) =
  18. a = b
  19. inc a, b
  20. echo "came here"
  21. var x = 5
  22. x = x + x
  23. block tpartial:
  24. proc p(x, y: int; cond: bool): int =
  25. result = if cond: x + y else: x - y
  26. template optPTrue{p(x, y, true)}(x, y): untyped = x - y
  27. template optPFalse{p(x, y, false)}(x, y): untyped = x + y
  28. echo p(2, 4, true)
  29. block tpatterns:
  30. template optZero{x+x}(x: int): int = x*3
  31. template andthen{`*`(x,3)}(x: int): int = x*4
  32. template optSubstr1{x = substr(x, a, b)}(x: string, a, b: int) = setlen(x, b+1)
  33. var y = 12
  34. echo y+y
  35. var s: array[0..2, string]
  36. s[0] = "hello"
  37. s[0] = substr(s[0], 0, 2)
  38. echo s[0]
  39. # Test varargs matching
  40. proc someVarargProc(k: varargs[string]) = doAssert(false) # this should not get called
  41. template someVarargProcSingleArg{someVarargProc([a])}(a: string) = echo a
  42. someVarargProc("lo")
  43. block tstar:
  44. var
  45. calls = 0
  46. proc `&&`(s: varargs[string]): string =
  47. result = s[0]
  48. for i in 1..len(s)-1: result.add s[i]
  49. inc calls
  50. template optConc{ `&&` * a }(a: string): string =
  51. {.noRewrite.}:
  52. &&a
  53. let space = " "
  54. echo "my" && (space & "awe" && "some " ) && "concat"
  55. # check that it's been optimized properly:
  56. doAssert calls == 1
  57. # bug #7524
  58. template in_to_out(typIn, typOut: typedesc) =
  59. proc to_out(x: typIn{lit}): typOut = result = ord(x)
  60. # Generating the proc via template doesn't work
  61. in_to_out(char, int)
  62. # This works
  63. proc to_out2(x: char{lit}): int = result = ord(x)