forked from koskenni/pytwolc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwparser.py
445 lines (386 loc) · 15.2 KB
/
twparser.py
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
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import sys, re, json
from codecs import open
from pprint import pprint
import tatsu
from tatsu.ast import AST
from tatsu.walkers import NodeWalker
from tatsu.exceptions import ParseException, FailedParse, ParseError, FailedSemantics
import cfg, hfst
import twexamp
class TwolRegexSemantics(object):
def define(self, ast):
cfg.definitions[ast.left] = ast.right
return ("=", ast.left, ast.right)
def identifier(self, ast):
string = ast.token.strip()
return string
def right_arrow_rule(self, ast):
result = ("=>", ast.left, ast.right)
return result
def left_arrow_rule(self, ast):
result = ("<=", ast.left, ast.right)
return result
def double_arrow_rule(self, ast):
result = ("<=>", ast.left, ast.right)
return result
def exclusion_rule(self, ast):
result = ("/<=", ast.left, ast.right)
return result
def context_lst(self, ast):
result = ast.left.extend(ast.right)
return result
def context(self, ast):
lc = ast.left if ast.left else ""
rc = ast.right if ast.right else ""
result = [(lc, rc)]
return result
def union(self, ast):
return "[{} | {}]".format(ast.left, ast.right)
def intersection(self, ast):
return "[{} & {}]".format(ast.left, ast.right)
def difference(self, ast):
return "[{} - {}]".format(ast.left, ast.right)
def concatenation(self, ast):
return "[{} {}]".format(ast.left, ast.right)
def composition(self, ast):
return "[{} .o. {}]".format(ast.left, ast.right)
def crossproduct(self, ast):
return "[{} .x. {}]".format(ast.left, ast.right)
def Kleene_star(self, ast):
return "[{}]*".format(ast.expr)
def Kleene_plus(self, ast):
return "[{}]+".format(ast.expr)
def Upper(self, ast):
return "[{}].u".format(ast.expr)
def Lower(self, ast):
return "[{}].l".format(ast.expr)
def One_but_not(self, ast):
return r"[PI - [{}]]".format(ast.expr)
def optexpression(self, ast):
return "({})".format(ast.expr)
def subexpression(self, ast):
return "[{}]".format(ast.expr)
def symbol_or_pair(self, ast):
string = ast.token.strip()
failmsg = []
pat = re.compile(r"""^
(?P<up>[a-zšžåäöüõA-ZÅÄÖ0-9]*
|
\{[a-zåäöüõA-ZÅÄÖØ]+\})
:
(?P<lo>[a-zšžåäöüõA-ZÅÄÖØ]*)
$""", re.X)
m = re.match(pat, string)
if m: # it is a pair with a colon
up = m.group("up")
up_quoted = re.sub(r"([{}])", r"%\1", up)
lo = m.group("lo")
if up and (up not in cfg.input_symbol_set):
failmsg.append("input symbol '{}'".format(up))
if lo and (lo not in cfg.output_symbol_set):
failmsg.append("output symbol '{}'".format(lo))
if up and lo and ((up, lo) not in cfg.symbol_pair_set):
failmsg.append("symbol pair '{}'".format(string))
if failmsg:
cfg.error_message = " and ".join(failmsg) + " not in alphabet"
raise FailedSemantics(cfg.error_message)
elif up and lo: # it is a valid pair with a colon
return "{}:{}".format(up_quoted, lo)
elif up and (not lo):
return "[{} .o. PI]".format(up_quoted)
elif (not up) and lo:
return "[PI .o. {}]".format(lo)
else:
return "PI"
m = re.fullmatch(r"[a-zåäöüõA-ZÅÄÖØ]+", string)
if m: # its either a defined sym or a surf ch
if string in cfg.definitions:
return "{}".format(string)
elif (string in cfg.output_symbol_set) and (string in cfg.input_symbol_set):
return "{}:{}".format(string, string)
elif string in {'BEGIN', 'END'}:
return string
cfg.error_message = "'" + string + "' is an invalid pair/definend symbol"
raise FailedSemantics(cfg.error_message)
class TwolFstSemantics(object):
def define(self, ast):
expr_fst = ast.right.copy()
def_name = ast.left
cfg.definitions[def_name] = expr_fst
return ("=", ast.left, ast.right)
def identifier(self, ast):
string = ast.token.strip()
return string
def right_arrow_rule(self, ast):
result = ("=>", ast.left, ast.right)
return result
def left_arrow_rule(self, ast):
result = ("<=", ast.left, ast.right)
return result
def double_arrow_rule(self, ast):
result = ("<=>", ast.left, ast.right)
return result
def exclusion_rule(self, ast):
result = ("/<=", ast.left, ast.right)
return result
def context_lst(self, ast):
left_lst = ast.left.copy()
right_lst = ast.right.copy()
result = left_lst.copy()
result.extend(right_lst)
return result
def context(self, ast):
lc = ast.left.copy() if ast.left else hfst.epsilon_fst()
rc = ast.right.copy() if ast.right else hfst.epsilon_fst()
lc.substitute("END", "BEGIN")
#print(lc)###
#print(rc)###
result = [(lc, rc)]
return result
def union(self, ast):
name = "[{} | {}]".format(ast.left.get_name(), ast.right.get_name())
result_fst = ast.left.copy()
result_fst.disjunct(ast.right)
result_fst.minimize()
result_fst.set_name(name)
return result_fst
def intersection(self, ast):
name = "[{} & {}]".format(ast.left.get_name(), ast.right.get_name())
result_fst = ast.left.copy()
result_fst.conjunct(ast.right)
result_fst.minimize()
result_fst.set_name(name)
return result_fst
def difference(self, ast):
name = "[{} - {}]".format(ast.left.get_name(), ast.right.get_name())
result_fst = ast.left.copy()
result_fst.minus(ast.right)
result_fst.minimize()
result_fst.set_name(name)
return result_fst
def concatenation(self, ast):
name = "[{} {}]".format(ast.left.get_name(), ast.right.get_name())
result_fst = ast.left.copy()
result_fst.concatenate(ast.right)
result_fst.minimize()
result_fst.set_name(name)
return result_fst
def composition(self, ast):
name = "[{} .o. {}]".format(ast.left.get_name(), ast.right.get_name())
result_fst = ast.left.copy()
result_fst.compose(ast.right)
result_fst.minimize()
result_fst.set_name(name)
return result_fst
def crossproduct(self, ast):
name = "[{} .x. {}]".format(ast.left.get_name(), ast.right.get_name())
result_fst = ast.left.copy()
result_fst.cross_product(ast.right)
result_fst.set_name(name)
return result_fst
def Kleene_star(self, ast):
name = "[{}]*".format(ast.expr.get_name())
result_fst = ast.expr.copy()
result_fst.repeat_star()
result_fst.minimize()
result_fst.set_name(name)
return result_fst
def Kleene_plus(self, ast):
name = "[{}]+".format(ast.expr.get_name())
result_fst = ast.expr.copy()
result_fst.repeat_plus()
result_fst.minimize()
result_fst.set_name(name)
return result_fst
def Upper(self, ast):
name = "[{}].u".format(ast.expr.get_name())
result_fst = ast.expr.copy()
result_fst.input_project()
result_fst.set_name(name)
return result_fst
def Lower(self, ast):
name = "[{}].l".format(ast.expr.get_name())
result_fst = ast.expr.copy()
result_fst.output_project()
result_fst.minimize()
result_fst.set_name(name)
return result_fst
def Morphophonemic(self, ast): # Surface completion
name = "[{}].m".format(ast.expr.get_name())
result_fst = ast.expr.copy()
result_fst.input_project()
all_pairs_fst = cfg.all_pairs_fst.copy()
result_fst.compose(all_pairs_fst)
result_fst.minimize()
result_fst.set_name(name)
return result_fst
def Surface(self, ast): # Morphophonemic completion
name = "[{}].s".format(ast.expr.get_name())
temp_fst = ast.expr.copy()
temp_fst.output_project()
result_fst = cfg.all_pairs_fst.copy()
result_fst.compose(temp_fst)
result_fst.minimize()
result_fst.set_name(name)
return result_fst
def One_but_not(self, ast):
name = r"\[{}]".format(ast.expr.get_name())
result_fst = cfg.all_pairs_fst.copy()
result_fst.minus(ast.expr)
result_fst.minimize()
result_fst.set_name(name)
return result_fst
def optexpression(self, ast):
result_fst = ast.expr.copy()
name = result_fst.get_name()
result_fst.optionalize()
result_fst.minimize()
result_fst.set_name("({})".format(name))
return result_fst
def subexpression(self, ast):
name = "[{}]".format(ast.expr.get_name())
result_fst = ast.expr.copy()
result_fst.set_name(name)
return result_fst
def symbol_or_pair(self, ast):
string = ast.token.strip()
failmsg = []
pat = re.compile(r"""^
(?P<up>[a-zšžåäöüõA-ZÅÄÖ0-9'´`]*
|
\{[a-zåäöüõA-ZÅÄÖØ'´`]+\})
:
(?P<lo>[a-zšžåäöüõA-ZÅÄÖØ'´`]*)
$""", re.X)
m = re.match(pat, string)
if m: # it is a pair with a colon
up = m.group("up")
up_quoted = re.sub(r"([{}])", r"%\1", up)
lo = m.group("lo")
if up and (up not in cfg.input_symbol_set):
failmsg.append("input symbol '{}'".format(up))
if lo and (lo not in cfg.output_symbol_set):
failmsg.append("output symbol '{}'".format(lo))
if up and lo and ((up, lo) not in cfg.symbol_pair_set):
failmsg.append("symbol pair '{}'".format(string))
if failmsg:
cfg.error_message = " and ".join(failmsg) + " not in alphabet"
raise FailedSemantics(cfg.error_message)
elif up and lo: # it is a valid pair with a colon
result_fst = hfst.regex(up_quoted + ':' + lo)
result_fst.set_name(string)
return result_fst
elif up and (not lo):
result_fst = hfst.regex(up_quoted)
result_fst.compose(cfg.all_pairs_fst)
result_fst.set_name(string)
return result_fst
elif (not up) and lo:
result_fst = cfg.all_pairs_fst.copy()
lo_fst = hfst.regex(lo)
result_fst.compose(lo_fst)
result_fst.set_name(string)
return result_fst
else:
result_fst = cfg.all_pairs_fst.copy()
result_fst.set_name("PI")
return result_fst
m = re.fullmatch(r"[a-zåäöšžüõA-ZÅÄÖØ'´`]+", string)
if m: # its either a defined sym or a surf ch
if string in cfg.definitions:
result_fst = cfg.definitions[string].copy()
result_fst.set_name(string)
return result_fst
elif (string in cfg.output_symbol_set) and (string in cfg.input_symbol_set):
result_fst = hfst.regex(string)
result_fst.set_name(string)
return result_fst
elif string in {'BEGIN', 'END'}:
result_fst = hfst.regex(string)
result_fst.set_name(string)
return result_fst
cfg.error_message = "'" + string + "' is an invalid pair/definend symbol"
raise FailedSemantics(cfg.error_message)
def boundary(self, ast):
result_fst = hfst.regex("END")
#print(result_fst)####
result_fst.set_name(".#.")
return result_fst
def init(grammar_file='../twolcsyntax.ebnf'):
"""Initializes the module and compiles and returns a tatsu parser
grammar_file -- the name of the file containing the EBNF grammar for rules
"""
grammar = open(grammar_file).read()
parser = tatsu.compile(grammar)
return parser
def parse_rule(parser, line_nl, start="expr_start"):
"""Parse one rule or definiton or any constituent given as start
parser -- a tatsu parser which parses the EBNF grammar for two-level rules
line_nl -- the string that contains the rule or definition to be parsed
keyword arguments:
start -- the element in the EBNF grammar where to start the parsing
"""
line = line_nl.strip()
if (not line) or line[0] == '!':
return "!", None, None, line # it was a comment or an empty line
rulepat = r"^.* +(=|<=|=>|<=>|/<=) +.*$"
try:
m = re.match(rulepat, line)
if m:
#print("groups:", m.groups())###
if m.group(1) == '=':
op, name, expr_fst = parser.parse(line, start='def_start',
semantics=TwolFstSemantics())
return op, name, expr_fst, line
elif m.group(1) in {'=>', '<=', '<=>', '/<='}:
op, x_fst, contexts = parser.parse(line, start='rul_start',
semantics=TwolFstSemantics())
return op, x_fst, contexts, line
else:
return "?", None, None, line
except ParseException as e:
msg = str(e)
lst = msg.split("\n")
if len(lst) >= 3:
print(lst[1])
print(lst[2], "<---", e.__class__.__name__, "ERROR HERE")
if cfg.error_message:
print(" ", cfg.error_message)
cfg.error_message = ""
return "?", None, None, line
else:
print(str(e))
return "?", None, None, line
if __name__ == '__main__':
import hfst, argparse, twbt, cfg, twexamp
arpar = argparse.ArgumentParser(description="A compiler and tester for two-level rules")
arpar.add_argument("start",
help="start parseing from",
default="expr_start")
args = arpar.parse_args()
twexamp.read_fst(filename="nounex.fst")
parser = init()
for line_nl in sys.stdin:
line = line_nl.strip()
#print(line)
result = parser.parse(line, start=args.start,
semantics=TwolFstSemantics())
if args.start == "def_start":
op, left, right, source = result
print(left, "=")
twbt.ppfst(right)
elif args.start == "rul_start":
op, left, right, source = result
twbt.ppfst(left)
print(op)
for lc, rc in right:
twbt.ppfst(lc, title="left context")
twbt.ppfst(rc, title="right context")
elif args.start == "expr_start":
fst = result
#print(fst)
twbt.ppfst(fst, True)
elif op == "?":
print("Incorrect: " + line)