make the 'canimport' template work

This commit is contained in:
Andreas Rumpf
2018-03-06 15:57:39 +01:00
parent 077ff83b6e
commit eeea000582
2 changed files with 27 additions and 1 deletions

View File

@@ -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")

View 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"