summary refs log tree commit diff stats
path: root/tests/run
diff options
context:
space:
mode:
authorZahary Karadjov <zahary@gmail.com>2012-03-29 16:03:51 +0300
committerZahary Karadjov <zahary@gmail.com>2012-03-31 18:50:48 +0300
commit22dc76a361c70af93403dfbf2610c8d49111637c (patch)
treee04bfd670534fa2bbd8924746cba656da00fde66 /tests/run
parent6216046bc6b2794d15705f5d2621f602bda636c4 (diff)
downloadNim-22dc76a361c70af93403dfbf2610c8d49111637c.tar.gz
typedesc and expr params
types are now valid proc/template/macro params and you can overload over them:
proc foo(T: typedesc)        # accept any type
proc foo(T: typedesc{int}) # overload specifically for int
proc foo(T: typedesc{int or float or Callable}) # overload for any type matching the constraints

expr{type} is a param expecting compile time value of the designated type (or type class).

when typedesc or expr params are used with a proc, the proc will be instantiated once
for each unique type/value used as parameter.
Diffstat (limited to 'tests/run')
-rw-r--r--tests/run/tmemoization.nim17
-rw-r--r--tests/run/ttypedesc1.nim35
2 files changed, 52 insertions, 0 deletions
diff --git a/tests/run/tmemoization.nim b/tests/run/tmemoization.nim
new file mode 100644
index 000000000..10db1fcf1
--- /dev/null
+++ b/tests/run/tmemoization.nim
@@ -0,0 +1,17 @@
+discard """
+  msg:    "test 1\ntest 2"
+  output: "TEST 1\nTEST 2\nTEST 2"
+"""
+
+import strutils
+
+proc foo(s: expr{string}): string =
+  static: echo s
+
+  const R = s.toUpper
+  return R
+  
+echo foo("test 1")
+echo foo("test 2")
+echo foo("test " & $2)
+
diff --git a/tests/run/ttypedesc1.nim b/tests/run/ttypedesc1.nim
new file mode 100644
index 000000000..9c960a809
--- /dev/null
+++ b/tests/run/ttypedesc1.nim
@@ -0,0 +1,35 @@
+import unittest
+
+type 
+  TFoo[T, U] = object
+    x: T
+    y: U
+
+proc foo(T: typedesc{float}, a: expr): string =
+  result = "float " & $(a.len > 5)
+
+proc foo(T: typedesc{TFoo}, a: int): string =
+  result = "TFoo "  & $(a)
+
+proc foo(T: typedesc{int or bool}): string =
+  var a: T
+  a = 10
+  result = "int or bool " & ($a)
+
+template foo(T: typedesc{seq}): expr = "seq"
+
+test "types can be used as proc params":
+  check foo(TFoo[int, float], 1000) == "TFoo 1000"
+  
+  var f = 10.0
+  check foo(float, "long string") == "float true"
+  check foo(type(f), [1, 2, 3]) == "float false"
+  
+  check foo(int) == "int or bool 10"
+
+  check foo(seq[int]) == "seq"
+  check foo(seq[TFoo[bool, string]]) == "seq"
+
+when false:
+  proc foo(T: typedesc{seq}, s: T) = nil
+