mirror of
https://github.com/nim-lang/Nim.git
synced 2025-12-28 08:54:53 +00:00
when statements branches exit early (#17143)
When statement branches exit early outside of nimvm. In nimvm it seems that all sides of the branches must be evaluated as the code gen happens at a later stage, this remains intact.
This commit is contained in:
@@ -2364,6 +2364,7 @@ proc semWhen(c: PContext, n: PNode, semCheck = true): PNode =
|
||||
discard
|
||||
elif e.intVal != 0 and result == nil:
|
||||
setResult(it[1])
|
||||
return # we're not in nimvm and we already have a result
|
||||
of nkElse, nkElseExpr:
|
||||
checkSonsLen(it, 1, c.config)
|
||||
if result == nil or whenNimvm:
|
||||
|
||||
47
tests/whenstmt/twhen.nim
Normal file
47
tests/whenstmt/twhen.nim
Normal file
@@ -0,0 +1,47 @@
|
||||
discard """
|
||||
nimout: '''
|
||||
nimvm - when
|
||||
nimvm - whenElif
|
||||
nimvm - whenElse
|
||||
'''
|
||||
output: '''
|
||||
when
|
||||
whenElif
|
||||
whenElse
|
||||
'''
|
||||
"""
|
||||
|
||||
# test both when and when nimvm to ensure proper evaluation
|
||||
|
||||
proc compileOrRuntimeProc(s: string) =
|
||||
when nimvm:
|
||||
echo "nimvm - " & s
|
||||
else:
|
||||
echo s
|
||||
|
||||
template output(s: string) =
|
||||
static:
|
||||
compileOrRuntimeProc(s)
|
||||
compileOrRuntimeProc(s)
|
||||
|
||||
when compiles(1):
|
||||
output("when")
|
||||
elif compiles(2):
|
||||
output("fail - whenElif")
|
||||
else:
|
||||
output("fail - whenElse")
|
||||
|
||||
when compiles(nonexistent):
|
||||
output("fail - when")
|
||||
elif compiles(1):
|
||||
output("whenElif")
|
||||
else:
|
||||
output("fail - whenElse")
|
||||
|
||||
when compiles(nonexistent):
|
||||
output("fail - when")
|
||||
elif compiles(nonexistent):
|
||||
output("fail - whenElif")
|
||||
else:
|
||||
output("whenElse")
|
||||
|
||||
24
tests/whenstmt/twhen_macro.nim
Normal file
24
tests/whenstmt/twhen_macro.nim
Normal file
@@ -0,0 +1,24 @@
|
||||
import macros
|
||||
|
||||
discard """
|
||||
output: '''
|
||||
when - test
|
||||
'''
|
||||
"""
|
||||
|
||||
# test that when stmt works from within a macro
|
||||
|
||||
macro output(s: string, xs: varargs[untyped]): auto =
|
||||
result = quote do:
|
||||
when compiles(`s`):
|
||||
"when - " & `s`
|
||||
elif compiles(`s`):
|
||||
"elif - " & `s`
|
||||
# should never get here so this should not break
|
||||
broken.xs
|
||||
else:
|
||||
"else - " & `s`
|
||||
# should never get here so this should not break
|
||||
more.broken.xs
|
||||
|
||||
echo output("test")
|
||||
Reference in New Issue
Block a user