summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAndreas Rumpf <rumpf_a@web.de>2016-08-05 20:11:28 +0200
committerGitHub <noreply@github.com>2016-08-05 20:11:28 +0200
commitdf0baefb1238adccf15c18e75992c5472aa02f65 (patch)
tree0e699686e315167aeccce56fae4d292d12289b72
parent64ce8c411e1b2d83cdc15ab8757aec738df0c963 (diff)
parente2e4df170281ca663fe023a551e2a97611a9ceca (diff)
downloadNim-df0baefb1238adccf15c18e75992c5472aa02f65.tar.gz
Merge pull request #4572 from oderwat/distinct-nil
Allowing `nil` for distinct types where the base type is nilable
-rw-r--r--compiler/sigmatch.nim2
-rw-r--r--tests/distinct/tnil.nim47
2 files changed, 49 insertions, 0 deletions
diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim
index 19ef8a117..7cde101cb 100644
--- a/compiler/sigmatch.nim
+++ b/compiler/sigmatch.nim
@@ -900,6 +900,8 @@ proc typeRel(c: var TCandidate, f, aOrig: PType, doBind = true): TTypeRelation =
       if sameDistinctTypes(f, a): result = isEqual
       elif f.base.kind == tyAnything: result = isGeneric
       elif c.coerceDistincts: result = typeRel(c, f.base, a)
+    elif a.kind == tyNil and f.base.kind in NilableTypes:
+      result = f.allowsNil
     elif c.coerceDistincts: result = typeRel(c, f.base, a)
   of tySet:
     if a.kind == tySet:
diff --git a/tests/distinct/tnil.nim b/tests/distinct/tnil.nim
new file mode 100644
index 000000000..ed0ac995a
--- /dev/null
+++ b/tests/distinct/tnil.nim
@@ -0,0 +1,47 @@
+discard """
+  file: "tnil.nim"
+  output: '''0x1
+
+nil
+
+nil
+
+'''
+"""
+
+type
+  MyPointer = distinct pointer
+  MyString = distinct string
+  MyStringNotNil = distinct (string not nil)
+  MyInt = distinct int
+
+proc foo(a: MyPointer) =
+  echo a.repr
+
+foo(cast[MyPointer](1))
+foo(cast[MyPointer](nil))
+foo(nil)
+
+var p: MyPointer
+p = cast[MyPointer](1)
+p = cast[MyPointer](nil)
+p = nil.MyPointer
+p = nil
+
+var c: MyString
+c = "Test".MyString
+c = nil.MyString
+c = nil
+
+p = nil
+doAssert(compiles(c = p) == false)
+
+var n: MyStringNotNil = "Test".MyStringNotNil # Cannot prove warning ...
+n = "Test".MyStringNotNil
+doAssert(compiles(n = nil.MyStringNotNil) == false)
+doAssert(compiles(n = nil.MyStringNotNil) == false)
+doAssert(compiles(n = nil) == false)
+
+var i: MyInt
+i = 1.MyInt
+doAssert(compiles(i = nil) == false)