Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions compiler/sem.nim
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,11 @@ proc semConstExpr(c: PContext, n: PNode; expectedType: PType = nil): PNode =
return n
if e.kind in nkSymChoices and e[0].typ.skipTypes(abstractInst).kind == tyEnum:
return e
if e.typ.kind == tyProc and e.typ.callConv == ccClosure and {tfHasAsgn} * e.typ.flags != {}:
localError(c.config, n.info, "const closure proc with an environment cannot be used at runtime: " &
renderTree(n, {renderNoComments}))
return e

result = getConstExpr(c.module, e, c.idgen, c.graph)
if result == nil:
#if e.kind == nkEmpty: globalError(n.info, errConstExprExpected)
Expand Down
3 changes: 3 additions & 0 deletions compiler/semexprs.nim
Original file line number Diff line number Diff line change
Expand Up @@ -873,6 +873,9 @@ proc evalAtCompileTime(c: PContext, n: PNode): PNode =
localError(c.config, n.info, errCannotInterpretNodeX % renderTree(call))
else: result = fixupTypeAfterEval(c, result, n)
else:
let noneCtProc = sfCompileTime notin n[0].typ.owner.flags
if callee.kind == skConst and (n.typ == nil and noneCtProc):
return n
result = evalConstExpr(c.module, c.idgen, c.graph, call)
if result.isNil: result = n
else: result = fixupTypeAfterEval(c, result, n)
Expand Down
47 changes: 47 additions & 0 deletions tests/closure/tconstclosure.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@

discard """
cmd: "nim check --hints:off --warnings:off $file"
action: "reject"
nimout: '''
tconstclosure.nim(44, 24) Error: const closure proc with an environment cannot be used at runtime: makeMyClosure(myRef)






'''
"""





type
CallbackFunc* = proc (arg: pointer) {.gcsafe, raises: [Defect].}

AsyncCallback* = object
function*: CallbackFunc
udata*: pointer

proc sentinelCallbackImpl(arg: pointer) {.gcsafe, raises: [Defect].} =
raiseAssert "Sentinel callback MUST not be scheduled"

const
SentinelCallback = AsyncCallback(function: sentinelCallbackImpl,
udata: nil)

const a = proc() {.closure.} = echo "Hello"
a()

proc makeMyClosure(r: ref int): proc() =
result = proc() =
inc r[]
echo r[]

var myRef {.compileTime.} = new int # This makes a reference in VM since it needs to be accessible at CT, but we can make a closure to capture it.

const c = makeMyClosure(myRef)
let d = c

d()