-
Notifications
You must be signed in to change notification settings - Fork 33
/
lulpeg.lua
2976 lines (2945 loc) · 87.5 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['API'] = function (...)
local assert, error, ipairs, pairs, pcall, print
, require, select, tonumber, tostring, type
= assert, error, ipairs, pairs, pcall, print
, require, select, tonumber, tostring, type
local t, u = require"table", require"util"
local _ENV = u.noglobals() ---------------------------------------------------
local t_concat = t.concat
local checkstring, copy, fold, load, map_fold, map_foldr, setify, t_pack, t_unpack
= u.checkstring, u.copy, u.fold, u.load, u.map_fold, u.map_foldr, u.setify, u.pack, u.unpack
local
function charset_error(index, charset)
error("Character at position ".. index + 1
.." is not a valid "..charset.." one.",
2)
end
return function(Builder, LL) -- module wrapper -------------------------------
local cs = Builder.charset
local constructors, LL_ispattern
= Builder.constructors, LL.ispattern
local truept, falsept, Cppt
= constructors.constant.truept
, constructors.constant.falsept
, constructors.constant.Cppt
local split_int, validate
= cs.split_int, cs.validate
local Range, Set, S_union, S_tostring
= Builder.Range, Builder.set.new
, Builder.set.union, Builder.set.tostring
local factorize_choice, factorize_lookahead, factorize_sequence, factorize_unm
local
function makechar(c)
return constructors.aux("char", c)
end
local
function LL_P (...)
local v, n = (...), select('#', ...)
if n == 0 then error"bad argument #1 to 'P' (value expected)" end
local typ = type(v)
if LL_ispattern(v) then
return v
elseif typ == "function" then
return
LL.Cmt("", v)
elseif typ == "string" then
local success, index = validate(v)
if not success then
charset_error(index, cs.name)
end
if v == "" then return truept end
return
map_foldr(split_int(v), makechar, Builder.sequence)
elseif typ == "table" then
local g = copy(v)
if g[1] == nil then error("grammar has no initial rule") end
if not LL_ispattern(g[1]) then g[1] = LL.V(g[1]) end
return
constructors.none("grammar", g)
elseif typ == "boolean" then
return v and truept or falsept
elseif typ == "number" then
if v == 0 then
return truept
elseif v > 0 then
return
constructors.aux("any", v)
else
return
- constructors.aux("any", -v)
end
else
error("bad argument #1 to 'P' (lpeg-pattern expected, got "..typ..")")
end
end
LL.P = LL_P
local
function LL_S (set)
if set == "" then
return
falsept
else
local success
set = checkstring(set, "S")
return
constructors.aux("set", Set(split_int(set)), set)
end
end
LL.S = LL_S
local
function LL_R (...)
if select('#', ...) == 0 then
return LL_P(false)
else
local range = Range(1,0)--Set("")
for _, r in ipairs{...} do
r = checkstring(r, "R")
assert(#r == 2, "bad argument #1 to 'R' (range must have two characters)")
range = S_union ( range, Range(t_unpack(split_int(r))) )
end
return
constructors.aux("set", range)
end
end
LL.R = LL_R
local
function LL_V (name)
assert(name ~= nil)
return
constructors.aux("ref", name)
end
LL.V = LL_V
do
local one = setify{"set", "range", "one", "char"}
local zero = setify{"true", "false", "lookahead", "unm"}
local forbidden = setify{
"Carg", "Cb", "C", "Cf",
"Cg", "Cs", "Ct", "/zero",
"Clb", "Cmt", "Cc", "Cp",
"div_string", "div_number", "div_table", "div_function",
"at least", "at most", "behind"
}
local function fixedlen(pt, gram, cycle)
local typ = pt.pkind
if forbidden[typ] then return false
elseif one[typ] then return 1
elseif zero[typ] then return 0
elseif typ == "string" then return #pt.as_is
elseif typ == "any" then return pt.aux
elseif typ == "choice" then
local l1, l2 = fixedlen(pt[1], gram, cycle), fixedlen(pt[2], gram, cycle)
return (l1 == l2) and l1
elseif typ == "sequence" then
local l1, l2 = fixedlen(pt[1], gram, cycle), fixedlen(pt[2], gram, cycle)
return l1 and l2 and l1 + l2
elseif typ == "grammar" then
if pt.aux[1].pkind == "ref" then
return fixedlen(pt.aux[pt.aux[1].aux], pt.aux, {})
else
return fixedlen(pt.aux[1], pt.aux, {})
end
elseif typ == "ref" then
if cycle[pt] then return false end
cycle[pt] = true
return fixedlen(gram[pt.aux], gram, cycle)
else
print(typ,"is not handled by fixedlen()")
end
end
function LL.B (pt)
pt = LL_P(pt)
local len = fixedlen(pt)
assert(len, "A 'behind' pattern takes a fixed length pattern as argument.")
if len >= 260 then error("Subpattern too long in 'behind' pattern constructor.") end
return
constructors.both("behind", pt, len)
end
end
local function nameify(a, b)
return ('%s:%s'):format(a.id, b.id)
end
local
function choice (a, b)
local name = nameify(a, b)
local ch = Builder.ptcache.choice[name]
if not ch then
ch = factorize_choice(a, b) or constructors.binary("choice", a, b)
Builder.ptcache.choice[name] = ch
end
return ch
end
function LL.__add (a, b)
return
choice(LL_P(a), LL_P(b))
end
local
function sequence (a, b)
local name = nameify(a, b)
local seq = Builder.ptcache.sequence[name]
if not seq then
seq = factorize_sequence(a, b) or constructors.binary("sequence", a, b)
Builder.ptcache.sequence[name] = seq
end
return seq
end
Builder.sequence = sequence
function LL.__mul (a, b)
return
sequence(LL_P(a), LL_P(b))
end
local
function LL_lookahead (pt)
if pt == truept
or pt == falsept
or pt.pkind == "unm"
or pt.pkind == "lookahead"
then
return pt
end
return
constructors.subpt("lookahead", pt)
end
LL.__len = LL_lookahead
LL.L = LL_lookahead
local
function LL_unm(pt)
return
factorize_unm(pt)
or constructors.subpt("unm", pt)
end
LL.__unm = LL_unm
local
function LL_sub (a, b)
a, b = LL_P(a), LL_P(b)
return LL_unm(b) * a
end
LL.__sub = LL_sub
local
function LL_repeat (pt, n)
local success
success, n = pcall(tonumber, n)
assert(success and type(n) == "number",
"Invalid type encountered at right side of '^'.")
return constructors.both(( n < 0 and "at most" or "at least" ), pt, n)
end
LL.__pow = LL_repeat
for _, cap in pairs{"C", "Cs", "Ct"} do
LL[cap] = function(pt)
pt = LL_P(pt)
return
constructors.subpt(cap, pt)
end
end
LL["Cb"] = function(aux)
return
constructors.aux("Cb", aux)
end
LL["Carg"] = function(aux)
assert(type(aux)=="number", "Number expected as parameter to Carg capture.")
assert( 0 < aux and aux <= 200, "Argument out of bounds in Carg capture.")
return
constructors.aux("Carg", aux)
end
local
function LL_Cp ()
return Cppt
end
LL.Cp = LL_Cp
local
function LL_Cc (...)
return
constructors.none("Cc", t_pack(...))
end
LL.Cc = LL_Cc
for _, cap in pairs{"Cf", "Cmt"} do
local msg = "Function expected in "..cap.." capture"
LL[cap] = function(pt, aux)
assert(type(aux) == "function", msg)
pt = LL_P(pt)
return
constructors.both(cap, pt, aux)
end
end
local
function LL_Cg (pt, tag)
pt = LL_P(pt)
if tag ~= nil then
return
constructors.both("Clb", pt, tag)
else
return
constructors.subpt("Cg", pt)
end
end
LL.Cg = LL_Cg
local valid_slash_type = setify{"string", "number", "table", "function"}
local
function LL_slash (pt, aux)
if LL_ispattern(aux) then
error"The right side of a '/' capture cannot be a pattern."
elseif not valid_slash_type[type(aux)] then
error("The right side of a '/' capture must be of type "
.."string, number, table or function.")
end
local name
if aux == 0 then
name = "/zero"
else
name = "div_"..type(aux)
end
return
constructors.both(name, pt, aux)
end
LL.__div = LL_slash
if Builder.proxymt then
for k, v in pairs(LL) do
if k:match"^__" then
Builder.proxymt[k] = v
end
end
else
LL.__index = LL
end
local factorizer
= Builder.factorizer(Builder, LL)
factorize_choice, factorize_lookahead, factorize_sequence, factorize_unm =
factorizer.choice, factorizer.lookahead, factorizer.sequence, factorizer.unm
end -- module wrapper --------------------------------------------------------
end
end
--=============================================================================
do local _ENV = _ENV
packages['analyzer'] = function (...)
local u = require"util"
local nop, weakkey = u.nop, u.weakkey
local hasVcache, hasCmtcache , lengthcache
= weakkey{}, weakkey{}, weakkey{}
return {
hasV = nop,
hasCmt = nop,
length = nop,
hasCapture = nop
}
end
end
--=============================================================================
do local _ENV = _ENV
packages['charsets'] = function (...)
local s, t, u = require"string", require"table", require"util"
local _ENV = u.noglobals() ----------------------------------------------------
local copy = u.copy
local s_char, s_sub, s_byte, t_concat, t_insert
= s.char, s.sub, s.byte, t.concat, t.insert
local
function utf8_offset (byte)
if byte < 128 then return 0, byte
elseif byte < 192 then
error("Byte values between 0x80 to 0xBF cannot start a multibyte sequence")
elseif byte < 224 then return 1, byte - 192
elseif byte < 240 then return 2, byte - 224
elseif byte < 248 then return 3, byte - 240
elseif byte < 252 then return 4, byte - 248
elseif byte < 254 then return 5, byte - 252
else
error("Byte values between 0xFE and OxFF cannot start a multibyte sequence")
end
end
local
function utf8_validate (subject, start, finish)
start = start or 1
finish = finish or #subject
local offset, char
= 0
for i = start,finish do
local b = s_byte(subject,i)
if offset == 0 then
char = i
success, offset = pcall(utf8_offset, b)
if not success then return false, char - 1 end
else
if not (127 < b and b < 192) then
return false, char - 1
end
offset = offset -1
end
end
if offset ~= 0 then return nil, char - 1 end -- Incomplete input.
return true, finish
end
local
function utf8_next_int (subject, i)
i = i and i+1 or 1
if i > #subject then return end
local c = s_byte(subject, i)
local offset, val = utf8_offset(c)
for i = i+1, i+offset do
c = s_byte(subject, i)
val = val * 64 + (c-128)
end
return i + offset, i, val
end
local
function utf8_next_char (subject, i)
i = i and i+1 or 1
if i > #subject then return end
local offset = utf8_offset(s_byte(subject,i))
return i + offset, i, s_sub(subject, i, i + offset)
end
local
function utf8_split_int (subject)
local chars = {}
for _, _, c in utf8_next_int, subject do
t_insert(chars,c)
end
return chars
end
local
function utf8_split_char (subject)
local chars = {}
for _, _, c in utf8_next_char, subject do
t_insert(chars,c)
end
return chars
end
local
function utf8_get_int(subject, i)
if i > #subject then return end
local c = s_byte(subject, i)
local offset, val = utf8_offset(c)
for i = i+1, i+offset do
c = s_byte(subject, i)
val = val * 64 + ( c - 128 )
end
return val, i + offset + 1
end
local
function split_generator (get)
if not get then return end
return function(subject)
local res = {}
local o, i = true
while o do
o,i = get(subject, i)
res[#res] = o
end
return res
end
end
local
function merge_generator (char)
if not char then return end
return function(ary)
local res = {}
for i = 1, #ary do
t_insert(res,char(ary[i]))
end
return t_concat(res)
end
end
local
function utf8_get_int2 (subject, i)
local byte, b5, b4, b3, b2, b1 = s_byte(subject, i)
if byte < 128 then return byte, i + 1
elseif byte < 192 then
error("Byte values between 0x80 to 0xBF cannot start a multibyte sequence")
elseif byte < 224 then
return (byte - 192)*64 + s_byte(subject, i+1), i+2
elseif byte < 240 then
b2, b1 = s_byte(subject, i+1, i+2)
return (byte-224)*4096 + b2%64*64 + b1%64, i+3
elseif byte < 248 then
b3, b2, b1 = s_byte(subject, i+1, i+2, 1+3)
return (byte-240)*262144 + b3%64*4096 + b2%64*64 + b1%64, i+4
elseif byte < 252 then
b4, b3, b2, b1 = s_byte(subject, i+1, i+2, 1+3, i+4)
return (byte-248)*16777216 + b4%64*262144 + b3%64*4096 + b2%64*64 + b1%64, i+5
elseif byte < 254 then
b5, b4, b3, b2, b1 = s_byte(subject, i+1, i+2, 1+3, i+4, i+5)
return (byte-252)*1073741824 + b5%64*16777216 + b4%64*262144 + b3%64*4096 + b2%64*64 + b1%64, i+6
else
error("Byte values between 0xFE and OxFF cannot start a multibyte sequence")
end
end
local
function utf8_get_char(subject, i)
if i > #subject then return end
local offset = utf8_offset(s_byte(subject,i))
return s_sub(subject, i, i + offset), i + offset + 1
end
local
function utf8_char(c)
if c < 128 then
return s_char(c)
elseif c < 2048 then
return s_char(192 + c/64, 128 + c%64)
elseif c < 55296 or 57343 < c and c < 65536 then
return s_char(224 + c/4096, 128 + c/64%64, 128 + c%64)
elseif c < 2097152 then
return s_char(240 + c/262144, 128 + c/4096%64, 128 + c/64%64, 128 + c%64)
elseif c < 67108864 then
return s_char(248 + c/16777216, 128 + c/262144%64, 128 + c/4096%64, 128 + c/64%64, 128 + c%64)
elseif c < 2147483648 then
return s_char( 252 + c/1073741824,
128 + c/16777216%64, 128 + c/262144%64, 128 + c/4096%64, 128 + c/64%64, 128 + c%64)
end
error("Bad Unicode code point: "..c..".")
end
local
function binary_validate (subject, start, finish)
start = start or 1
finish = finish or #subject
return true, finish
end
local
function binary_next_int (subject, i)
i = i and i+1 or 1
if i >= #subject then return end
return i, i, s_sub(subject, i, i)
end
local
function binary_next_char (subject, i)
i = i and i+1 or 1
if i > #subject then return end
return i, i, s_byte(subject,i)
end
local
function binary_split_int (subject)
local chars = {}
for i = 1, #subject do
t_insert(chars, s_byte(subject,i))
end
return chars
end
local
function binary_split_char (subject)
local chars = {}
for i = 1, #subject do
t_insert(chars, s_sub(subject,i,i))
end
return chars
end
local
function binary_get_int(subject, i)
return s_byte(subject, i), i + 1
end
local
function binary_get_char(subject, i)
return s_sub(subject, i, i), i + 1
end
local charsets = {
binary = {
name = "binary",
binary = true,
validate = binary_validate,
split_char = binary_split_char,
split_int = binary_split_int,
next_char = binary_next_char,
next_int = binary_next_int,
get_char = binary_get_char,
get_int = binary_get_int,
tochar = s_char
},
["UTF-8"] = {
name = "UTF-8",
validate = utf8_validate,
split_char = utf8_split_char,
split_int = utf8_split_int,
next_char = utf8_next_char,
next_int = utf8_next_int,
get_char = utf8_get_char,
get_int = utf8_get_int
}
}
return function (Builder)
local cs = Builder.options.charset or "binary"
if charsets[cs] then
Builder.charset = copy(charsets[cs])
Builder.binary_split_int = binary_split_int
else
error("NYI: custom charsets")
end
end
end
end
--=============================================================================
do local _ENV = _ENV
packages['compat'] = function (...)
local _, debug, jit
_, debug = pcall(require, "debug")
_, jit = pcall(require, "jit")
jit = _ and jit
local compat = {
debug = debug,
lua51 = (_VERSION == "Lua 5.1") and not jit,
lua52 = _VERSION == "Lua 5.2",
luajit = jit and true or false,
jit = jit and jit.status(),
lua52_len = not #setmetatable({},{__len = function()end}),
proxies = pcall(function()
local prox = newproxy(true)
local prox2 = newproxy(prox)
assert (type(getmetatable(prox)) == "table"
and (getmetatable(prox)) == (getmetatable(prox2)))
end),
_goto = not not(loadstring or load)"::R::"
}
return compat
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