-
Notifications
You must be signed in to change notification settings - Fork 0
/
lulpeg.lua
2964 lines (2934 loc) · 87.2 KB
/
lulpeg.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- LuLPeg, a pure Lua port of LPeg, Roberto Ierusalimschy's
-- Parsing Expression Grammars library.
--
-- Copyright (C) Pierre-Yves Gerardy.
-- Released under the Romantic WTF Public License (cf. the LICENSE
-- file or the end of this file, whichever is present).
--
-- See http://www.inf.puc-rio.br/~roberto/lpeg/ for the original.
--
-- The re.lua module and the test suite (tests/lpeg.*.*.tests.lua)
-- are part of the original LPeg distribution.
local _ENV, loaded, packages, release, require_
= _ENV or _G, {}, {}, true, require
local function require(...)
local lib = ...
-- is it a private file?
if loaded[lib] then
return loaded[lib]
elseif packages[lib] then
loaded[lib] = packages[lib](lib)
return loaded[lib]
else
return require_(lib)
end
end
--=============================================================================
do local _ENV = _ENV
packages['util'] = function (...)
local getmetatable, setmetatable, load, loadstring, next
, pairs, pcall, print, rawget, rawset, select, tostring
, type, unpack
= getmetatable, setmetatable, load, loadstring, next
, pairs, pcall, print, rawget, rawset, select, tostring
, type, unpack
local m, s, t = require"math", require"string", require"table"
local m_max, s_match, s_gsub, t_concat, t_insert
= m.max, s.match, s.gsub, t.concat, t.insert
local compat = require"compat"
local
function nop () end
local noglobals, getglobal, setglobal if pcall and not compat.lua52 and not release then
local function errR (_,i)
error("illegal global read: " .. tostring(i), 2)
end
local function errW (_,i, v)
error("illegal global write: " .. tostring(i)..": "..tostring(v), 2)
end
local env = setmetatable({}, { __index=errR, __newindex=errW })
noglobals = function()
pcall(setfenv, 3, env)
end
function getglobal(k) rawget(env, k) end
function setglobal(k, v) rawset(env, k, v) end
else
noglobals = nop
end
local _ENV = noglobals() ------------------------------------------------------
local util = {
nop = nop,
noglobals = noglobals,
getglobal = getglobal,
setglobal = setglobal
}
util.unpack = t.unpack or unpack
util.pack = t.pack or function(...) return { n = select('#', ...), ... } end
if compat.lua51 then
local old_load = load
function util.load (ld, source, mode, env)
local fun
if type (ld) == 'string' then
fun = loadstring (ld)
else
fun = old_load (ld, source)
end
if env then
setfenv (fun, env)
end
return fun
end
else
util.load = load
end
if compat.luajit and compat.jit then
function util.max (ary)
local max = 0
for i = 1, #ary do
max = m_max(max,ary[i])
end
return max
end
elseif compat.luajit then
local t_unpack = util.unpack
function util.max (ary)
local len = #ary
if len <=30 or len > 10240 then
local max = 0
for i = 1, #ary do
local j = ary[i]
if j > max then max = j end
end
return max
else
return m_max(t_unpack(ary))
end
end
else
local t_unpack = util.unpack
local safe_len = 1000
function util.max(array)
local len = #array
if len == 0 then return -1 end -- FIXME: shouldn't this be `return -1`?
local off = 1
local off_end = safe_len
local max = array[1] -- seed max.
repeat
if off_end > len then off_end = len end
local seg_max = m_max(t_unpack(array, off, off_end))
if seg_max > max then
max = seg_max
end
off = off + safe_len
off_end = off_end + safe_len
until off >= len
return max
end
end
local
function setmode(t,mode)
local mt = getmetatable(t) or {}
if mt.__mode then
error("The mode has already been set on table "..tostring(t)..".")
end
mt.__mode = mode
return setmetatable(t, mt)
end
util.setmode = setmode
function util.weakboth (t)
return setmode(t,"kv")
end
function util.weakkey (t)
return setmode(t,"k")
end
function util.weakval (t)
return setmode(t,"v")
end
function util.strip_mt (t)
return setmetatable(t, nil)
end
local getuniqueid
do
local N, index = 0, {}
function getuniqueid(v)
if not index[v] then
N = N + 1
index[v] = N
end
return index[v]
end
end
util.getuniqueid = getuniqueid
do
local counter = 0
function util.gensym ()
counter = counter + 1
return "___SYM_"..counter
end
end
function util.passprint (...) print(...) return ... end
local val_to_str_, key_to_str, table_tostring, cdata_to_str, t_cache
local multiplier = 2
local
function val_to_string (v, indent)
indent = indent or 0
t_cache = {} -- upvalue.
local acc = {}
val_to_str_(v, acc, indent, indent)
local res = t_concat(acc, "")
return res
end
util.val_to_str = val_to_string
function val_to_str_ ( v, acc, indent, str_indent )
str_indent = str_indent or 1
if "string" == type( v ) then
v = s_gsub( v, "\n", "\n" .. (" "):rep( indent * multiplier + str_indent ) )
if s_match( s_gsub( v,"[^'\"]",""), '^"+$' ) then
acc[#acc+1] = t_concat{ "'", "", v, "'" }
else
acc[#acc+1] = t_concat{'"', s_gsub(v,'"', '\\"' ), '"' }
end
elseif "cdata" == type( v ) then
cdata_to_str( v, acc, indent )
elseif "table" == type(v) then
if t_cache[v] then
acc[#acc+1] = t_cache[v]
else
t_cache[v] = tostring( v )
table_tostring( v, acc, indent )
end
else
acc[#acc+1] = tostring( v )
end
end
function key_to_str ( k, acc, indent )
if "string" == type( k ) and s_match( k, "^[_%a][_%a%d]*$" ) then
acc[#acc+1] = s_gsub( k, "\n", (" "):rep( indent * multiplier + 1 ) .. "\n" )
else
acc[#acc+1] = "[ "
val_to_str_( k, acc, indent )
acc[#acc+1] = " ]"
end
end
function cdata_to_str(v, acc, indent)
acc[#acc+1] = ( " " ):rep( indent * multiplier )
acc[#acc+1] = "["
print(#acc)
for i = 0, #v do
if i % 16 == 0 and i ~= 0 then
acc[#acc+1] = "\n"
acc[#acc+1] = (" "):rep(indent * multiplier + 2)
end
acc[#acc+1] = v[i] and 1 or 0
acc[#acc+1] = i ~= #v and ", " or ""
end
print(#acc, acc[1], acc[2])
acc[#acc+1] = "]"
end
function table_tostring ( tbl, acc, indent )
acc[#acc+1] = t_cache[tbl]
acc[#acc+1] = "{\n"
for k, v in pairs( tbl ) do
local str_indent = 1
acc[#acc+1] = (" "):rep((indent + 1) * multiplier)
key_to_str( k, acc, indent + 1)
if acc[#acc] == " ]"
and acc[#acc - 2] == "[ "
then str_indent = 8 + #acc[#acc - 1]
end
acc[#acc+1] = " = "
val_to_str_( v, acc, indent + 1, str_indent)
acc[#acc+1] = "\n"
end
acc[#acc+1] = ( " " ):rep( indent * multiplier )
acc[#acc+1] = "}"
end
function util.expose(v) print(val_to_string(v)) return v end
function util.map (ary, func, ...)
if type(ary) == "function" then ary, func = func, ary end
local res = {}
for i = 1,#ary do
res[i] = func(ary[i], ...)
end
return res
end
function util.selfmap (ary, func, ...)
if type(ary) == "function" then ary, func = func, ary end
for i = 1,#ary do
ary[i] = func(ary[i], ...)
end
return ary
end
local
function map_all (tbl, func, ...)
if type(tbl) == "function" then tbl, func = func, tbl end
local res = {}
for k, v in next, tbl do
res[k]=func(v, ...)
end
return res
end
util.map_all = map_all
local
function fold (ary, func, acc)
local i0 = 1
if not acc then
acc = ary[1]
i0 = 2
end
for i = i0, #ary do
acc = func(acc,ary[i])
end
return acc
end
util.fold = fold
local
function foldr (ary, func, acc)
local offset = 0
if not acc then
acc = ary[#ary]
offset = 1
end
for i = #ary - offset, 1 , -1 do
acc = func(ary[i], acc)
end
return acc
end
util.foldr = foldr
local
function map_fold(ary, mfunc, ffunc, acc)
local i0 = 1
if not acc then
acc = mfunc(ary[1])
i0 = 2
end
for i = i0, #ary do
acc = ffunc(acc,mfunc(ary[i]))
end
return acc
end
util.map_fold = map_fold
local
function map_foldr(ary, mfunc, ffunc, acc)
local offset = 0
if not acc then
acc = mfunc(ary[#acc])
offset = 1
end
for i = #ary - offset, 1 , -1 do
acc = ffunc(mfunc(ary[i], acc))
end
return acc
end
util.map_foldr = map_fold
function util.zip(a1, a2)
local res, len = {}, m_max(#a1,#a2)
for i = 1,len do
res[i] = {a1[i], a2[i]}
end
return res
end
function util.zip_all(t1, t2)
local res = {}
for k,v in pairs(t1) do
res[k] = {v, t2[k]}
end
for k,v in pairs(t2) do
if res[k] == nil then
res[k] = {t1[k], v}
end
end
return res
end
function util.filter(ary,func)
local res = {}
for i = 1,#ary do
if func(ary[i]) then
t_insert(res, ary[i])
end
end
end
local
function id (...) return ... end
util.id = id
local function AND (a,b) return a and b end
local function OR (a,b) return a or b end
function util.copy (tbl) return map_all(tbl, id) end
function util.all (ary, mfunc)
if mfunc then
return map_fold(ary, mfunc, AND)
else
return fold(ary, AND)
end
end
function util.any (ary, mfunc)
if mfunc then
return map_fold(ary, mfunc, OR)
else
return fold(ary, OR)
end
end
function util.get(field)
return function(tbl) return tbl[field] end
end
function util.lt(ref)
return function(val) return val < ref end
end
function util.compose(f,g)
return function(...) return f(g(...)) end
end
function util.extend (destination, ...)
for i = 1, select('#', ...) do
for k,v in pairs((select(i, ...))) do
destination[k] = v
end
end
return destination
end
function util.setify (t)
local set = {}
for i = 1, #t do
set[t[i]]=true
end
return set
end
function util.arrayify (...) return {...} end
local
function _checkstrhelper(s)
return s..""
end
function util.checkstring(s, func)
local success, str = pcall(_checkstrhelper, s)
if not success then
if func == nil then func = "?" end
error("bad argument to '"
..tostring(func)
.."' (string expected, got "
..type(s)
..")",
2)
end
return str
end
return util
end
end
--=============================================================================
do local _ENV = _ENV
packages['compiler'] = function (...)
local assert, error, pairs, print, rawset, select, setmetatable, tostring, type
= assert, error, pairs, print, rawset, select, setmetatable, tostring, type
local s, t, u = require"string", require"table", require"util"
local _ENV = u.noglobals() ----------------------------------------------------
local s_byte, s_sub, t_concat, t_insert, t_remove, t_unpack
= s.byte, s.sub, t.concat, t.insert, t.remove, u.unpack
local load, map, map_all, t_pack
= u.load, u.map, u.map_all, u.pack
local expose = u.expose
return function(Builder, LL)
local evaluate, LL_ispattern = LL.evaluate, LL.ispattern
local charset = Builder.charset
local compilers = {}
local
function compile(pt, ccache)
if not LL_ispattern(pt) then
error("pattern expected")
end
local typ = pt.pkind
if typ == "grammar" then
ccache = {}
elseif typ == "ref" or typ == "choice" or typ == "sequence" then
if not ccache[pt] then
ccache[pt] = compilers[typ](pt, ccache)
end
return ccache[pt]
end
if not pt.compiled then
pt.compiled = compilers[pt.pkind](pt, ccache)
end
return pt.compiled
end
LL.compile = compile
local
function clear_captures(ary, ci)
for i = ci, #ary do ary[i] = nil end
end
local LL_compile, LL_evaluate, LL_P
= LL.compile, LL.evaluate, LL.P
local function computeidex(i, len)
if i == 0 or i == 1 or i == nil then return 1
elseif type(i) ~= "number" then error"number or nil expected for the stating index"
elseif i > 0 then return i > len and len + 1 or i
else return len + i < 0 and 1 or len + i + 1
end
end
local function newcaps()
return {
kind = {},
bounds = {},
openclose = {},
aux = -- [[DBG]] dbgcaps
{}
}
end
local
function _match(dbg, pt, sbj, si, ...)
if dbg then -------------
print("@!!! Match !!!@", pt)
end ---------------------
pt = LL_P(pt)
assert(type(sbj) == "string", "string expected for the match subject")
si = computeidex(si, #sbj)
if dbg then -------------
print(("-"):rep(30))
print(pt.pkind)
LL.pprint(pt)
end ---------------------
local matcher = compile(pt, {})
local caps = newcaps()
local matcher_state = {grammars = {}, args = {n = select('#',...),...}, tags = {}}
local success, final_si, ci = matcher(sbj, si, caps, 1, matcher_state)
if dbg then -------------
print("!!! Done Matching !!! success: ", success,
"final position", final_si, "final cap index", ci,
"#caps", #caps.openclose)
end----------------------
if success then
clear_captures(caps.kind, ci)
clear_captures(caps.aux, ci)
if dbg then -------------
print("trimmed cap index = ", #caps + 1)
LL.cprint(caps, sbj, 1)
end ---------------------
local values, _, vi = LL_evaluate(caps, sbj, 1, 1)
if dbg then -------------
print("#values", vi)
expose(values)
end ---------------------
if vi == 0
then return final_si
else return t_unpack(values, 1, vi) end
else
if dbg then print("Failed") end
return nil
end
end
function LL.match(...)
return _match(false, ...)
end
function LL.dmatch(...)
return _match(true, ...)
end
for _, v in pairs{
"C", "Cf", "Cg", "Cs", "Ct", "Clb",
"div_string", "div_table", "div_number", "div_function"
} do
compilers[v] = load(([=[
local compile, expose, type, LL = ...
return function (pt, ccache)
local matcher, this_aux = compile(pt.pattern, ccache), pt.aux
return function (sbj, si, caps, ci, state)
local ref_ci = ci
local kind, bounds, openclose, aux
= caps.kind, caps.bounds, caps.openclose, caps.aux
kind [ci] = "XXXX"
bounds [ci] = si
openclose [ci] = 0
caps.aux [ci] = (this_aux or false)
local success
success, si, ci
= matcher(sbj, si, caps, ci + 1, state)
if success then
if ci == ref_ci + 1 then
caps.openclose[ref_ci] = si
else
kind [ci] = "XXXX"
bounds [ci] = si
openclose [ci] = ref_ci - ci
aux [ci] = this_aux or false
ci = ci + 1
end
else
ci = ci - 1
end
return success, si, ci
end
end]=]):gsub("XXXX", v), v.." compiler")(compile, expose, type, LL)
end
compilers["Carg"] = function (pt, ccache)
local n = pt.aux
return function (sbj, si, caps, ci, state)
if state.args.n < n then error("reference to absent argument #"..n) end
caps.kind [ci] = "value"
caps.bounds [ci] = si
if state.args[n] == nil then
caps.openclose [ci] = 1/0
caps.aux [ci] = 1/0
else
caps.openclose [ci] = si
caps.aux [ci] = state.args[n]
end
return true, si, ci + 1
end
end
for _, v in pairs{
"Cb", "Cc", "Cp"
} do
compilers[v] = load(([=[
return function (pt, ccache)
local this_aux = pt.aux
return function (sbj, si, caps, ci, state)
caps.kind [ci] = "XXXX"
caps.bounds [ci] = si
caps.openclose [ci] = si
caps.aux [ci] = this_aux or false
return true, si, ci + 1
end
end]=]):gsub("XXXX", v), v.." compiler")(expose)
end
compilers["/zero"] = function (pt, ccache)
local matcher = compile(pt.pattern, ccache)
return function (sbj, si, caps, ci, state)
local success, nsi = matcher(sbj, si, caps, ci, state)
clear_captures(caps.aux, ci)
return success, nsi, ci
end
end
local function pack_Cmt_caps(i,...) return i, t_pack(...) end
compilers["Cmt"] = function (pt, ccache)
local matcher, func = compile(pt.pattern, ccache), pt.aux
return function (sbj, si, caps, ci, state)
local success, Cmt_si, Cmt_ci = matcher(sbj, si, caps, ci, state)
if not success then
clear_captures(caps.aux, ci)
return false, si, ci
end
local final_si, values
if Cmt_ci == ci then
final_si, values = pack_Cmt_caps(
func(sbj, Cmt_si, s_sub(sbj, si, Cmt_si - 1))
)
else
clear_captures(caps.aux, Cmt_ci)
clear_captures(caps.kind, Cmt_ci)
local cps, _, nn = evaluate(caps, sbj, ci)
final_si, values = pack_Cmt_caps(
func(sbj, Cmt_si, t_unpack(cps, 1, nn))
)
end
if not final_si then
return false, si, ci
end
if final_si == true then final_si = Cmt_si end
if type(final_si) == "number"
and si <= final_si
and final_si <= #sbj + 1
then
local kind, bounds, openclose, aux
= caps.kind, caps.bounds, caps.openclose, caps.aux
for i = 1, values.n do
kind [ci] = "value"
bounds [ci] = si
if values[i] == nil then
caps.openclose [ci] = 1/0
caps.aux [ci] = 1/0
else
caps.openclose [ci] = final_si
caps.aux [ci] = values[i]
end
ci = ci + 1
end
elseif type(final_si) == "number" then
error"Index out of bounds returned by match-time capture."
else
error("Match time capture must return a number, a boolean or nil"
.." as first argument, or nothing at all.")
end
return true, final_si, ci
end
end
compilers["string"] = function (pt, ccache)
local S = pt.aux
local N = #S
return function(sbj, si, caps, ci, state)
local in_1 = si - 1
for i = 1, N do
local c
c = s_byte(sbj,in_1 + i)
if c ~= S[i] then
return false, si, ci
end
end
return true, si + N, ci
end
end
compilers["char"] = function (pt, ccache)
return load(([=[
local s_byte, s_char = ...
return function(sbj, si, caps, ci, state)
local c, nsi = s_byte(sbj, si), si + 1
if c ~= __C0__ then
return false, si, ci
end
return true, nsi, ci
end]=]):gsub("__C0__", tostring(pt.aux)))(s_byte, ("").char)
end
local
function truecompiled (sbj, si, caps, ci, state)
return true, si, ci
end
compilers["true"] = function (pt)
return truecompiled
end
local
function falsecompiled (sbj, si, caps, ci, state)
return false, si, ci
end
compilers["false"] = function (pt)
return falsecompiled
end
local
function eoscompiled (sbj, si, caps, ci, state)
return si > #sbj, si, ci
end
compilers["eos"] = function (pt)
return eoscompiled
end
local
function onecompiled (sbj, si, caps, ci, state)
local char, _ = s_byte(sbj, si), si + 1
if char
then return true, si + 1, ci
else return false, si, ci end
end
compilers["one"] = function (pt)
return onecompiled
end
compilers["any"] = function (pt)
local N = pt.aux
if N == 1 then
return onecompiled
else
N = pt.aux - 1
return function (sbj, si, caps, ci, state)
local n = si + N
if n <= #sbj then
return true, n + 1, ci
else
return false, si, ci
end
end
end
end
do
local function checkpatterns(g)
for k,v in pairs(g.aux) do
if not LL_ispattern(v) then
error(("rule 'A' is not a pattern"):gsub("A", tostring(k)))
end
end
end
compilers["grammar"] = function (pt, ccache)
checkpatterns(pt)
local gram = map_all(pt.aux, compile, ccache)
local start = gram[1]
return function (sbj, si, caps, ci, state)
t_insert(state.grammars, gram)
local success, nsi, ci = start(sbj, si, caps, ci, state)
t_remove(state.grammars)
return success, nsi, ci
end
end
end
local dummy_acc = {kind={}, bounds={}, openclose={}, aux={}}
compilers["behind"] = function (pt, ccache)
local matcher, N = compile(pt.pattern, ccache), pt.aux
return function (sbj, si, caps, ci, state)
if si <= N then return false, si, ci end
local success = matcher(sbj, si - N, dummy_acc, ci, state)
dummy_acc.aux = {}
return success, si, ci
end
end
compilers["range"] = function (pt)
local ranges = pt.aux
return function (sbj, si, caps, ci, state)
local char, nsi = s_byte(sbj, si), si + 1
for i = 1, #ranges do
local r = ranges[i]
if char and r[char]
then return true, nsi, ci end
end
return false, si, ci
end
end
compilers["set"] = function (pt)
local s = pt.aux
return function (sbj, si, caps, ci, state)
local char, nsi = s_byte(sbj, si), si + 1
if s[char]
then return true, nsi, ci
else return false, si, ci end
end
end
compilers["range"] = compilers.set
compilers["ref"] = function (pt, ccache)
local name = pt.aux
local ref
return function (sbj, si, caps, ci, state)
if not ref then
if #state.grammars == 0 then
error(("rule 'XXXX' used outside a grammar"):gsub("XXXX", tostring(name)))
elseif not state.grammars[#state.grammars][name] then
error(("rule 'XXXX' undefined in given grammar"):gsub("XXXX", tostring(name)))
end
ref = state.grammars[#state.grammars][name]
end
local success, nsi, nci = ref(sbj, si, caps, ci, state)
return success, nsi, nci
end
end
local choice_tpl = [=[
success, si, ci = XXXX(sbj, si, caps, ci, state)
if success then
return true, si, ci
else
end]=]
local function flatten(kind, pt, ccache)
if pt[2].pkind == kind then
return compile(pt[1], ccache), flatten(kind, pt[2], ccache)
else
return compile(pt[1], ccache), compile(pt[2], ccache)
end
end
compilers["choice"] = function (pt, ccache)
local choices = {flatten("choice", pt, ccache)}
local names, chunks = {}, {}
for i = 1, #choices do
local m = "ch"..i
names[#names + 1] = m
chunks[ #names ] = choice_tpl:gsub("XXXX", m)
end
names[#names + 1] = "clear_captures"
choices[ #names ] = clear_captures
local compiled = t_concat{
"local ", t_concat(names, ", "), [=[ = ...
return function (sbj, si, caps, ci, state)
local aux, success = caps.aux, false
]=],
t_concat(chunks,"\n"),[=[--
return false, si, ci
end]=]
}
return load(compiled, "Choice")(t_unpack(choices))
end
local sequence_tpl = [=[
success, si, ci = XXXX(sbj, si, caps, ci, state)
if not success then
return false, ref_si, ref_ci
end]=]
compilers["sequence"] = function (pt, ccache)
local sequence = {flatten("sequence", pt, ccache)}
local names, chunks = {}, {}
for i = 1, #sequence do
local m = "seq"..i
names[#names + 1] = m
chunks[ #names ] = sequence_tpl:gsub("XXXX", m)
end
names[#names + 1] = "clear_captures"
sequence[ #names ] = clear_captures
local compiled = t_concat{
"local ", t_concat(names, ", "), [=[ = ...
return function (sbj, si, caps, ci, state)
local ref_si, ref_ci, success = si, ci
]=],
t_concat(chunks,"\n"),[=[
return true, si, ci
end]=]
}
return load(compiled, "Sequence")(t_unpack(sequence))
end
compilers["at most"] = function (pt, ccache)
local matcher, n = compile(pt.pattern, ccache), pt.aux
n = -n
return function (sbj, si, caps, ci, state)
local success = true
for i = 1, n do
success, si, ci = matcher(sbj, si, caps, ci, state)
if not success then
break
end
end
return true, si, ci
end
end
compilers["at least"] = function (pt, ccache)
local matcher, n = compile(pt.pattern, ccache), pt.aux
if n == 0 then
return function (sbj, si, caps, ci, state)
local last_si, last_ci
while true do
local success
last_si, last_ci = si, ci
success, si, ci = matcher(sbj, si, caps, ci, state)
if not success then
si, ci = last_si, last_ci
break
end
end
return true, si, ci
end
elseif n == 1 then
return function (sbj, si, caps, ci, state)
local last_si, last_ci
local success = true
success, si, ci = matcher(sbj, si, caps, ci, state)
if not success then
return false, si, ci
end
while true do
local success
last_si, last_ci = si, ci
success, si, ci = matcher(sbj, si, caps, ci, state)
if not success then
si, ci = last_si, last_ci
break
end
end
return true, si, ci
end
else
return function (sbj, si, caps, ci, state)
local last_si, last_ci
local success = true
for _ = 1, n do
success, si, ci = matcher(sbj, si, caps, ci, state)
if not success then
return false, si, ci
end
end
while true do
local success
last_si, last_ci = si, ci
success, si, ci = matcher(sbj, si, caps, ci, state)
if not success then
si, ci = last_si, last_ci
break
end
end
return true, si, ci
end
end
end
compilers["unm"] = function (pt, ccache)
if pt.pkind == "any" and pt.aux == 1 then
return eoscompiled
end
local matcher = compile(pt.pattern, ccache)
return function (sbj, si, caps, ci, state)
local success, _, _ = matcher(sbj, si, caps, ci, state)
return not success, si, ci
end
end
compilers["lookahead"] = function (pt, ccache)
local matcher = compile(pt.pattern, ccache)
return function (sbj, si, caps, ci, state)
local success, _, _ = matcher(sbj, si, caps, ci, state)
return success, si, ci
end
end
end
end
end
--=============================================================================
do local _ENV = _ENV
packages['datastructures'] = function (...)
local getmetatable, pairs, setmetatable, type
= getmetatable, pairs, setmetatable, type
local m, t , u = require"math", require"table", require"util"
local compat = require"compat"
local ffi if compat.luajit then
ffi = require"ffi"
end
local _ENV = u.noglobals() ----------------------------------------------------
local extend, load, u_max
= u.extend, u.load, u.max
local m_max, t_concat, t_insert, t_sort
= m.max, t.concat, t.insert, t.sort
local structfor = {}
local byteset_new, isboolset, isbyteset
local byteset_mt = {}
local
function byteset_constructor (upper)
local set = setmetatable(load(t_concat{
"return{ [0]=false",
(", false"):rep(upper),
" }"
})(),
byteset_mt)
return set
end
if compat.jit then
local struct, boolset_constructor = {v={}}
function byteset_mt.__index(s,i)
if i == nil or i > s.upper then return nil end
return s.v[i]
end
function byteset_mt.__len(s)
return s.upper
end
function byteset_mt.__newindex(s,i,v)
s.v[i] = v
end
boolset_constructor = ffi.metatype('struct { int upper; bool v[?]; }', byteset_mt)
function byteset_new (t)
if type(t) == "number" then
local res = boolset_constructor(t+1)
res.upper = t
return res
end
local upper = u_max(t)
struct.upper = upper
if upper > 255 then error"bool_set overflow" end
local set = boolset_constructor(upper+1)
set.upper = upper
for i = 1, #t do set[t[i]] = true end