mirror of
https://github.com/nim-lang/Nim.git
synced 2026-02-18 17:08:32 +00:00
make the 'canimport' template work
This commit is contained in:
@@ -2376,7 +2376,14 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode =
|
||||
of nkMacroDef: result = semMacroDef(c, n)
|
||||
of nkTemplateDef: result = semTemplateDef(c, n)
|
||||
of nkImportStmt:
|
||||
if not isTopLevel(c): localError(n.info, errXOnlyAtModuleScope, "import")
|
||||
# this particular way allows 'import' in a 'compiles' context so that
|
||||
# template canImport(x): bool =
|
||||
# compiles:
|
||||
# import x
|
||||
#
|
||||
# works:
|
||||
if c.currentScope.depthLevel > 2 + c.compilesContextId:
|
||||
localError(n.info, errXOnlyAtModuleScope, "import")
|
||||
result = evalImport(c, n)
|
||||
of nkImportExceptStmt:
|
||||
if not isTopLevel(c): localError(n.info, errXOnlyAtModuleScope, "import")
|
||||
|
||||
19
tests/modules/tcanimport.nim
Normal file
19
tests/modules/tcanimport.nim
Normal file
@@ -0,0 +1,19 @@
|
||||
discard """
|
||||
output: '''ABC
|
||||
nope'''
|
||||
"""
|
||||
|
||||
template canImport(x): bool =
|
||||
compiles:
|
||||
import x
|
||||
|
||||
when canImport(strutils):
|
||||
import strutils
|
||||
echo "abc".toUpperAscii
|
||||
else:
|
||||
echo "meh"
|
||||
|
||||
when canImport(none):
|
||||
echo "what"
|
||||
else:
|
||||
echo "nope"
|
||||
Reference in New Issue
Block a user