Skip to content

Commit

Permalink
Fix return inside switch case
Browse files Browse the repository at this point in the history
Fixes #2783
  • Loading branch information
Vurv78 committed Oct 6, 2023
1 parent 540cae7 commit cd4d012
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
20 changes: 20 additions & 0 deletions data/expression2/tests/regressions/2783.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
## SHOULD_PASS:EXECUTE

function number test(N:number) {
switch (N) {
case 1,
return 5
case 3,
error("unreachable")
case 2,
return 2
case 5,
error("unreachable")
}

return 1
}

assert( test(1) == 5 )
assert( test(2) == 2 )
assert( test(4) == 1 )
13 changes: 8 additions & 5 deletions lua/entities/gmod_wire_expression2/base/compiler.lua
Original file line number Diff line number Diff line change
Expand Up @@ -536,24 +536,26 @@ local CompileVisitors = {

return function(state) ---@param state RuntimeContext
local expr = expr(state)

state:PushScope()

for i = 1, ncases do
local case = cases[i]
if case[1](state, expr) ~= 0 then
case[2](state)

if state.__break__ then
state.__break__ = false
state:PopScope()
return
goto exit
elseif state.__return__ then -- Yes this should only be checked if the switch is inside a function, but I don't care enough about the performance of switch case to add another duplicated 30 lines to the file
goto exit
else -- Fallthrough, run every case until break found.
for j = i + 1, ncases do
cases[j][2](state)
if state.__break__ then
state.__break__ = false
state:PopScope()
return
goto exit
elseif state.__return__ then
goto exit
end
end
end
Expand All @@ -564,6 +566,7 @@ local CompileVisitors = {
default(state)
end

::exit::
state:PopScope()
end
end,
Expand Down

0 comments on commit cd4d012

Please sign in to comment.