diff options
Diffstat (limited to 'examples/listId2.lua')
-rw-r--r-- | examples/listId2.lua | 32 |
1 files changed, 13 insertions, 19 deletions
diff --git a/examples/listId2.lua b/examples/listId2.lua index 48157f1..509fda4 100644 --- a/examples/listId2.lua +++ b/examples/listId2.lua | |||
@@ -1,42 +1,36 @@ | |||
1 | local m = require'lpeglabel' | 1 | local m = require'lpeglabel' |
2 | local re = require'relabel' | ||
2 | 3 | ||
3 | local terror = {} | 4 | local terror = {} |
4 | 5 | ||
5 | local function newError(s) | 6 | local function newError(s) |
6 | table.insert(terror, s) | 7 | table.insert(terror, s) |
7 | return #terror | 8 | return #terror |
8 | end | 9 | end |
9 | 10 | ||
10 | local errUndef = newError("undefined") | 11 | local errUndef = newError("undefined") |
11 | local errId = newError("expecting an identifier") | 12 | local errId = newError("expecting an identifier") |
12 | local errComma = newError("expecting ','") | 13 | local errComma = newError("expecting ','") |
13 | 14 | ||
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{ | 15 | local g = m.P{ |
22 | "S", | 16 | "S", |
23 | S = m.V"Id" * m.V"List", | 17 | S = m.V"Id" * m.V"List", |
24 | 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", |
25 | Id = m.V"Sp" * m.R'az'^1, | 19 | Id = m.V"Sp" * m.R'az'^1, |
26 | Comma = m.V"Sp" * ",", | 20 | Comma = m.V"Sp" * ",", |
27 | Sp = m.S" \n\t"^0, | 21 | Sp = m.S" \n\t"^0, |
28 | } | 22 | } |
29 | 23 | ||
30 | function mymatch (g, s) | 24 | function mymatch (g, s) |
31 | local r, e, sfail = g:match(s) | 25 | local r, e, sfail = g:match(s) |
32 | if not r then | 26 | if not r then |
33 | local line, col = calcline(s, #s - #sfail) | 27 | local line, col = re.calcline(s, #s - #sfail) |
34 | local msg = "Error at line " .. line .. " (col " .. col .. "): " | 28 | local msg = "Error at line " .. line .. " (col " .. col .. "): " |
35 | return r, msg .. terror[e] .. " before '" .. sfail .. "'" | 29 | return r, msg .. terror[e] .. " before '" .. sfail .. "'" |
36 | end | 30 | end |
37 | return r | 31 | return r |
38 | end | 32 | end |
39 | 33 | ||
40 | print(mymatch(g, "one,two")) | 34 | print(mymatch(g, "one,two")) |
41 | print(mymatch(g, "one two")) | 35 | print(mymatch(g, "one two")) |
42 | print(mymatch(g, "one,\n two,\nthree,")) | 36 | print(mymatch(g, "one,\n two,\nthree,")) |