trmacros_various2.nim 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 = &&a
  51. let space = " "
  52. echo "my" && (space & "awe" && "some " ) && "concat"
  53. # check that it's been optimized properly:
  54. doAssert calls == 1
  55. # bug #7524
  56. template in_to_out(typIn, typOut: typedesc) =
  57. proc to_out(x: typIn{lit}): typOut = result = ord(x)
  58. # Generating the proc via template doesn't work
  59. in_to_out(char, int)
  60. # This works
  61. proc to_out2(x: char{lit}): int = result = ord(x)