summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--changelog.md2
-rw-r--r--compiler/semexprs.nim5
-rw-r--r--compiler/semfold.nim4
-rw-r--r--tests/misc/tcast.nim3
4 files changed, 12 insertions, 2 deletions
diff --git a/changelog.md b/changelog.md
index 7cbd4bb66..d53f5b038 100644
--- a/changelog.md
+++ b/changelog.md
@@ -51,7 +51,7 @@
 
 - The `cstring` doesn't support `[]=` operator in JS backend.
 
-
+- nil dereference is not allowed at compile time. `cast[ptr int](nil)[]` is rejected at compile time.
 
 ## Compiler changes
 
diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim
index cb119b3e8..608a82715 100644
--- a/compiler/semexprs.nim
+++ b/compiler/semexprs.nim
@@ -1440,6 +1440,11 @@ proc buildOverloadedSubscripts(n: PNode, ident: PIdent): PNode =
 proc semDeref(c: PContext, n: PNode): PNode =
   checkSonsLen(n, 1, c.config)
   n[0] = semExprWithType(c, n[0])
+  let a = getConstExpr(c.module, n[0], c.idgen, c.graph)
+  if a != nil:
+    if a.kind == nkNilLit:
+      localError(c.config, n.info, "nil dereference is not allowed")
+    n[0] = a
   result = n
   var t = skipTypes(n[0].typ, {tyGenericInst, tyVar, tyLent, tyAlias, tySink, tyOwned})
   case t.kind
diff --git a/compiler/semfold.nim b/compiler/semfold.nim
index 9b21c5fa3..b92895b19 100644
--- a/compiler/semfold.nim
+++ b/compiler/semfold.nim
@@ -671,6 +671,10 @@ proc getConstExpr(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode
     var a = getConstExpr(m, n[1], idgen, g)
     if a == nil: return
     result = foldConv(n, a, g, check=true)
+  of nkDerefExpr, nkHiddenDeref:
+    let a = getConstExpr(m, n[0], idgen, g)
+    if a != nil and a.kind == nkNilLit:
+       localError(g.config, n.info, "nil dereference is not allowed")
   of nkCast:
     var a = getConstExpr(m, n[1], idgen, g)
     if a == nil: return
diff --git a/tests/misc/tcast.nim b/tests/misc/tcast.nim
index 6c6de6f8d..454801a2d 100644
--- a/tests/misc/tcast.nim
+++ b/tests/misc/tcast.nim
@@ -33,7 +33,8 @@ reject: discard cast[ptr](a)
 # bug #15623
 block:
   if false:
-    echo cast[ptr int](nil)[]
+    let x = cast[ptr int](nil)
+    echo x[]
 
 block:
   if false: