diff options
Diffstat (limited to 'examples/listIdCatch.lua')
-rw-r--r-- | examples/listIdCatch.lua | 35 |
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' | |||
3 | local terror = {} | 3 | local terror = {} |
4 | 4 | ||
5 | local function newError(s) | 5 | local function newError(s) |
6 | table.insert(terror, s) | 6 | table.insert(terror, s) |
7 | return #terror | 7 | return #terror |
8 | end | 8 | end |
9 | 9 | ||
10 | local errUndef = newError("undefined") | 10 | local errUndef = newError("undefined") |
11 | local errId = newError("expecting an identifier") | 11 | local errId = newError("expecting an identifier") |
12 | local errComma = newError("expecting ','") | 12 | local errComma = newError("expecting ','") |
13 | 13 | ||
14 | local 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 | ||
19 | end | ||
20 | |||
21 | local g = m.P{ | 14 | local 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 | ||
33 | function mymatch (g, s) | 26 | print(m.match(g, "one,two")) |
34 | local r, e, sfail = g:match(s) | 27 | print(m.match(g, "one two")) |
35 | if not r then | 28 | print(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 | ||
41 | end | ||
42 | |||
43 | print(mymatch(g, "one,two")) | ||
44 | print(mymatch(g, "one two")) | ||
45 | print(mymatch(g, "one,\n two,\nthree,")) | ||