diff options
author | Andreas Rumpf <rumpf_a@web.de> | 2018-03-06 15:57:39 +0100 |
---|---|---|
committer | Andreas Rumpf <rumpf_a@web.de> | 2018-03-06 15:57:46 +0100 |
commit | eeea00058247e09a81e802f541194389d673c627 (patch) | |
tree | 267ab8b0f76459395ca10652bbd40ae29b9849dd | |
parent | 077ff83b6e27dad47c654f6d732fb03618f07748 (diff) | |
download | Nim-eeea00058247e09a81e802f541194389d673c627.tar.gz |
make the 'canimport' template work
-rw-r--r-- | compiler/semexprs.nim | 9 | ||||
-rw-r--r-- | tests/modules/tcanimport.nim | 19 |
2 files changed, 27 insertions, 1 deletions
diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index f1d226160..8e3aeffbe 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -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") diff --git a/tests/modules/tcanimport.nim b/tests/modules/tcanimport.nim new file mode 100644 index 000000000..bc4e2e53f --- /dev/null +++ b/tests/modules/tcanimport.nim @@ -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" |