-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathensure.lua
62 lines (57 loc) · 1.29 KB
/
ensure.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
local parser = require("overseer.parser")
local util = require("overseer.parser.util")
local Ensure = {
desc = "Decorator that runs a child until it succeeds",
doc_args = {
{
name = "succeed",
type = "boolean",
desc = "Set to false to run child until failure",
default = true,
position_optional = true,
},
{
name = "child",
type = "parser",
desc = "The child parser node",
},
},
examples = {
{
desc = [[An extract node that runs until it successfully parses]],
code = [[
{"ensure",
{"extract", "^([^%s].+):(%d+): (.+)$", "filename", "lnum", "text" }
}
]],
},
},
}
local MAX_LOOP = 2
function Ensure.new(succeed, child)
if type(succeed) ~= "boolean" then
child = succeed
succeed = true
end
return setmetatable({
child = util.hydrate(child),
succeed = succeed,
}, { __index = Ensure })
end
function Ensure:reset()
self.child:reset()
end
function Ensure:ingest(...)
for _ = 1, MAX_LOOP do
local st = self.child:ingest(...)
if st == parser.STATUS.FAILURE and self.succeed then
self.child:reset()
elseif st == parser.STATUS.SUCCESS and not self.succeed then
self.child:reset()
else
return st
end
end
return parser.STATUS.RUNNING
end
return Ensure