aboutsummaryrefslogtreecommitdiff
path: root/examples/listId2.lua
diff options
context:
space:
mode:
Diffstat (limited to 'examples/listId2.lua')
-rw-r--r--examples/listId2.lua32
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 @@
1local m = require'lpeglabel' 1local m = require'lpeglabel'
2local re = require'relabel'
2 3
3local terror = {} 4local terror = {}
4 5
5local function newError(s) 6local function newError(s)
6 table.insert(terror, s) 7 table.insert(terror, s)
7 return #terror 8 return #terror
8end 9end
9 10
10local errUndef = newError("undefined") 11local errUndef = newError("undefined")
11local errId = newError("expecting an identifier") 12local errId = newError("expecting an identifier")
12local errComma = newError("expecting ','") 13local errComma = newError("expecting ','")
13 14
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{ 15local 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
30function mymatch (g, s) 24function 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
38end 32end
39 33
40print(mymatch(g, "one,two")) 34print(mymatch(g, "one,two"))
41print(mymatch(g, "one two")) 35print(mymatch(g, "one two"))
42print(mymatch(g, "one,\n two,\nthree,")) 36print(mymatch(g, "one,\n two,\nthree,"))