forked from vsbenas/parser-gen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
peg-parser.lua
324 lines (261 loc) · 9.39 KB
/
peg-parser.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
local re = require "relabel"
local peg = {}
-- from relabel.lua
local errinfo = {
{"NoPatt", "no pattern found"},
{"ExtraChars", "unexpected characters after the pattern"},
{"ExpPatt1", "expected a pattern after '/' or '//{...}'"},
{"ExpPatt2", "expected a pattern after '&'"},
{"ExpPatt3", "expected a pattern after '!'"},
{"ExpPatt4", "expected a pattern after '('"},
{"ExpPatt5", "expected a pattern after ':'"},
{"ExpPatt6", "expected a pattern after '{~'"},
{"ExpPatt7", "expected a pattern after '{|'"},
{"ExpPatt8", "expected a pattern after '<-'"},
{"ExpPattOrClose", "expected a pattern or closing '}' after '{'"},
{"ExpNum", "expected a number after '^', '+' or '-' (no space)"},
{"ExpNumOrLab", "expected a number or a label after ^"},
{"ExpCap", "expected a string, number, '{}' or name after '->'"},
{"ExpName1", "expected the name of a rule after '=>'"},
{"ExpName2", "expected the name of a rule after '=' (no space)"},
{"ExpName3", "expected the name of a rule after '<' (no space)"},
{"ExpLab1", "expected at least one label after '{'"},
{"ExpLab2", "expected a label after the comma"},
{"ExpNameOrLab", "expected a name or label after '%' (no space)"},
{"ExpItem", "expected at least one item after '[' or '^'"},
{"MisClose1", "missing closing ')'"},
{"MisClose2", "missing closing ':}'"},
{"MisClose3", "missing closing '~}'"},
{"MisClose4", "missing closing '|}'"},
{"MisClose5", "missing closing '}'"}, -- for the captures
{"MisClose6", "missing closing '>'"},
{"MisClose7", "missing closing '}'"}, -- for the labels
{"MisClose8", "missing closing ']'"},
{"MisTerm1", "missing terminating single quote"},
{"MisTerm2", "missing terminating double quote"},
}
local errmsgs = {}
local labels = {}
for i, err in ipairs(errinfo) do
errmsgs[i] = err[2]
labels[err[1]] = i
end
re.setlabels(labels)
function concat(a,b)
return a..b
end
function foldtable(action,t)
local re
local first = true
for key,value in pairs(t) do
if first then
re = value
first = false
else
local temp = re
if action == "suf" then -- suffix actions
local act = value[1]
if act == "*" or act == "?" or act == "+" then
re = {action=act, op1=temp}
else
re = {action=act, op1=temp, op2=value[2]}
end
elseif action == "or" and #value == 2 then -- recovery expression
local labels = value[1]
local op2 = value[2]
re = {action=action, op1=temp, op2=op2, condition=labels}
else
re = {action=action, op1=temp, op2=value}
end
end
end
return re
end
local gram = [=[
pattern <- (exp / %{NoPatt}) (!. / %{ExtraChars})
exp <- S (grammar / alternative)
labels <- {| '{' {: (label / %{ExpLab1}) :} (',' {: (label / %{ExpLab2}) :})* ('}' / %{MisClose7}) |}
alternative <- ( {:''->'or':} {| {: seq :} ('/' (('/' {| {: labels :} S {: (seq / %{ExpPatt1}) :} |}) / (S {: (seq / %{ExpPatt1}) :} ) ) )* |} ) -> foldtable
seq <- ( {:''->'and':} {| {: prefix :}+ |} ) -> foldtable
prefix <- {| {:action: '&' :} S {:op1: (prefix / %{ExpPatt2}) :} |}
/ {| {:action: '!' :} S {:op1: (prefix / %{ExpPatt3}) :} |}
/ suffix
suffix <- ( {:''->'suf':} {| primary S {| suffixaction S |}* |} ) -> foldtable
suffixaction <- {[+*?]}
/ {'^'} {| {:num: [+-]? NUM:} |}
/ '^'->'^LABEL' (label / %{ExpNumOrLab})
/ {'->'} S ((string / {| {:action:'{}'->'poscap':} |} / funcname / {|{:num: NUM :} |}) / %{ExpCap})
/ {'=>'} S (funcname / %{ExpName1})
primary <- '(' (exp / %{ExpPatt4}) (')' / %{MisClose1})
/ term
/ class
/ defined
/ {| {:action: '%'->'label':} ('{' / %{ExpNameOrLab}) S ({:op1: label:} / %{ExpLab1}) S ('}' / %{MisClose7}) |}
/ {| {:action: '{:'->'gcap':} {:op2: defname:} ':' !'}' ({:op1:exp:} / %{ExpPatt5}) (':}' / %{MisClose2}) |}
/ {| {:action: '{:'->'gcap':} ({:op1:exp:} / %{ExpPatt5}) (':}' / %{MisClose2}) |}
/ {| {:action: '='->'bref':} ({:op1: defname:} / %{ExpName2}) |}
/ {| {:action: '{}'->'poscap':} |}
/ {| {:action: '{~'->'subcap':} ({:op1: exp:} / %{ExpPatt6}) ('~}' / %{MisClose3}) |}
/ {| {:action: '{|'->'tcap':} ({:op1: exp:} / %{ExpPatt7}) ('|}' / %{MisClose4}) |}
/ {| {:action: '{'->'scap':} ({:op1: exp:} / %{ExpPattOrClose}) ('}' / %{MisClose5}) |}
/ {| {:action: '.'->'anychar':} |}
/ !frag name S !ARROW
/ '<' (name / %{ExpName3}) ('>' / %{MisClose6}) -- old-style non terminals
grammar <- {| definition+ |}
definition <- {| frag? (token / nontoken) S ARROW ({:rule: exp :} / %{ExpPatt8}) |}
label <- {| {:s: ERRORNAME :} |}
frag <- {:fragment: 'fragment'->'1' :} ![0-9_a-z] S !ARROW
token <- {:rulename: TOKENNAME :} {:token:''->'1':}
nontoken <- {:rulename: NAMESTRING :}
class <- '[' ( ('^' {| {:action:''->'invert':} {:op1: classset :} |} ) / classset ) (']' / %{MisClose8})
classset <- ( {:''->'or':} {| {: (item / %{ExpItem}) :} (!']' {: (item / %{ExpItem}) :})* |} ) -> foldtable
item <- defined / range / {| {:t: . :} |}
range <- {| {:action:''->'range':} {:op1: {| {:s: ({: . :} ('-') {: [^]] :} ) -> concat :} |} :} |}
S <- (%s / '--' [^%nl]*)* -- spaces and comments
name <- {| {:nt: TOKENNAME :} {:token:''->'1':} / {:nt: NAMESTRING :} |}
funcname <- {| {:func: NAMESTRING :} |}
ERRORNAME <- NAMESTRING
NAMESTRING <- [A-Za-z][A-Za-z0-9_]*
TOKENNAME <- [A-Z_]+ ![0-9a-z]
defname <- {| {:s: NAMESTRING :} |}
ARROW <- '<-'
NUM <- [0-9]+
term <- {| '"' {:t: [^"]* :} ('"' / %{MisTerm2}) / "'" {:t: [^']* :} ("'" / %{MisTerm1}) |}
string <- {| '"' {:s: [^"]* :} ('"' / %{MisTerm2}) / "'" {:s: [^']* :} ("'" / %{MisTerm1}) |}
defined <- {| {:action: '%':} {:op1: defname :} |}
]=]
local defs = {foldtable=foldtable, concat=concat}
peg.gram = gram
peg.defs = defs
peg.labels = labels
local p = re.compile ( gram, defs)
--[[
Function: pegToAST(input)
Input: a grammar in PEG format, described in https://github.com/vsbenas/parser-gen
Output: if parsing successful - a table of grammar rules, else - runtime error
Example input: "
Program <- stmt* / SPACE
stmt <- ('a' / 'b')+
SPACE <- ''
"
Example output: {
{rulename = "Program", rule = {action = "or", op1 = {action = "*", op1 = {nt = "stmt"}}, op2 = {nt = "SPACE", token="1"}}},
{rulename = "stmt", rule = {action = "+", op1 = {action="or", op1 = {t = "a"}, op2 = {t = "b"}}}},
{rulename = "SPACE", rule = {t=""}, token=1},
}
The rules are further processed and turned into lpeg compatible format in parser-gen.lua
Action names:
or (has parameter condition for recovery expresions)
and
&
!
+
*
?
^num (num is a number with an optional plus or minus sign)
^label (label is an error label set with setlabels)
->
=>
tcap
gcap (op2= name, anonymous otherwise)
bref
poscap
subcap
scap
anychar
label
%
range
Final token actions:
t - terminal
nt - non terminal
func - function definition
s - literal string
num - literal number
]]--
local function splitlines(str)
local t = {}
local function helper(line) table.insert(t, line) return "" end
helper((str:gsub("(.-)\r?\n", helper)))
return t
end
function peg.pegToAST(input, defs)
local r, e, sfail = p:match(input, defs)
if not r then
local lab
if e == 0 then
lab = "Syntax error"
else
lab = errmsgs[e]
end
local lines = splitlines(input)
local line, col = re.calcline(input, #input - #sfail + 1)
local err = {}
table.insert(err, "L" .. line .. ":C" .. col .. ": " .. lab)
table.insert(err, lines[line])
table.insert(err, string.rep(" ", col-1) .. "^")
error("syntax error(s) in pattern\n" .. table.concat(err, "\n"), 3)
end
return r
end
function peg.print_r ( t ) -- for debugging
local print_r_cache={}
local function sub_print_r(t,indent)
if (print_r_cache[tostring(t)]) then
print(indent.."*"..tostring(t))
else
print_r_cache[tostring(t)]=true
if (type(t)=="table") then
for pos,val in pairs(t) do
if (type(val)=="table") then
print(indent.."["..pos.."] => {")
sub_print_r(val,indent..string.rep(" ",string.len(pos)+8))
print(indent..string.rep(" ",string.len(pos)+6).."}")
else
print(indent.."["..pos.."] => '"..tostring(val).."'")
end
end
else
print(indent..tostring(t))
end
end
end
sub_print_r(t,"")
end
function peg.print_t ( t ) -- for debugging
local print_r_cache={}
local function sub_print_r (t,indent)
if (print_r_cache[tostring(t)]) then
print(indent.."*"..tostring(t))
else
print_r_cache[tostring(t)]=true
if (type(t)=="table") then
local function subprint (pos,val,ident)
if (type(val)=="table") then
print(indent.."{")
sub_print_r(val,indent..string.rep(" ",string.len(pos)+8))
print(indent..string.rep(" ",string.len(pos)-1).."},")
else
if tonumber(pos) then
print(indent.."'"..tostring(val).."',")
else
print(indent..pos.."='"..tostring(val).."',")
end
end
end
if t["rule"] then
subprint("rule",t["rule"],ident)
end
for pos,val in pairs(t) do
if pos ~= "rule" then
subprint(pos,val,ident)
end
end
else
print(indent..tostring(t))
end
end
end
sub_print_r(t,"")
end
return peg