aboutsummaryrefslogtreecommitdiff
path: root/test.lua
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2019-02-20 10:13:46 -0300
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2019-02-20 10:13:46 -0300
commite08e5df853560de6482d84066a7accc6a18de545 (patch)
treeee19686bb35da90709a32ed24bf7855de1a3946a /test.lua
downloadlpeg-e08e5df853560de6482d84066a7accc6a18de545.tar.gz
lpeg-e08e5df853560de6482d84066a7accc6a18de545.tar.bz2
lpeg-e08e5df853560de6482d84066a7accc6a18de545.zip
Fist version of LPeg on GIT
LPeg repository is being moved to git. Past versions won't be moved; they are still available in RCS.
Diffstat (limited to 'test.lua')
-rwxr-xr-xtest.lua1513
1 files changed, 1513 insertions, 0 deletions
diff --git a/test.lua b/test.lua
new file mode 100755
index 0000000..51c5204
--- /dev/null
+++ b/test.lua
@@ -0,0 +1,1513 @@
1#!/usr/bin/env lua
2
3-- $Id: test.lua,v 1.114 2018/06/04 16:21:19 roberto Exp $
4
5-- require"strict" -- just to be pedantic
6
7local m = require"lpeg"
8
9
10-- for general use
11local a, b, c, d, e, f, g, p, t
12
13
14-- compatibility with Lua 5.2
15local unpack = rawget(table, "unpack") or unpack
16local loadstring = rawget(_G, "loadstring") or load
17
18
19local any = m.P(1)
20local space = m.S" \t\n"^0
21
22local function checkeq (x, y, p)
23if p then print(x,y) end
24 if type(x) ~= "table" then assert(x == y)
25 else
26 for k,v in pairs(x) do checkeq(v, y[k], p) end
27 for k,v in pairs(y) do checkeq(v, x[k], p) end
28 end
29end
30
31
32local mt = getmetatable(m.P(1))
33
34
35local allchar = {}
36for i=0,255 do allchar[i + 1] = i end
37allchar = string.char(unpack(allchar))
38assert(#allchar == 256)
39
40local function cs2str (c)
41 return m.match(m.Cs((c + m.P(1)/"")^0), allchar)
42end
43
44local function eqcharset (c1, c2)
45 assert(cs2str(c1) == cs2str(c2))
46end
47
48
49print"General tests for LPeg library"
50
51assert(type(m.version()) == "string")
52print("version " .. m.version())
53assert(m.type("alo") ~= "pattern")
54assert(m.type(io.input) ~= "pattern")
55assert(m.type(m.P"alo") == "pattern")
56
57-- tests for some basic optimizations
58assert(m.match(m.P(false) + "a", "a") == 2)
59assert(m.match(m.P(true) + "a", "a") == 1)
60assert(m.match("a" + m.P(false), "b") == nil)
61assert(m.match("a" + m.P(true), "b") == 1)
62
63assert(m.match(m.P(false) * "a", "a") == nil)
64assert(m.match(m.P(true) * "a", "a") == 2)
65assert(m.match("a" * m.P(false), "a") == nil)
66assert(m.match("a" * m.P(true), "a") == 2)
67
68assert(m.match(#m.P(false) * "a", "a") == nil)
69assert(m.match(#m.P(true) * "a", "a") == 2)
70assert(m.match("a" * #m.P(false), "a") == nil)
71assert(m.match("a" * #m.P(true), "a") == 2)
72
73
74-- tests for locale
75do
76 assert(m.locale(m) == m)
77 local t = {}
78 assert(m.locale(t, m) == t)
79 local x = m.locale()
80 for n,v in pairs(x) do
81 assert(type(n) == "string")
82 eqcharset(v, m[n])
83 end
84end
85
86
87assert(m.match(3, "aaaa"))
88assert(m.match(4, "aaaa"))
89assert(not m.match(5, "aaaa"))
90assert(m.match(-3, "aa"))
91assert(not m.match(-3, "aaa"))
92assert(not m.match(-3, "aaaa"))
93assert(not m.match(-4, "aaaa"))
94assert(m.P(-5):match"aaaa")
95
96assert(m.match("a", "alo") == 2)
97assert(m.match("al", "alo") == 3)
98assert(not m.match("alu", "alo"))
99assert(m.match(true, "") == 1)
100
101local digit = m.S"0123456789"
102local upper = m.S"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
103local lower = m.S"abcdefghijklmnopqrstuvwxyz"
104local letter = m.S"" + upper + lower
105local alpha = letter + digit + m.R()
106
107eqcharset(m.S"", m.P(false))
108eqcharset(upper, m.R("AZ"))
109eqcharset(lower, m.R("az"))
110eqcharset(upper + lower, m.R("AZ", "az"))
111eqcharset(upper + lower, m.R("AZ", "cz", "aa", "bb", "90"))
112eqcharset(digit, m.S"01234567" + "8" + "9")
113eqcharset(upper, letter - lower)
114eqcharset(m.S(""), m.R())
115assert(cs2str(m.S("")) == "")
116
117eqcharset(m.S"\0", "\0")
118eqcharset(m.S"\1\0\2", m.R"\0\2")
119eqcharset(m.S"\1\0\2", m.R"\1\2" + "\0")
120eqcharset(m.S"\1\0\2" - "\0", m.R"\1\2")
121
122local word = alpha^1 * (1 - alpha)^0
123
124assert((word^0 * -1):match"alo alo")
125assert(m.match(word^1 * -1, "alo alo"))
126assert(m.match(word^2 * -1, "alo alo"))
127assert(not m.match(word^3 * -1, "alo alo"))
128
129assert(not m.match(word^-1 * -1, "alo alo"))
130assert(m.match(word^-2 * -1, "alo alo"))
131assert(m.match(word^-3 * -1, "alo alo"))
132
133local eos = m.P(-1)
134
135assert(m.match(digit^0 * letter * digit * eos, "1298a1"))
136assert(not m.match(digit^0 * letter * eos, "1257a1"))
137
138b = {
139 [1] = "(" * (((1 - m.S"()") + #m.P"(" * m.V(1))^0) * ")"
140}
141
142assert(m.match(b, "(al())()"))
143assert(not m.match(b * eos, "(al())()"))
144assert(m.match(b * eos, "((al())()(é))"))
145assert(not m.match(b, "(al()()"))
146
147assert(not m.match(letter^1 - "for", "foreach"))
148assert(m.match(letter^1 - ("for" * eos), "foreach"))
149assert(not m.match(letter^1 - ("for" * eos), "for"))
150
151function basiclookfor (p)
152 return m.P {
153 [1] = p + (1 * m.V(1))
154 }
155end
156
157function caplookfor (p)
158 return basiclookfor(p:C())
159end
160
161assert(m.match(caplookfor(letter^1), " 4achou123...") == "achou")
162a = {m.match(caplookfor(letter^1)^0, " two words, one more ")}
163checkeq(a, {"two", "words", "one", "more"})
164
165assert(m.match( basiclookfor((#m.P(b) * 1) * m.Cp()), " ( (a)") == 7)
166
167a = {m.match(m.C(digit^1 * m.Cc"d") + m.C(letter^1 * m.Cc"l"), "123")}
168checkeq(a, {"123", "d"})
169
170-- bug in LPeg 0.12 (nil value does not create a 'ktable')
171assert(m.match(m.Cc(nil), "") == nil)
172
173a = {m.match(m.C(digit^1 * m.Cc"d") + m.C(letter^1 * m.Cc"l"), "abcd")}
174checkeq(a, {"abcd", "l"})
175
176a = {m.match(m.Cc(10,20,30) * 'a' * m.Cp(), 'aaa')}
177checkeq(a, {10,20,30,2})
178a = {m.match(m.Cp() * m.Cc(10,20,30) * 'a' * m.Cp(), 'aaa')}
179checkeq(a, {1,10,20,30,2})
180a = m.match(m.Ct(m.Cp() * m.Cc(10,20,30) * 'a' * m.Cp()), 'aaa')
181checkeq(a, {1,10,20,30,2})
182a = m.match(m.Ct(m.Cp() * m.Cc(7,8) * m.Cc(10,20,30) * 'a' * m.Cp()), 'aaa')
183checkeq(a, {1,7,8,10,20,30,2})
184a = {m.match(m.Cc() * m.Cc() * m.Cc(1) * m.Cc(2,3,4) * m.Cc() * 'a', 'aaa')}
185checkeq(a, {1,2,3,4})
186
187a = {m.match(m.Cp() * letter^1 * m.Cp(), "abcd")}
188checkeq(a, {1, 5})
189
190
191t = {m.match({[1] = m.C(m.C(1) * m.V(1) + -1)}, "abc")}
192checkeq(t, {"abc", "a", "bc", "b", "c", "c", ""})
193
194-- bug in 0.12 ('hascapture' did not check for captures inside a rule)
195do
196 local pat = m.P{
197 'S';
198 S1 = m.C('abc') + 3,
199 S = #m.V('S1') -- rule has capture, but '#' must ignore it
200 }
201 assert(pat:match'abc' == 1)
202end
203
204
205-- bug: loop in 'hascaptures'
206do
207 local p = m.C(-m.P{m.P'x' * m.V(1) + m.P'y'})
208 assert(p:match("xxx") == "")
209end
210
211
212
213-- test for small capture boundary
214for i = 250,260 do
215 assert(#m.match(m.C(i), string.rep('a', i)) == i)
216 assert(#m.match(m.C(m.C(i)), string.rep('a', i)) == i)
217end
218
219-- tests for any*n and any*-n
220for n = 1, 550, 13 do
221 local x_1 = string.rep('x', n - 1)
222 local x = x_1 .. 'a'
223 assert(not m.P(n):match(x_1))
224 assert(m.P(n):match(x) == n + 1)
225 assert(n < 4 or m.match(m.P(n) + "xxx", x_1) == 4)
226 assert(m.C(n):match(x) == x)
227 assert(m.C(m.C(n)):match(x) == x)
228 assert(m.P(-n):match(x_1) == 1)
229 assert(not m.P(-n):match(x))
230 assert(n < 13 or m.match(m.Cc(20) * ((n - 13) * m.P(10)) * 3, x) == 20)
231 local n3 = math.floor(n/3)
232 assert(m.match(n3 * m.Cp() * n3 * n3, x) == n3 + 1)
233end
234
235-- true values
236assert(m.P(0):match("x") == 1)
237assert(m.P(0):match("") == 1)
238assert(m.C(0):match("x") == "")
239
240assert(m.match(m.Cc(0) * m.P(10) + m.Cc(1) * "xuxu", "xuxu") == 1)
241assert(m.match(m.Cc(0) * m.P(10) + m.Cc(1) * "xuxu", "xuxuxuxuxu") == 0)
242assert(m.match(m.C(m.P(2)^1), "abcde") == "abcd")
243p = m.Cc(0) * 1 + m.Cc(1) * 2 + m.Cc(2) * 3 + m.Cc(3) * 4
244
245
246-- test for alternation optimization
247assert(m.match(m.P"a"^1 + "ab" + m.P"x"^0, "ab") == 2)
248assert(m.match((m.P"a"^1 + "ab" + m.P"x"^0 * 1)^0, "ab") == 3)
249assert(m.match(m.P"ab" + "cd" + "" + "cy" + "ak", "98") == 1)
250assert(m.match(m.P"ab" + "cd" + "ax" + "cy", "ax") == 3)
251assert(m.match("a" * m.P"b"^0 * "c" + "cd" + "ax" + "cy", "ax") == 3)
252assert(m.match((m.P"ab" + "cd" + "ax" + "cy")^0, "ax") == 3)
253assert(m.match(m.P(1) * "x" + m.S"" * "xu" + "ay", "ay") == 3)
254assert(m.match(m.P"abc" + "cde" + "aka", "aka") == 4)
255assert(m.match(m.S"abc" * "x" + "cde" + "aka", "ax") == 3)
256assert(m.match(m.S"abc" * "x" + "cde" + "aka", "aka") == 4)
257assert(m.match(m.S"abc" * "x" + "cde" + "aka", "cde") == 4)
258assert(m.match(m.S"abc" * "x" + "ide" + m.S"ab" * "ka", "aka") == 4)
259assert(m.match("ab" + m.S"abc" * m.P"y"^0 * "x" + "cde" + "aka", "ax") == 3)
260assert(m.match("ab" + m.S"abc" * m.P"y"^0 * "x" + "cde" + "aka", "aka") == 4)
261assert(m.match("ab" + m.S"abc" * m.P"y"^0 * "x" + "cde" + "aka", "cde") == 4)
262assert(m.match("ab" + m.S"abc" * m.P"y"^0 * "x" + "ide" + m.S"ab" * "ka", "aka") == 4)
263assert(m.match("ab" + m.S"abc" * m.P"y"^0 * "x" + "ide" + m.S"ab" * "ka", "ax") == 3)
264assert(m.match(m.P(1) * "x" + "cde" + m.S"ab" * "ka", "aka") == 4)
265assert(m.match(m.P(1) * "x" + "cde" + m.P(1) * "ka", "aka") == 4)
266assert(m.match(m.P(1) * "x" + "cde" + m.P(1) * "ka", "cde") == 4)
267assert(m.match(m.P"eb" + "cd" + m.P"e"^0 + "x", "ee") == 3)
268assert(m.match(m.P"ab" + "cd" + m.P"e"^0 + "x", "abcd") == 3)
269assert(m.match(m.P"ab" + "cd" + m.P"e"^0 + "x", "eeex") == 4)
270assert(m.match(m.P"ab" + "cd" + m.P"e"^0 + "x", "cd") == 3)
271assert(m.match(m.P"ab" + "cd" + m.P"e"^0 + "x", "x") == 1)
272assert(m.match(m.P"ab" + "cd" + m.P"e"^0 + "x" + "", "zee") == 1)
273assert(m.match(m.P"ab" + "cd" + m.P"e"^1 + "x", "abcd") == 3)
274assert(m.match(m.P"ab" + "cd" + m.P"e"^1 + "x", "eeex") == 4)
275assert(m.match(m.P"ab" + "cd" + m.P"e"^1 + "x", "cd") == 3)
276assert(m.match(m.P"ab" + "cd" + m.P"e"^1 + "x", "x") == 2)
277assert(m.match(m.P"ab" + "cd" + m.P"e"^1 + "x" + "", "zee") == 1)
278assert(not m.match(("aa" * m.P"bc"^-1 + "aab") * "e", "aabe"))
279
280assert(m.match("alo" * (m.P"\n" + -1), "alo") == 4)
281
282
283-- bug in 0.12 (rc1)
284assert(m.match((m.P"\128\187\191" + m.S"abc")^0, "\128\187\191") == 4)
285
286assert(m.match(m.S"\0\128\255\127"^0, string.rep("\0\128\255\127", 10)) ==
287 4*10 + 1)
288
289-- optimizations with optional parts
290assert(m.match(("ab" * -m.P"c")^-1, "abc") == 1)
291assert(m.match(("ab" * #m.P"c")^-1, "abd") == 1)
292assert(m.match(("ab" * m.B"c")^-1, "ab") == 1)
293assert(m.match(("ab" * m.P"cd"^0)^-1, "abcdcdc") == 7)
294
295assert(m.match(m.P"ab"^-1 - "c", "abcd") == 3)
296
297p = ('Aa' * ('Bb' * ('Cc' * m.P'Dd'^0)^0)^0)^-1
298assert(p:match("AaBbCcDdBbCcDdDdDdBb") == 21)
299
300
301-- bug in 0.12.2
302-- p = { ('ab' ('c' 'ef'?)*)? }
303p = m.C(('ab' * ('c' * m.P'ef'^-1)^0)^-1)
304s = "abcefccefc"
305assert(s == p:match(s))
306
307
308pi = "3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510"
309assert(m.match(m.Cs((m.P"1" / "a" + m.P"5" / "b" + m.P"9" / "c" + 1)^0), pi) ==
310 m.match(m.Cs((m.P(1) / {["1"] = "a", ["5"] = "b", ["9"] = "c"})^0), pi))
311print"+"
312
313
314-- tests for capture optimizations
315assert(m.match((m.P(3) + 4 * m.Cp()) * "a", "abca") == 5)
316t = {m.match(((m.P"a" + m.Cp()) * m.P"x")^0, "axxaxx")}
317checkeq(t, {3, 6})
318
319
320-- tests for numbered captures
321p = m.C(1)
322assert(m.match(m.C(m.C(p * m.C(2)) * m.C(3)) / 3, "abcdefgh") == "a")
323assert(m.match(m.C(m.C(p * m.C(2)) * m.C(3)) / 1, "abcdefgh") == "abcdef")
324assert(m.match(m.C(m.C(p * m.C(2)) * m.C(3)) / 4, "abcdefgh") == "bc")
325assert(m.match(m.C(m.C(p * m.C(2)) * m.C(3)) / 0, "abcdefgh") == 7)
326
327a, b, c = m.match(p * (m.C(p * m.C(2)) * m.C(3) / 4) * p, "abcdefgh")
328assert(a == "a" and b == "efg" and c == "h")
329
330-- test for table captures
331t = m.match(m.Ct(letter^1), "alo")
332checkeq(t, {})
333
334t, n = m.match(m.Ct(m.C(letter)^1) * m.Cc"t", "alo")
335assert(n == "t" and table.concat(t) == "alo")
336
337t = m.match(m.Ct(m.C(m.C(letter)^1)), "alo")
338assert(table.concat(t, ";") == "alo;a;l;o")
339
340t = m.match(m.Ct(m.C(m.C(letter)^1)), "alo")
341assert(table.concat(t, ";") == "alo;a;l;o")
342
343t = m.match(m.Ct(m.Ct((m.Cp() * letter * m.Cp())^1)), "alo")
344assert(table.concat(t[1], ";") == "1;2;2;3;3;4")
345
346t = m.match(m.Ct(m.C(m.C(1) * 1 * m.C(1))), "alo")
347checkeq(t, {"alo", "a", "o"})
348
349
350-- tests for groups
351p = m.Cg(1) -- no capture
352assert(p:match('x') == 'x')
353p = m.Cg(m.P(true)/function () end * 1) -- no value
354assert(p:match('x') == 'x')
355p = m.Cg(m.Cg(m.Cg(m.C(1))))
356assert(p:match('x') == 'x')
357p = m.Cg(m.Cg(m.Cg(m.C(1))^0) * m.Cg(m.Cc(1) * m.Cc(2)))
358t = {p:match'abc'}
359checkeq(t, {'a', 'b', 'c', 1, 2})
360
361p = m.Ct(m.Cg(m.Cc(10), "hi") * m.C(1)^0 * m.Cg(m.Cc(20), "ho"))
362t = p:match''
363checkeq(t, {hi = 10, ho = 20})
364t = p:match'abc'
365checkeq(t, {hi = 10, ho = 20, 'a', 'b', 'c'})
366
367-- non-string group names
368p = m.Ct(m.Cg(1, print) * m.Cg(1, 23.5) * m.Cg(1, io))
369t = p:match('abcdefghij')
370assert(t[print] == 'a' and t[23.5] == 'b' and t[io] == 'c')
371
372
373-- test for error messages
374local function checkerr (msg, f, ...)
375 local st, err = pcall(f, ...)
376 assert(not st and m.match({ m.P(msg) + 1 * m.V(1) }, err))
377end
378
379checkerr("rule '1' may be left recursive", m.match, { m.V(1) * 'a' }, "a")
380checkerr("rule '1' used outside a grammar", m.match, m.V(1), "")
381checkerr("rule 'hiii' used outside a grammar", m.match, m.V('hiii'), "")
382checkerr("rule 'hiii' undefined in given grammar", m.match, { m.V('hiii') }, "")
383checkerr("undefined in given grammar", m.match, { m.V{} }, "")
384
385checkerr("rule 'A' is not a pattern", m.P, { m.P(1), A = {} })
386checkerr("grammar has no initial rule", m.P, { [print] = {} })
387
388-- grammar with a long call chain before left recursion
389p = {'a',
390 a = m.V'b' * m.V'c' * m.V'd' * m.V'a',
391 b = m.V'c',
392 c = m.V'd',
393 d = m.V'e',
394 e = m.V'f',
395 f = m.V'g',
396 g = m.P''
397}
398checkerr("rule 'a' may be left recursive", m.match, p, "a")
399
400-- Bug in peephole optimization of LPeg 0.12 (IJmp -> ICommit)
401-- the next grammar has an original sequence IJmp -> ICommit -> IJmp L1
402-- that is optimized to ICommit L1
403
404p = m.P { (m.P {m.P'abc'} + 'ayz') * m.V'y'; y = m.P'x' }
405assert(p:match('abcx') == 5 and p:match('ayzx') == 5 and not p:match'abc')
406
407
408do
409 -- large dynamic Cc
410 local lim = 2^16 - 1
411 local c = 0
412 local function seq (n)
413 if n == 1 then c = c + 1; return m.Cc(c)
414 else
415 local m = math.floor(n / 2)
416 return seq(m) * seq(n - m)
417 end
418 end
419 p = m.Ct(seq(lim))
420 t = p:match('')
421 assert(t[lim] == lim)
422 checkerr("too many", function () p = p / print end)
423 checkerr("too many", seq, lim + 1)
424end
425
426
427-- tests for non-pattern as arguments to pattern functions
428
429p = { ('a' * m.V(1))^-1 } * m.P'b' * { 'a' * m.V(2); m.V(1)^-1 }
430assert(m.match(p, "aaabaac") == 7)
431
432p = m.P'abc' * 2 * -5 * true * 'de' -- mix of numbers and strings and booleans
433
434assert(p:match("abc01de") == 8)
435assert(p:match("abc01de3456") == nil)
436
437p = 'abc' * (2 * (-5 * (true * m.P'de')))
438
439assert(p:match("abc01de") == 8)
440assert(p:match("abc01de3456") == nil)
441
442p = { m.V(2), m.P"abc" } *
443 (m.P{ "xx", xx = m.P"xx" } + { "x", x = m.P"a" * m.V"x" + "" })
444assert(p:match("abcaaaxx") == 7)
445assert(p:match("abcxx") == 6)
446
447
448-- a large table capture
449t = m.match(m.Ct(m.C('a')^0), string.rep("a", 10000))
450assert(#t == 10000 and t[1] == 'a' and t[#t] == 'a')
451
452print('+')
453
454
455-- bug in 0.10 (rechecking a grammar, after tail-call optimization)
456m.P{ m.P { (m.P(3) + "xuxu")^0 * m.V"xuxu", xuxu = m.P(1) } }
457
458local V = m.V
459
460local Space = m.S(" \n\t")^0
461local Number = m.C(m.R("09")^1) * Space
462local FactorOp = m.C(m.S("+-")) * Space
463local TermOp = m.C(m.S("*/")) * Space
464local Open = "(" * Space
465local Close = ")" * Space
466
467
468local function f_factor (v1, op, v2, d)
469 assert(d == nil)
470 if op == "+" then return v1 + v2
471 else return v1 - v2
472 end
473end
474
475
476local function f_term (v1, op, v2, d)
477 assert(d == nil)
478 if op == "*" then return v1 * v2
479 else return v1 / v2
480 end
481end
482
483G = m.P{ "Exp",
484 Exp = m.Cf(V"Factor" * m.Cg(FactorOp * V"Factor")^0, f_factor);
485 Factor = m.Cf(V"Term" * m.Cg(TermOp * V"Term")^0, f_term);
486 Term = Number / tonumber + Open * V"Exp" * Close;
487}
488
489G = Space * G * -1
490
491for _, s in ipairs{" 3 + 5*9 / (1+1) ", "3+4/2", "3+3-3- 9*2+3*9/1- 8"} do
492 assert(m.match(G, s) == loadstring("return "..s)())
493end
494
495
496-- test for grammars (errors deep in calling non-terminals)
497g = m.P{
498 [1] = m.V(2) + "a",
499 [2] = "a" * m.V(3) * "x",
500 [3] = "b" * m.V(3) + "c"
501}
502
503assert(m.match(g, "abbbcx") == 7)
504assert(m.match(g, "abbbbx") == 2)
505
506
507-- tests for \0
508assert(m.match(m.R("\0\1")^1, "\0\1\0") == 4)
509assert(m.match(m.S("\0\1ab")^1, "\0\1\0a") == 5)
510assert(m.match(m.P(1)^3, "\0\1\0a") == 5)
511assert(not m.match(-4, "\0\1\0a"))
512assert(m.match("\0\1\0a", "\0\1\0a") == 5)
513assert(m.match("\0\0\0", "\0\0\0") == 4)
514assert(not m.match("\0\0\0", "\0\0"))
515
516
517-- tests for predicates
518assert(not m.match(-m.P("a") * 2, "alo"))
519assert(m.match(- -m.P("a") * 2, "alo") == 3)
520assert(m.match(#m.P("a") * 2, "alo") == 3)
521assert(m.match(##m.P("a") * 2, "alo") == 3)
522assert(not m.match(##m.P("c") * 2, "alo"))
523assert(m.match(m.Cs((##m.P("a") * 1 + m.P(1)/".")^0), "aloal") == "a..a.")
524assert(m.match(m.Cs((#((#m.P"a")/"") * 1 + m.P(1)/".")^0), "aloal") == "a..a.")
525assert(m.match(m.Cs((- -m.P("a") * 1 + m.P(1)/".")^0), "aloal") == "a..a.")
526assert(m.match(m.Cs((-((-m.P"a")/"") * 1 + m.P(1)/".")^0), "aloal") == "a..a.")
527
528
529-- fixed length
530do
531 -- 'and' predicate using fixed length
532 local p = m.C(#("a" * (m.P("bd") + "cd")) * 2)
533 assert(p:match("acd") == "ac")
534
535 p = #m.P{ "a" * m.V(2), m.P"b" } * 2
536 assert(p:match("abc") == 3)
537
538 p = #(m.P"abc" * m.B"c")
539 assert(p:match("abc") == 1 and not p:match("ab"))
540
541 p = m.P{ "a" * m.V(2), m.P"b"^1 }
542 checkerr("pattern may not have fixed length", m.B, p)
543
544 p = "abc" * (m.P"b"^1 + m.P"a"^0)
545 checkerr("pattern may not have fixed length", m.B, p)
546end
547
548
549p = -m.P'a' * m.Cc(1) + -m.P'b' * m.Cc(2) + -m.P'c' * m.Cc(3)
550assert(p:match('a') == 2 and p:match('') == 1 and p:match('b') == 1)
551
552p = -m.P'a' * m.Cc(10) + #m.P'a' * m.Cc(20)
553assert(p:match('a') == 20 and p:match('') == 10 and p:match('b') == 10)
554
555
556
557-- look-behind predicate
558assert(not m.match(m.B'a', 'a'))
559assert(m.match(1 * m.B'a', 'a') == 2)
560assert(not m.match(m.B(1), 'a'))
561assert(m.match(1 * m.B(1), 'a') == 2)
562assert(m.match(-m.B(1), 'a') == 1)
563assert(m.match(m.B(250), string.rep('a', 250)) == nil)
564assert(m.match(250 * m.B(250), string.rep('a', 250)) == 251)
565
566-- look-behind with an open call
567checkerr("pattern may not have fixed length", m.B, m.V'S1')
568checkerr("too long to look behind", m.B, 260)
569
570B = #letter * -m.B(letter) + -letter * m.B(letter)
571x = m.Ct({ (B * m.Cp())^-1 * (1 * m.V(1) + m.P(true)) })
572checkeq(m.match(x, 'ar cal c'), {1,3,4,7,9,10})
573checkeq(m.match(x, ' ar cal '), {2,4,5,8})
574checkeq(m.match(x, ' '), {})
575checkeq(m.match(x, 'aloalo'), {1,7})
576
577assert(m.match(B, "a") == 1)
578assert(m.match(1 * B, "a") == 2)
579assert(not m.B(1 - letter):match(""))
580assert((-m.B(letter)):match("") == 1)
581
582assert((4 * m.B(letter, 4)):match("aaaaaaaa") == 5)
583assert(not (4 * m.B(#letter * 5)):match("aaaaaaaa"))
584assert((4 * -m.B(#letter * 5)):match("aaaaaaaa") == 5)
585
586-- look-behind with grammars
587assert(m.match('a' * m.B{'x', x = m.P(3)}, 'aaa') == nil)
588assert(m.match('aa' * m.B{'x', x = m.P('aaa')}, 'aaaa') == nil)
589assert(m.match('aaa' * m.B{'x', x = m.P('aaa')}, 'aaaaa') == 4)
590
591
592
593-- bug in 0.9
594assert(m.match(('a' * #m.P'b'), "ab") == 2)
595assert(not m.match(('a' * #m.P'b'), "a"))
596
597assert(not m.match(#m.S'567', ""))
598assert(m.match(#m.S'567' * 1, "6") == 2)
599
600
601-- tests for Tail Calls
602
603p = m.P{ 'a' * m.V(1) + '' }
604assert(p:match(string.rep('a', 1000)) == 1001)
605
606-- create a grammar for a simple DFA for even number of 0s and 1s
607--
608-- ->1 <---0---> 2
609-- ^ ^
610-- | |
611-- 1 1
612-- | |
613-- V V
614-- 3 <---0---> 4
615--
616-- this grammar should keep no backtracking information
617
618p = m.P{
619 [1] = '0' * m.V(2) + '1' * m.V(3) + -1,
620 [2] = '0' * m.V(1) + '1' * m.V(4),
621 [3] = '0' * m.V(4) + '1' * m.V(1),
622 [4] = '0' * m.V(3) + '1' * m.V(2),
623}
624
625assert(p:match(string.rep("00", 10000)))
626assert(p:match(string.rep("01", 10000)))
627assert(p:match(string.rep("011", 10000)))
628assert(not p:match(string.rep("011", 10000) .. "1"))
629assert(not p:match(string.rep("011", 10001)))
630
631
632-- this grammar does need backtracking info.
633local lim = 10000
634p = m.P{ '0' * m.V(1) + '0' }
635checkerr("stack overflow", m.match, p, string.rep("0", lim))
636m.setmaxstack(2*lim)
637checkerr("stack overflow", m.match, p, string.rep("0", lim))
638m.setmaxstack(2*lim + 4)
639assert(m.match(p, string.rep("0", lim)) == lim + 1)
640
641-- this repetition should not need stack space (only the call does)
642p = m.P{ ('a' * m.V(1))^0 * 'b' + 'c' }
643m.setmaxstack(200)
644assert(p:match(string.rep('a', 180) .. 'c' .. string.rep('b', 180)) == 362)
645
646m.setmaxstack(100) -- restore low limit
647
648-- tests for optional start position
649assert(m.match("a", "abc", 1))
650assert(m.match("b", "abc", 2))
651assert(m.match("c", "abc", 3))
652assert(not m.match(1, "abc", 4))
653assert(m.match("a", "abc", -3))
654assert(m.match("b", "abc", -2))
655assert(m.match("c", "abc", -1))
656assert(m.match("abc", "abc", -4)) -- truncate to position 1
657
658assert(m.match("", "abc", 10)) -- empty string is everywhere!
659assert(m.match("", "", 10))
660assert(not m.match(1, "", 1))
661assert(not m.match(1, "", -1))
662assert(not m.match(1, "", 0))
663
664print("+")
665
666
667-- tests for argument captures
668checkerr("invalid argument", m.Carg, 0)
669checkerr("invalid argument", m.Carg, -1)
670checkerr("invalid argument", m.Carg, 2^18)
671checkerr("absent extra argument #1", m.match, m.Carg(1), 'a', 1)
672assert(m.match(m.Carg(1), 'a', 1, print) == print)
673x = {m.match(m.Carg(1) * m.Carg(2), '', 1, 10, 20)}
674checkeq(x, {10, 20})
675
676assert(m.match(m.Cmt(m.Cg(m.Carg(3), "a") *
677 m.Cmt(m.Cb("a"), function (s,i,x)
678 assert(s == "a" and i == 1);
679 return i, x+1
680 end) *
681 m.Carg(2), function (s,i,a,b,c)
682 assert(s == "a" and i == 1 and c == nil);
683 return i, 2*a + 3*b
684 end) * "a",
685 "a", 1, false, 100, 1000) == 2*1001 + 3*100)
686
687
688-- tests for Lua functions
689
690t = {}
691s = ""
692p = m.P(function (s1, i) assert(s == s1); t[#t + 1] = i; return nil end) * false
693s = "hi, this is a test"
694assert(m.match(((p - m.P(-1)) + 2)^0, s) == string.len(s) + 1)
695assert(#t == string.len(s)/2 and t[1] == 1 and t[2] == 3)
696
697assert(not m.match(p, s))
698
699p = mt.__add(function (s, i) return i end, function (s, i) return nil end)
700assert(m.match(p, "alo"))
701
702p = mt.__mul(function (s, i) return i end, function (s, i) return nil end)
703assert(not m.match(p, "alo"))
704
705
706t = {}
707p = function (s1, i) assert(s == s1); t[#t + 1] = i; return i end
708s = "hi, this is a test"
709assert(m.match((m.P(1) * p)^0, s) == string.len(s) + 1)
710assert(#t == string.len(s) and t[1] == 2 and t[2] == 3)
711
712t = {}
713p = m.P(function (s1, i) assert(s == s1); t[#t + 1] = i;
714 return i <= s1:len() and i end) * 1
715s = "hi, this is a test"
716assert(m.match(p^0, s) == string.len(s) + 1)
717assert(#t == string.len(s) + 1 and t[1] == 1 and t[2] == 2)
718
719p = function (s1, i) return m.match(m.P"a"^1, s1, i) end
720assert(m.match(p, "aaaa") == 5)
721assert(m.match(p, "abaa") == 2)
722assert(not m.match(p, "baaa"))
723
724checkerr("invalid position", m.match, function () return 2^20 end, s)
725checkerr("invalid position", m.match, function () return 0 end, s)
726checkerr("invalid position", m.match, function (s, i) return i - 1 end, s)
727checkerr("invalid position", m.match,
728 m.P(1)^0 * function (_, i) return i - 1 end, s)
729assert(m.match(m.P(1)^0 * function (_, i) return i end * -1, s))
730checkerr("invalid position", m.match,
731 m.P(1)^0 * function (_, i) return i + 1 end, s)
732assert(m.match(m.P(function (s, i) return s:len() + 1 end) * -1, s))
733checkerr("invalid position", m.match, m.P(function (s, i) return s:len() + 2 end) * -1, s)
734assert(not m.match(m.P(function (s, i) return s:len() end) * -1, s))
735assert(m.match(m.P(1)^0 * function (_, i) return true end, s) ==
736 string.len(s) + 1)
737for i = 1, string.len(s) + 1 do
738 assert(m.match(function (_, _) return i end, s) == i)
739end
740
741p = (m.P(function (s, i) return i%2 == 0 and i end) * 1
742 + m.P(function (s, i) return i%2 ~= 0 and i + 2 <= s:len() and i end) * 3)^0
743 * -1
744assert(p:match(string.rep('a', 14000)))
745
746-- tests for Function Replacements
747f = function (a, ...) if a ~= "x" then return {a, ...} end end
748
749t = m.match(m.C(1)^0/f, "abc")
750checkeq(t, {"a", "b", "c"})
751
752t = m.match(m.C(1)^0/f/f, "abc")
753checkeq(t, {{"a", "b", "c"}})
754
755t = m.match(m.P(1)^0/f/f, "abc") -- no capture
756checkeq(t, {{"abc"}})
757
758t = m.match((m.P(1)^0/f * m.Cp())/f, "abc")
759checkeq(t, {{"abc"}, 4})
760
761t = m.match((m.C(1)^0/f * m.Cp())/f, "abc")
762checkeq(t, {{"a", "b", "c"}, 4})
763
764t = m.match((m.C(1)^0/f * m.Cp())/f, "xbc")
765checkeq(t, {4})
766
767t = m.match(m.C(m.C(1)^0)/f, "abc")
768checkeq(t, {"abc", "a", "b", "c"})
769
770g = function (...) return 1, ... end
771t = {m.match(m.C(1)^0/g/g, "abc")}
772checkeq(t, {1, 1, "a", "b", "c"})
773
774t = {m.match(m.Cc(nil,nil,4) * m.Cc(nil,3) * m.Cc(nil, nil) / g / g, "")}
775t1 = {1,1,nil,nil,4,nil,3,nil,nil}
776for i=1,10 do assert(t[i] == t1[i]) end
777
778-- bug in 0.12.2: ktable with only nil could be eliminated when joining
779-- with a pattern without ktable
780assert((m.P"aaa" * m.Cc(nil)):match"aaa" == nil)
781
782t = {m.match((m.C(1) / function (x) return x, x.."x" end)^0, "abc")}
783checkeq(t, {"a", "ax", "b", "bx", "c", "cx"})
784
785t = m.match(m.Ct((m.C(1) / function (x,y) return y, x end * m.Cc(1))^0), "abc")
786checkeq(t, {nil, "a", 1, nil, "b", 1, nil, "c", 1})
787
788-- tests for Query Replacements
789
790assert(m.match(m.C(m.C(1)^0)/{abc = 10}, "abc") == 10)
791assert(m.match(m.C(1)^0/{a = 10}, "abc") == 10)
792assert(m.match(m.S("ba")^0/{ab = 40}, "abc") == 40)
793t = m.match(m.Ct((m.S("ba")/{a = 40})^0), "abc")
794checkeq(t, {40})
795
796assert(m.match(m.Cs((m.C(1)/{a=".", d=".."})^0), "abcdde") == ".bc....e")
797assert(m.match(m.Cs((m.C(1)/{f="."})^0), "abcdde") == "abcdde")
798assert(m.match(m.Cs((m.C(1)/{d="."})^0), "abcdde") == "abc..e")
799assert(m.match(m.Cs((m.C(1)/{e="."})^0), "abcdde") == "abcdd.")
800assert(m.match(m.Cs((m.C(1)/{e=".", f="+"})^0), "eefef") == "..+.+")
801assert(m.match(m.Cs((m.C(1))^0), "abcdde") == "abcdde")
802assert(m.match(m.Cs(m.C(m.C(1)^0)), "abcdde") == "abcdde")
803assert(m.match(1 * m.Cs(m.P(1)^0), "abcdde") == "bcdde")
804assert(m.match(m.Cs((m.C('0')/'x' + 1)^0), "abcdde") == "abcdde")
805assert(m.match(m.Cs((m.C('0')/'x' + 1)^0), "0ab0b0") == "xabxbx")
806assert(m.match(m.Cs((m.C('0')/'x' + m.P(1)/{b=3})^0), "b0a0b") == "3xax3")
807assert(m.match(m.P(1)/'%0%0'/{aa = -3} * 'x', 'ax') == -3)
808assert(m.match(m.C(1)/'%0%1'/{aa = 'z'}/{z = -3} * 'x', 'ax') == -3)
809
810assert(m.match(m.Cs(m.Cc(0) * (m.P(1)/"")), "4321") == "0")
811
812assert(m.match(m.Cs((m.P(1) / "%0")^0), "abcd") == "abcd")
813assert(m.match(m.Cs((m.P(1) / "%0.%0")^0), "abcd") == "a.ab.bc.cd.d")
814assert(m.match(m.Cs((m.P("a") / "%0.%0" + 1)^0), "abcad") == "a.abca.ad")
815assert(m.match(m.C("a") / "%1%%%0", "a") == "a%a")
816assert(m.match(m.Cs((m.P(1) / ".xx")^0), "abcd") == ".xx.xx.xx.xx")
817assert(m.match(m.Cp() * m.P(3) * m.Cp()/"%2%1%1 - %0 ", "abcde") ==
818 "411 - abc ")
819
820assert(m.match(m.P(1)/"%0", "abc") == "a")
821checkerr("invalid capture index", m.match, m.P(1)/"%1", "abc")
822checkerr("invalid capture index", m.match, m.P(1)/"%9", "abc")
823
824p = m.C(1)
825p = p * p; p = p * p; p = p * p * m.C(1) / "%9 - %1"
826assert(p:match("1234567890") == "9 - 1")
827
828assert(m.match(m.Cc(print), "") == print)
829
830-- too many captures (just ignore extra ones)
831p = m.C(1)^0 / "%2-%9-%0-%9"
832assert(p:match"01234567890123456789" == "1-8-01234567890123456789-8")
833s = string.rep("12345678901234567890", 20)
834assert(m.match(m.C(1)^0 / "%9-%1-%0-%3", s) == "9-1-" .. s .. "-3")
835
836-- string captures with non-string subcaptures
837p = m.Cc('alo') * m.C(1) / "%1 - %2 - %1"
838assert(p:match'x' == 'alo - x - alo')
839
840checkerr("invalid capture value (a boolean)", m.match, m.Cc(true) / "%1", "a")
841
842-- long strings for string capture
843l = 10000
844s = string.rep('a', l) .. string.rep('b', l) .. string.rep('c', l)
845
846p = (m.C(m.P'a'^1) * m.C(m.P'b'^1) * m.C(m.P'c'^1)) / '%3%2%1'
847
848assert(p:match(s) == string.rep('c', l) ..
849 string.rep('b', l) ..
850 string.rep('a', l))
851
852print"+"
853
854-- accumulator capture
855function f (x) return x + 1 end
856assert(m.match(m.Cf(m.Cc(0) * m.C(1)^0, f), "alo alo") == 7)
857
858t = {m.match(m.Cf(m.Cc(1,2,3), error), "")}
859checkeq(t, {1})
860p = m.Cf(m.Ct(true) * m.Cg(m.C(m.R"az"^1) * "=" * m.C(m.R"az"^1) * ";")^0,
861 rawset)
862t = p:match("a=b;c=du;xux=yuy;")
863checkeq(t, {a="b", c="du", xux="yuy"})
864
865
866-- errors in accumulator capture
867
868-- no initial capture
869checkerr("no initial value", m.match, m.Cf(m.P(5), print), 'aaaaaa')
870-- no initial capture (very long match forces fold to be a pair open-close)
871checkerr("no initial value", m.match, m.Cf(m.P(500), print),
872 string.rep('a', 600))
873
874-- nested capture produces no initial value
875checkerr("no initial value", m.match, m.Cf(m.P(1) / {}, print), "alo")
876
877
878-- tests for loop checker
879
880local function isnullable (p)
881 checkerr("may accept empty string", function (p) return p^0 end, m.P(p))
882end
883
884isnullable(m.P("x")^-4)
885assert(m.match(((m.P(0) + 1) * m.S"al")^0, "alo") == 3)
886assert(m.match((("x" + #m.P(1))^-4 * m.S"al")^0, "alo") == 3)
887isnullable("")
888isnullable(m.P("x")^0)
889isnullable(m.P("x")^-1)
890isnullable(m.P("x") + 1 + 2 + m.P("a")^-1)
891isnullable(-m.P("ab"))
892isnullable(- -m.P("ab"))
893isnullable(# #(m.P("ab") + "xy"))
894isnullable(- #m.P("ab")^0)
895isnullable(# -m.P("ab")^1)
896isnullable(#m.V(3))
897isnullable(m.V(3) + m.V(1) + m.P('a')^-1)
898isnullable({[1] = m.V(2) * m.V(3), [2] = m.V(3), [3] = m.P(0)})
899assert(m.match(m.P{[1] = m.V(2) * m.V(3), [2] = m.V(3), [3] = m.P(1)}^0, "abc")
900 == 3)
901assert(m.match(m.P""^-3, "a") == 1)
902
903local function find (p, s)
904 return m.match(basiclookfor(p), s)
905end
906
907
908local function badgrammar (g, expected)
909 local stat, msg = pcall(m.P, g)
910 assert(not stat)
911 if expected then assert(find(expected, msg)) end
912end
913
914badgrammar({[1] = m.V(1)}, "rule '1'")
915badgrammar({[1] = m.V(2)}, "rule '2'") -- invalid non-terminal
916badgrammar({[1] = m.V"x"}, "rule 'x'") -- invalid non-terminal
917badgrammar({[1] = m.V{}}, "rule '(a table)'") -- invalid non-terminal
918badgrammar({[1] = #m.P("a") * m.V(1)}, "rule '1'") -- left-recursive
919badgrammar({[1] = -m.P("a") * m.V(1)}, "rule '1'") -- left-recursive
920badgrammar({[1] = -1 * m.V(1)}, "rule '1'") -- left-recursive
921badgrammar({[1] = -1 + m.V(1)}, "rule '1'") -- left-recursive
922badgrammar({[1] = 1 * m.V(2), [2] = m.V(2)}, "rule '2'") -- left-recursive
923badgrammar({[1] = 1 * m.V(2)^0, [2] = m.P(0)}, "rule '1'") -- inf. loop
924badgrammar({ m.V(2), m.V(3)^0, m.P"" }, "rule '2'") -- inf. loop
925badgrammar({ m.V(2) * m.V(3)^0, m.V(3)^0, m.P"" }, "rule '1'") -- inf. loop
926badgrammar({"x", x = #(m.V(1) * 'a') }, "rule '1'") -- inf. loop
927badgrammar({ -(m.V(1) * 'a') }, "rule '1'") -- inf. loop
928badgrammar({"x", x = m.P'a'^-1 * m.V"x"}, "rule 'x'") -- left recursive
929badgrammar({"x", x = m.P'a' * m.V"y"^1, y = #m.P(1)}, "rule 'x'")
930
931assert(m.match({'a' * -m.V(1)}, "aaa") == 2)
932assert(m.match({'a' * -m.V(1)}, "aaaa") == nil)
933
934
935-- good x bad grammars
936m.P{ ('a' * m.V(1))^-1 }
937m.P{ -('a' * m.V(1)) }
938m.P{ ('abc' * m.V(1))^-1 }
939m.P{ -('abc' * m.V(1)) }
940badgrammar{ #m.P('abc') * m.V(1) }
941badgrammar{ -('a' + m.V(1)) }
942m.P{ #('a' * m.V(1)) }
943badgrammar{ #('a' + m.V(1)) }
944m.P{ m.B{ m.P'abc' } * 'a' * m.V(1) }
945badgrammar{ m.B{ m.P'abc' } * m.V(1) }
946badgrammar{ ('a' + m.P'bcd')^-1 * m.V(1) }
947
948
949-- simple tests for maximum sizes:
950local p = m.P"a"
951for i=1,14 do p = p * p end
952
953p = {}
954for i=1,100 do p[i] = m.P"a" end
955p = m.P(p)
956
957
958-- strange values for rule labels
959
960p = m.P{ "print",
961 print = m.V(print),
962 [print] = m.V(_G),
963 [_G] = m.P"a",
964 }
965
966assert(p:match("a"))
967
968-- initial rule
969g = {}
970for i = 1, 10 do g["i"..i] = "a" * m.V("i"..i+1) end
971g.i11 = m.P""
972for i = 1, 10 do
973 g[1] = "i"..i
974 local p = m.P(g)
975 assert(p:match("aaaaaaaaaaa") == 11 - i + 1)
976end
977
978print"+"
979
980
981-- tests for back references
982checkerr("back reference 'x' not found", m.match, m.Cb('x'), '')
983checkerr("back reference 'b' not found", m.match, m.Cg(1, 'a') * m.Cb('b'), 'a')
984
985p = m.Cg(m.C(1) * m.C(1), "k") * m.Ct(m.Cb("k"))
986t = p:match("ab")
987checkeq(t, {"a", "b"})
988
989p = m.P(true)
990for i = 1, 10 do p = p * m.Cg(1, i) end
991for i = 1, 10 do
992 local p = p * m.Cb(i)
993 assert(p:match('abcdefghij') == string.sub('abcdefghij', i, i))
994end
995
996
997t = {}
998function foo (p) t[#t + 1] = p; return p .. "x" end
999
1000p = m.Cg(m.C(2) / foo, "x") * m.Cb"x" *
1001 m.Cg(m.Cb('x') / foo, "x") * m.Cb"x" *
1002 m.Cg(m.Cb('x') / foo, "x") * m.Cb"x" *
1003 m.Cg(m.Cb('x') / foo, "x") * m.Cb"x"
1004x = {p:match'ab'}
1005checkeq(x, {'abx', 'abxx', 'abxxx', 'abxxxx'})
1006checkeq(t, {'ab',
1007 'ab', 'abx',
1008 'ab', 'abx', 'abxx',
1009 'ab', 'abx', 'abxx', 'abxxx'})
1010
1011
1012
1013-- tests for match-time captures
1014
1015p = m.P'a' * (function (s, i) return (s:sub(i, i) == 'b') and i + 1 end)
1016 + 'acd'
1017
1018assert(p:match('abc') == 3)
1019assert(p:match('acd') == 4)
1020
1021local function id (s, i, ...)
1022 return true, ...
1023end
1024
1025assert(m.Cmt(m.Cs((m.Cmt(m.S'abc' / { a = 'x', c = 'y' }, id) +
1026 m.R'09'^1 / string.char +
1027 m.P(1))^0), id):match"acb98+68c" == "xyb\98+\68y")
1028
1029p = m.P{'S',
1030 S = m.V'atom' * space
1031 + m.Cmt(m.Ct("(" * space * (m.Cmt(m.V'S'^1, id) + m.P(true)) * ")" * space), id),
1032 atom = m.Cmt(m.C(m.R("AZ", "az", "09")^1), id)
1033}
1034x = p:match"(a g () ((b) c) (d (e)))"
1035checkeq(x, {'a', 'g', {}, {{'b'}, 'c'}, {'d', {'e'}}});
1036
1037x = {(m.Cmt(1, id)^0):match(string.rep('a', 500))}
1038assert(#x == 500)
1039
1040local function id(s, i, x)
1041 if x == 'a' then return i, 1, 3, 7
1042 else return nil, 2, 4, 6, 8
1043 end
1044end
1045
1046p = ((m.P(id) * 1 + m.Cmt(2, id) * 1 + m.Cmt(1, id) * 1))^0
1047assert(table.concat{p:match('abababab')} == string.rep('137', 4))
1048
1049local function ref (s, i, x)
1050 return m.match(x, s, i - x:len())
1051end
1052
1053assert(m.Cmt(m.P(1)^0, ref):match('alo') == 4)
1054assert((m.P(1) * m.Cmt(m.P(1)^0, ref)):match('alo') == 4)
1055assert(not (m.P(1) * m.Cmt(m.C(1)^0, ref)):match('alo'))
1056
1057ref = function (s,i,x) return i == tonumber(x) and i, 'xuxu' end
1058
1059assert(m.Cmt(1, ref):match'2')
1060assert(not m.Cmt(1, ref):match'1')
1061assert(m.Cmt(m.P(1)^0, ref):match'03')
1062
1063function ref (s, i, a, b)
1064 if a == b then return i, a:upper() end
1065end
1066
1067p = m.Cmt(m.C(m.R"az"^1) * "-" * m.C(m.R"az"^1), ref)
1068p = (any - p)^0 * p * any^0 * -1
1069
1070assert(p:match'abbbc-bc ddaa' == 'BC')
1071
1072do -- match-time captures cannot be optimized away
1073 local touch = 0
1074 f = m.P(function () touch = touch + 1; return true end)
1075
1076 local function check(n) n = n or 1; assert(touch == n); touch = 0 end
1077
1078 assert(m.match(f * false + 'b', 'a') == nil); check()
1079 assert(m.match(f * false + 'b', '') == nil); check()
1080 assert(m.match( (f * 'a')^0 * 'b', 'b') == 2); check()
1081 assert(m.match( (f * 'a')^0 * 'b', '') == nil); check()
1082 assert(m.match( (f * 'a')^-1 * 'b', 'b') == 2); check()
1083 assert(m.match( (f * 'a')^-1 * 'b', '') == nil); check()
1084 assert(m.match( ('b' + f * 'a')^-1 * 'b', '') == nil); check()
1085 assert(m.match( (m.P'b'^-1 * f * 'a')^-1 * 'b', '') == nil); check()
1086 assert(m.match( (-m.P(1) * m.P'b'^-1 * f * 'a')^-1 * 'b', '') == nil);
1087 check()
1088 assert(m.match( (f * 'a' + 'b')^-1 * 'b', '') == nil); check()
1089 assert(m.match(f * 'a' + f * 'b', 'b') == 2); check(2)
1090 assert(m.match(f * 'a' + f * 'b', 'a') == 2); check(1)
1091 assert(m.match(-f * 'a' + 'b', 'b') == 2); check(1)
1092 assert(m.match(-f * 'a' + 'b', '') == nil); check(1)
1093end
1094
1095c = '[' * m.Cg(m.P'='^0, "init") * '[' *
1096 { m.Cmt(']' * m.C(m.P'='^0) * ']' * m.Cb("init"), function (_, _, s1, s2)
1097 return s1 == s2 end)
1098 + 1 * m.V(1) } / 0
1099
1100assert(c:match'[==[]]====]]]]==]===[]' == 18)
1101assert(c:match'[[]=]====]=]]]==]===[]' == 14)
1102assert(not c:match'[[]=]====]=]=]==]===[]')
1103
1104
1105-- old bug: optimization of concat with fail removed match-time capture
1106p = m.Cmt(0, function (s) p = s end) * m.P(false)
1107assert(not p:match('alo'))
1108assert(p == 'alo')
1109
1110
1111-- ensure that failed match-time captures are not kept on Lua stack
1112do
1113 local t = {__mode = "kv"}; setmetatable(t,t)
1114 local c = 0
1115
1116 local function foo (s,i)
1117 collectgarbage();
1118 assert(next(t) == "__mode" and next(t, "__mode") == nil)
1119 local x = {}
1120 t[x] = true
1121 c = c + 1
1122 return i, x
1123 end
1124
1125 local p = m.P{ m.Cmt(0, foo) * m.P(false) + m.P(1) * m.V(1) + m.P"" }
1126 p:match(string.rep('1', 10))
1127 assert(c == 11)
1128end
1129
1130
1131-- Return a match-time capture that returns 'n' captures
1132local function manyCmt (n)
1133 return m.Cmt("a", function ()
1134 local a = {}; for i = 1, n do a[i] = n - i end
1135 return true, unpack(a)
1136 end)
1137end
1138
1139-- bug in 1.0: failed match-time that used previous match-time results
1140do
1141 local x
1142 local function aux (...) x = #{...}; return false end
1143 local res = {m.match(m.Cmt(manyCmt(20), aux) + manyCmt(10), "a")}
1144 assert(#res == 10 and res[1] == 9 and res[10] == 0)
1145end
1146
1147
1148-- bug in 1.0: problems with math-times returning too many captures
1149do
1150 local lim = 2^11 - 10
1151 local res = {m.match(manyCmt(lim), "a")}
1152 assert(#res == lim and res[1] == lim - 1 and res[lim] == 0)
1153 checkerr("too many", m.match, manyCmt(2^15), "a")
1154end
1155
1156p = (m.P(function () return true, "a" end) * 'a'
1157 + m.P(function (s, i) return i, "aa", 20 end) * 'b'
1158 + m.P(function (s,i) if i <= #s then return i, "aaa" end end) * 1)^0
1159
1160t = {p:match('abacc')}
1161checkeq(t, {'a', 'aa', 20, 'a', 'aaa', 'aaa'})
1162
1163
1164-------------------------------------------------------------------
1165-- Tests for 're' module
1166-------------------------------------------------------------------
1167
1168local re = require "re"
1169
1170local match, compile = re.match, re.compile
1171
1172
1173
1174assert(match("a", ".") == 2)
1175assert(match("a", "''") == 1)
1176assert(match("", " ! . ") == 1)
1177assert(not match("a", " ! . "))
1178assert(match("abcde", " ( . . ) * ") == 5)
1179assert(match("abbcde", " [a-c] +") == 5)
1180assert(match("0abbc1de", "'0' [a-c]+ '1'") == 7)
1181assert(match("0zz1dda", "'0' [^a-c]+ 'a'") == 8)
1182assert(match("abbc--", " [a-c] + +") == 5)
1183assert(match("abbc--", " [ac-] +") == 2)
1184assert(match("abbc--", " [-acb] + ") == 7)
1185assert(not match("abbcde", " [b-z] + "))
1186assert(match("abb\"de", '"abb"["]"de"') == 7)
1187assert(match("abceeef", "'ac' ? 'ab' * 'c' { 'e' * } / 'abceeef' ") == "eee")
1188assert(match("abceeef", "'ac'? 'ab'* 'c' { 'f'+ } / 'abceeef' ") == 8)
1189
1190assert(re.match("aaand", "[a]^2") == 3)
1191
1192local t = {match("abceefe", "( ( & 'e' {} ) ? . ) * ")}
1193checkeq(t, {4, 5, 7})
1194local t = {match("abceefe", "((&&'e' {})? .)*")}
1195checkeq(t, {4, 5, 7})
1196local t = {match("abceefe", "( ( ! ! 'e' {} ) ? . ) *")}
1197checkeq(t, {4, 5, 7})
1198local t = {match("abceefe", "(( & ! & ! 'e' {})? .)*")}
1199checkeq(t, {4, 5, 7})
1200
1201assert(match("cccx" , "'ab'? ('ccc' / ('cde' / 'cd'*)? / 'ccc') 'x'+") == 5)
1202assert(match("cdx" , "'ab'? ('ccc' / ('cde' / 'cd'*)? / 'ccc') 'x'+") == 4)
1203assert(match("abcdcdx" , "'ab'? ('ccc' / ('cde' / 'cd'*)? / 'ccc') 'x'+") == 8)
1204
1205assert(match("abc", "a <- (. a)?") == 4)
1206b = "balanced <- '(' ([^()] / balanced)* ')'"
1207assert(match("(abc)", b))
1208assert(match("(a(b)((c) (d)))", b))
1209assert(not match("(a(b ((c) (d)))", b))
1210
1211b = compile[[ balanced <- "(" ([^()] / balanced)* ")" ]]
1212assert(b == m.P(b))
1213assert(b:match"((((a))(b)))")
1214
1215local g = [[
1216 S <- "0" B / "1" A / "" -- balanced strings
1217 A <- "0" S / "1" A A -- one more 0
1218 B <- "1" S / "0" B B -- one more 1
1219]]
1220assert(match("00011011", g) == 9)
1221
1222local g = [[
1223 S <- ("0" B / "1" A)*
1224 A <- "0" / "1" A A
1225 B <- "1" / "0" B B
1226]]
1227assert(match("00011011", g) == 9)
1228assert(match("000110110", g) == 9)
1229assert(match("011110110", g) == 3)
1230assert(match("000110010", g) == 1)
1231
1232s = "aaaaaaaaaaaaaaaaaaaaaaaa"
1233assert(match(s, "'a'^3") == 4)
1234assert(match(s, "'a'^0") == 1)
1235assert(match(s, "'a'^+3") == s:len() + 1)
1236assert(not match(s, "'a'^+30"))
1237assert(match(s, "'a'^-30") == s:len() + 1)
1238assert(match(s, "'a'^-5") == 6)
1239for i = 1, s:len() do
1240 assert(match(s, string.format("'a'^+%d", i)) >= i + 1)
1241 assert(match(s, string.format("'a'^-%d", i)) <= i + 1)
1242 assert(match(s, string.format("'a'^%d", i)) == i + 1)
1243end
1244assert(match("01234567890123456789", "[0-9]^3+") == 19)
1245
1246
1247assert(match("01234567890123456789", "({....}{...}) -> '%2%1'") == "4560123")
1248t = match("0123456789", "{| {.}* |}")
1249checkeq(t, {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"})
1250assert(match("012345", "{| (..) -> '%0%0' |}")[1] == "0101")
1251
1252assert(match("abcdef", "( {.} {.} {.} {.} {.} ) -> 3") == "c")
1253assert(match("abcdef", "( {:x: . :} {.} {.} {.} {.} ) -> 3") == "d")
1254assert(match("abcdef", "( {:x: . :} {.} {.} {.} {.} ) -> 0") == 6)
1255
1256assert(not match("abcdef", "{:x: ({.} {.} {.}) -> 2 :} =x"))
1257assert(match("abcbef", "{:x: ({.} {.} {.}) -> 2 :} =x"))
1258
1259eqcharset(compile"[]]", "]")
1260eqcharset(compile"[][]", m.S"[]")
1261eqcharset(compile"[]-]", m.S"-]")
1262eqcharset(compile"[-]", m.S"-")
1263eqcharset(compile"[az-]", m.S"a-z")
1264eqcharset(compile"[-az]", m.S"a-z")
1265eqcharset(compile"[a-z]", m.R"az")
1266eqcharset(compile"[]['\"]", m.S[[]['"]])
1267
1268eqcharset(compile"[^]]", any - "]")
1269eqcharset(compile"[^][]", any - m.S"[]")
1270eqcharset(compile"[^]-]", any - m.S"-]")
1271eqcharset(compile"[^]-]", any - m.S"-]")
1272eqcharset(compile"[^-]", any - m.S"-")
1273eqcharset(compile"[^az-]", any - m.S"a-z")
1274eqcharset(compile"[^-az]", any - m.S"a-z")
1275eqcharset(compile"[^a-z]", any - m.R"az")
1276eqcharset(compile"[^]['\"]", any - m.S[[]['"]])
1277
1278-- tests for comments in 're'
1279e = compile[[
1280A <- _B -- \t \n %nl .<> <- -> --
1281_B <- 'x' --]]
1282assert(e:match'xy' == 2)
1283
1284-- tests for 're' with pre-definitions
1285defs = {digits = m.R"09", letters = m.R"az", _=m.P"__"}
1286e = compile("%letters (%letters / %digits)*", defs)
1287assert(e:match"x123" == 5)
1288e = compile("%_", defs)
1289assert(e:match"__" == 3)
1290
1291e = compile([[
1292 S <- A+
1293 A <- %letters+ B
1294 B <- %digits+
1295]], defs)
1296
1297e = compile("{[0-9]+'.'?[0-9]*} -> sin", math)
1298assert(e:match("2.34") == math.sin(2.34))
1299
1300
1301function eq (_, _, a, b) return a == b end
1302
1303c = re.compile([[
1304 longstring <- '[' {:init: '='* :} '[' close
1305 close <- ']' =init ']' / . close
1306]])
1307
1308assert(c:match'[==[]]===]]]]==]===[]' == 17)
1309assert(c:match'[[]=]====]=]]]==]===[]' == 14)
1310assert(not c:match'[[]=]====]=]=]==]===[]')
1311
1312c = re.compile" '[' {:init: '='* :} '[' (!(']' =init ']') .)* ']' =init ']' !. "
1313
1314assert(c:match'[==[]]===]]]]==]')
1315assert(c:match'[[]=]====]=][]==]===[]]')
1316assert(not c:match'[[]=]====]=]=]==]===[]')
1317
1318assert(re.find("hi alalo", "{:x:..:} =x") == 4)
1319assert(re.find("hi alalo", "{:x:..:} =x", 4) == 4)
1320assert(not re.find("hi alalo", "{:x:..:} =x", 5))
1321assert(re.find("hi alalo", "{'al'}", 5) == 6)
1322assert(re.find("hi aloalolo", "{:x:..:} =x") == 8)
1323assert(re.find("alo alohi x x", "{:word:%w+:}%W*(=word)!%w") == 11)
1324
1325-- re.find discards any captures
1326local a,b,c = re.find("alo", "{.}{'o'}")
1327assert(a == 2 and b == 3 and c == nil)
1328
1329local function match (s,p)
1330 local i,e = re.find(s,p)
1331 if i then return s:sub(i, e) end
1332end
1333assert(match("alo alo", '[a-z]+') == "alo")
1334assert(match("alo alo", '{:x: [a-z]+ :} =x') == nil)
1335assert(match("alo alo", "{:x: [a-z]+ :} ' ' =x") == "alo alo")
1336
1337assert(re.gsub("alo alo", "[abc]", "x") == "xlo xlo")
1338assert(re.gsub("alo alo", "%w+", ".") == ". .")
1339assert(re.gsub("hi, how are you", "[aeiou]", string.upper) ==
1340 "hI, hOw ArE yOU")
1341
1342s = 'hi [[a comment[=]=] ending here]] and [=[another]]=]]'
1343c = re.compile" '[' {:i: '='* :} '[' (!(']' =i ']') .)* ']' { =i } ']' "
1344assert(re.gsub(s, c, "%2") == 'hi and =]')
1345assert(re.gsub(s, c, "%0") == s)
1346assert(re.gsub('[=[hi]=]', c, "%2") == '=')
1347
1348assert(re.find("", "!.") == 1)
1349assert(re.find("alo", "!.") == 4)
1350
1351function addtag (s, i, t, tag) t.tag = tag; return i, t end
1352
1353c = re.compile([[
1354 doc <- block !.
1355 block <- (start {| (block / { [^<]+ })* |} end?) => addtag
1356 start <- '<' {:tag: [a-z]+ :} '>'
1357 end <- '</' { =tag } '>'
1358]], {addtag = addtag})
1359
1360x = c:match[[
1361<x>hi<b>hello</b>but<b>totheend</x>]]
1362checkeq(x, {tag='x', 'hi', {tag = 'b', 'hello'}, 'but',
1363 {'totheend'}})
1364
1365
1366-- test for folding captures
1367c = re.compile([[
1368 S <- (number (%s+ number)*) ~> add
1369 number <- %d+ -> tonumber
1370]], {tonumber = tonumber, add = function (a,b) return a + b end})
1371assert(c:match("3 401 50") == 3 + 401 + 50)
1372
1373-- tests for look-ahead captures
1374x = {re.match("alo", "&(&{.}) !{'b'} {&(...)} &{..} {...} {!.}")}
1375checkeq(x, {"", "alo", ""})
1376
1377assert(re.match("aloalo",
1378 "{~ (((&'al' {.}) -> 'A%1' / (&%l {.}) -> '%1%1') / .)* ~}")
1379 == "AallooAalloo")
1380
1381-- bug in 0.9 (and older versions), due to captures in look-aheads
1382x = re.compile[[ {~ (&(. ([a-z]* -> '*')) ([a-z]+ -> '+') ' '*)* ~} ]]
1383assert(x:match"alo alo" == "+ +")
1384
1385-- valid capture in look-ahead (used inside the look-ahead itself)
1386x = re.compile[[
1387 S <- &({:two: .. :} . =two) {[a-z]+} / . S
1388]]
1389assert(x:match("hello aloaLo aloalo xuxu") == "aloalo")
1390
1391
1392p = re.compile[[
1393 block <- {| {:ident:space*:} line
1394 ((=ident !space line) / &(=ident space) block)* |}
1395 line <- {[^%nl]*} %nl
1396 space <- '_' -- should be ' ', but '_' is simpler for editors
1397]]
1398
1399t= p:match[[
14001
1401__1.1
1402__1.2
1403____1.2.1
1404____
14052
1406__2.1
1407]]
1408checkeq(t, {"1", {"1.1", "1.2", {"1.2.1", "", ident = "____"}, ident = "__"},
1409 "2", {"2.1", ident = "__"}, ident = ""})
1410
1411
1412-- nested grammars
1413p = re.compile[[
1414 s <- a b !.
1415 b <- ( x <- ('b' x)? )
1416 a <- ( x <- 'a' x? )
1417]]
1418
1419assert(p:match'aaabbb')
1420assert(p:match'aaa')
1421assert(not p:match'bbb')
1422assert(not p:match'aaabbba')
1423
1424-- testing groups
1425t = {re.match("abc", "{:S <- {:.:} {S} / '':}")}
1426checkeq(t, {"a", "bc", "b", "c", "c", ""})
1427
1428t = re.match("1234", "{| {:a:.:} {:b:.:} {:c:.{.}:} |}")
1429checkeq(t, {a="1", b="2", c="4"})
1430t = re.match("1234", "{|{:a:.:} {:b:{.}{.}:} {:c:{.}:}|}")
1431checkeq(t, {a="1", b="2", c="4"})
1432t = re.match("12345", "{| {:.:} {:b:{.}{.}:} {:{.}{.}:} |}")
1433checkeq(t, {"1", b="2", "4", "5"})
1434t = re.match("12345", "{| {:.:} {:{:b:{.}{.}:}:} {:{.}{.}:} |}")
1435checkeq(t, {"1", "23", "4", "5"})
1436t = re.match("12345", "{| {:.:} {{:b:{.}{.}:}} {:{.}{.}:} |}")
1437checkeq(t, {"1", "23", "4", "5"})
1438
1439
1440-- testing pre-defined names
1441assert(os.setlocale("C") == "C")
1442
1443function eqlpeggsub (p1, p2)
1444 local s1 = cs2str(re.compile(p1))
1445 local s2 = string.gsub(allchar, "[^" .. p2 .. "]", "")
1446 -- if s1 ~= s2 then print(#s1,#s2) end
1447 assert(s1 == s2)
1448end
1449
1450
1451eqlpeggsub("%w", "%w")
1452eqlpeggsub("%a", "%a")
1453eqlpeggsub("%l", "%l")
1454eqlpeggsub("%u", "%u")
1455eqlpeggsub("%p", "%p")
1456eqlpeggsub("%d", "%d")
1457eqlpeggsub("%x", "%x")
1458eqlpeggsub("%s", "%s")
1459eqlpeggsub("%c", "%c")
1460
1461eqlpeggsub("%W", "%W")
1462eqlpeggsub("%A", "%A")
1463eqlpeggsub("%L", "%L")
1464eqlpeggsub("%U", "%U")
1465eqlpeggsub("%P", "%P")
1466eqlpeggsub("%D", "%D")
1467eqlpeggsub("%X", "%X")
1468eqlpeggsub("%S", "%S")
1469eqlpeggsub("%C", "%C")
1470
1471eqlpeggsub("[%w]", "%w")
1472eqlpeggsub("[_%w]", "_%w")
1473eqlpeggsub("[^%w]", "%W")
1474eqlpeggsub("[%W%S]", "%W%S")
1475
1476re.updatelocale()
1477
1478
1479-- testing nested substitutions x string captures
1480
1481p = re.compile[[
1482 text <- {~ item* ~}
1483 item <- macro / [^()] / '(' item* ')'
1484 arg <- ' '* {~ (!',' item)* ~}
1485 args <- '(' arg (',' arg)* ')'
1486 macro <- ('apply' args) -> '%1(%2)'
1487 / ('add' args) -> '%1 + %2'
1488 / ('mul' args) -> '%1 * %2'
1489]]
1490
1491assert(p:match"add(mul(a,b), apply(f,x))" == "a * b + f(x)")
1492
1493rev = re.compile[[ R <- (!.) -> '' / ({.} R) -> '%2%1']]
1494
1495assert(rev:match"0123456789" == "9876543210")
1496
1497
1498-- testing error messages in re
1499
1500local function errmsg (p, err)
1501 checkerr(err, re.compile, p)
1502end
1503
1504errmsg('aaaa', "rule 'aaaa'")
1505errmsg('a', 'outside')
1506errmsg('b <- a', 'undefined')
1507errmsg("x <- 'a' x <- 'b'", 'already defined')
1508errmsg("'a' -", "near '-'")
1509
1510
1511print"OK"
1512
1513