aboutsummaryrefslogtreecommitdiff
path: root/examples/listIdCatch.lua
diff options
context:
space:
mode:
Diffstat (limited to 'examples/listIdCatch.lua')
-rw-r--r--examples/listIdCatch.lua35
1 files changed, 9 insertions, 26 deletions
diff --git a/examples/listIdCatch.lua b/examples/listIdCatch.lua
index 3cbc834..5ad6f2d 100644
--- a/examples/listIdCatch.lua
+++ b/examples/listIdCatch.lua
@@ -3,43 +3,26 @@ local m = require'lpeglabel'
3local terror = {} 3local terror = {}
4 4
5local function newError(s) 5local function newError(s)
6 table.insert(terror, s) 6 table.insert(terror, s)
7 return #terror 7 return #terror
8end 8end
9 9
10local errUndef = newError("undefined") 10local errUndef = newError("undefined")
11local errId = newError("expecting an identifier") 11local errId = newError("expecting an identifier")
12local errComma = newError("expecting ','") 12local errComma = newError("expecting ','")
13 13
14local function calcline (s, i)
15 if i == 1 then return 1, 1 end
16 local rest, line = s:sub(1,i):gsub("[^\n]*\n", "")
17 local col = #rest
18 return 1 + line, col ~= 0 and col or 1
19end
20
21local g = m.P{ 14local g = m.P{
22 "S", 15 "S",
23 S = m.Lc(m.Lc(m.V"Id" * m.V"List", m.V"ErrId", errId), 16 S = m.Lc(m.Lc(m.V"Id" * m.V"List", m.V"ErrId", errId),
24 m.V"ErrComma", errComma), 17 m.V"ErrComma", errComma),
25 List = -m.P(1) + (m.V"Comma" + m.T(errComma)) * (m.V"Id" + m.T(errId)) * m.V"List", 18 List = -m.P(1) + (m.V"Comma" + m.T(errComma)) * (m.V"Id" + m.T(errId)) * m.V"List",
26 Id = m.V"Sp" * m.R'az'^1, 19 Id = m.V"Sp" * m.R'az'^1,
27 Comma = m.V"Sp" * ",", 20 Comma = m.V"Sp" * ",",
28 Sp = m.S" \n\t"^0, 21 Sp = m.S" \n\t"^0,
29 ErrId = m.Cc(errId) / terror, 22 ErrId = m.Cc(errId) / terror,
30 ErrComma = m.Cc(errComma) / terror 23 ErrComma = m.Cc(errComma) / terror
31} 24}
32 25
33function mymatch (g, s) 26print(m.match(g, "one,two"))
34 local r, e, sfail = g:match(s) 27print(m.match(g, "one two"))
35 if not r then 28print(m.match(g, "one,\n two,\nthree,"))
36 local line, col = calcline(s, #s - #sfail)
37 local msg = "Error at line " .. line .. " (col " .. col .. "): "
38 return r, msg .. terror[e] .. " before '" .. sfail .. "'"
39 end
40 return r
41end
42
43print(mymatch(g, "one,two"))
44print(mymatch(g, "one two"))
45print(mymatch(g, "one,\n two,\nthree,"))