aboutsummaryrefslogtreecommitdiff
path: root/examples/listId2Rec2.lua
diff options
context:
space:
mode:
authorSergio Queiroz <sqmedeiros@gmail.com>2016-11-14 17:15:27 -0300
committerSergio Queiroz <sqmedeiros@gmail.com>2016-11-14 17:15:27 -0300
commit448762908fd822fbc101a4fe66fac9cd8aa913b5 (patch)
treec7bc865aa66f557be6d3d9d422bcaec42a8be0be /examples/listId2Rec2.lua
parentfd28f9d9e54f33bf7ae3a5e12dc71478f9c91aea (diff)
downloadlpeglabel-448762908fd822fbc101a4fe66fac9cd8aa913b5.tar.gz
lpeglabel-448762908fd822fbc101a4fe66fac9cd8aa913b5.tar.bz2
lpeglabel-448762908fd822fbc101a4fe66fac9cd8aa913b5.zip
Changing documentation and examples with recovery
Diffstat (limited to 'examples/listId2Rec2.lua')
-rw-r--r--examples/listId2Rec2.lua67
1 files changed, 67 insertions, 0 deletions
diff --git a/examples/listId2Rec2.lua b/examples/listId2Rec2.lua
new file mode 100644
index 0000000..a347a5b
--- /dev/null
+++ b/examples/listId2Rec2.lua
@@ -0,0 +1,67 @@
1local m = require'lpeglabelrec'
2local re = require'relabelrec'
3
4local terror = {}
5
6local function newError(s)
7 table.insert(terror, s)
8 return #terror
9end
10
11local errUndef = newError("undefined")
12local errId = newError("expecting an identifier")
13local errComma = newError("expecting ','")
14
15local id = m.R'az'^1
16
17local g = m.P{
18 "S",
19 S = m.V"Id" * m.V"List",
20 List = -m.P(1) + m.V"Comma" * m.V"Id" * m.V"List",
21 Id = m.V"Sp" * id + m.T(errId),
22 Comma = m.V"Sp" * "," + m.T(errComma),
23 Sp = m.S" \n\t"^0,
24}
25
26local subject, errors
27
28function recorderror(pos, lab)
29 local line, col = re.calcline(subject, pos)
30 table.insert(errors, { line = line, col = col, msg = terror[lab] })
31end
32
33function record (lab)
34 return (m.Cp() * m.Cc(lab)) / recorderror
35end
36
37function sync (p)
38 return (-p * m.P(1))^0
39end
40
41local grec = m.P{
42 "S",
43 S = m.Rec(m.Rec(g, m.V"ErrComma", errComma), m.V"ErrId", errId),
44 ErrComma = record(errComma) * sync(-m.P(1) + id),
45 ErrId = record(errId) * sync(-m.P(1) + ",")
46}
47
48
49function mymatch (g, s)
50 errors = {}
51 subject = s
52 local r, e, sfail = g:match(s)
53 if #errors > 0 then
54 local out = {}
55 for i, err in ipairs(errors) do
56 local msg = "Error at line " .. err.line .. " (col " .. err.col .. "): " .. err.msg
57 table.insert(out, msg)
58 end
59 return nil, table.concat(out, "\n")
60 end
61 return r
62end
63
64print(mymatch(grec, "one,two"))
65print(mymatch(grec, "one two three"))
66print(mymatch(grec, "1,\n two, \n3,"))
67print(mymatch(grec, "one\n two123, \nthree,"))