Skip to content

Commit eeea000

Browse files
committed
make the 'canimport' template work
1 parent 077ff83 commit eeea000

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

compiler/semexprs.nim

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2376,7 +2376,14 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode =
23762376
of nkMacroDef: result = semMacroDef(c, n)
23772377
of nkTemplateDef: result = semTemplateDef(c, n)
23782378
of nkImportStmt:
2379-
if not isTopLevel(c): localError(n.info, errXOnlyAtModuleScope, "import")
2379+
# this particular way allows 'import' in a 'compiles' context so that
2380+
# template canImport(x): bool =
2381+
# compiles:
2382+
# import x
2383+
#
2384+
# works:
2385+
if c.currentScope.depthLevel > 2 + c.compilesContextId:
2386+
localError(n.info, errXOnlyAtModuleScope, "import")
23802387
result = evalImport(c, n)
23812388
of nkImportExceptStmt:
23822389
if not isTopLevel(c): localError(n.info, errXOnlyAtModuleScope, "import")

tests/modules/tcanimport.nim

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
discard """
2+
output: '''ABC
3+
nope'''
4+
"""
5+
6+
template canImport(x): bool =
7+
compiles:
8+
import x
9+
10+
when canImport(strutils):
11+
import strutils
12+
echo "abc".toUpperAscii
13+
else:
14+
echo "meh"
15+
16+
when canImport(none):
17+
echo "what"
18+
else:
19+
echo "nope"

0 commit comments

Comments
 (0)