1
0
Fork 0
mirror of https://github.com/Reuh/anselme.git synced 2025-10-27 16:49:31 +00:00

Add break and continue

This commit is contained in:
Étienne Fildadut 2024-01-02 00:34:59 +01:00
parent e71096cab7
commit a79b054bfb
3 changed files with 32 additions and 13 deletions

View file

@ -1,32 +1,29 @@
local ast = require("anselme.ast")
local operator_priority = require("anselme.common").operator_priority
local Return
Return = ast.abstract.Node {
Return = ast.abstract.Runtime {
type = "return",
expression = nil,
subtype = nil, -- string; "break" or "continue"
init = function(self, expression)
init = function(self, expression, subtype)
self.expression = expression
self.subtype = subtype
end,
_format = function(self, ...)
return ("@%s"):format(self.expression:format_right(...))
end,
_format_priority = function(self)
return operator_priority["@_"]
if self.subtype then
return ("return(%s, %s)"):format(self.expression:format(...), self.subtype)
else
return ("return(%s)"):format(self.expression:format(...))
end
end,
traverse = function(self, fn, ...)
fn(self.expression, ...)
end,
_eval = function(self, state)
return Return:new(self.expression:eval(state))
end,
to_lua = function(self, state)
return self.expression:to_lua(state)
end

View file

@ -73,6 +73,20 @@ return {
return Return:new(val)
end
},
{
"break", "(value=())",
function(state, val)
if Return:is(val) then val = val.expression end
return Return:new(val, "break")
end
},
{
"continue", "(value=())",
function(state, val)
if Return:is(val) then val = val.expression end
return Return:new(val, "continue")
end
},
{
"attached block", "(level::number=1)",
function(state, level)

View file

@ -80,7 +80,15 @@ return {
end
while cond:truthy() do
r = expression:call(state, ArgumentTuple:new())
if Return:is(r) then break end
if Return:is(r) then
if r.subtype == "continue" then
r = r.expression -- consume return & pass
elseif r.subtype == "break" then
return r.expression -- consume return & break
else
return r
end
end
cond = condition:call(state, ArgumentTuple:new())
end
return r