ParserCombinators.py 72 KB
Newer Older
Eckhart Arnold's avatar
Eckhart Arnold committed
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
#!/usr/bin/python3

"""ParserCombinators.py - parser combinators for left-recursive grammers

Copyright 2016  by Eckhart Arnold

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


Module parser_combinators contains a number of classes that together make up
parser combinators for left-recursive grammers. For each element of the
extended Backus-Naur-Form as well as for a regular expression token a class is
defined. The set of classes can be used to define a parser for
(ambiguous) left-recursive grammers.


References and Acknowledgements:

Dominikus Herzberg: Objekt-orientierte Parser-Kombinatoren in Python,
Blog-Post, September, 18th 2008 on denkspuren. gedanken, ideen, anregungen und
links rund um informatik-themen, URL:
http://denkspuren.blogspot.de/2008/09/objekt-orientierte-parser-kombinatoren.html

Dominikus Herzberg: Eine einfache Grammatik für LaTeX, Blog-Post, September,
18th 2008 on denkspuren. gedanken, ideen, anregungen und links rund
um informatik-themen, URL:
http://denkspuren.blogspot.de/2008/09/eine-einfache-grammatik-fr-latex.html

Dominikus Herzberg: Uniform Syntax, Blog-Post, February, 27th 2007 on
denkspuren. gedanken, ideen, anregungen und links rund um informatik-themen,
URL:
http://denkspuren.blogspot.de/2007/02/uniform-syntax.html

Richard A. Frost, Rahmatullah Hafiz and Paul Callaghan: Parser Combinators
for Ambiguous Left-Recursive Grammars, in: P. Hudak and D.S. Warren (Eds.):
PADL 2008, LNCS 4902, pp. 167–181, Springer-Verlag Berlin Heidelberg 2008.

Juancarlo Añez: grako, a PEG parser generator in Python,
https://bitbucket.org/apalala/grako
"""

52
# TODO: Replace copy.deepcopy() call in ParserHeadquarter class by custom copy()-methods in the Parser classes. Is that really better?
Eckhart Arnold's avatar
Eckhart Arnold committed
53
54
55
56


import collections
import copy
57
import hashlib
Eckhart Arnold's avatar
Eckhart Arnold committed
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
import keyword
import os

# try:
#     import regex as re
# except ImportError:
#     import re
import re       # as of now use `re` - even hough `regex` appears to be better
import sys
import types
from functools import reduce, partial


DEBUG = True
DEBUG_DUMP_AST = ""


def DEBUG_DUMP_SYNTAX_TREE(parser_root, syntax_tree, compiler, ext):
    global DEBUG, DEBUG_DUMP_AST
    if DEBUG:
        if os.path.exists("DEBUG"):
            prefix = "DEBUG" if os.path.isdir("DEBUG") else ""
        else:
            os.mkdir("DEBUG")
            prefix = "DEBUG"
        ast_file_name = (DEBUG_DUMP_AST or compiler.grammar_name or \
                         parser_root.__class__.__name__) + ext
85
86
        with open(os.path.join(prefix, ast_file_name), "w",
                  encoding="utf-8") as f:
Eckhart Arnold's avatar
Eckhart Arnold committed
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
            f.write(syntax_tree.as_sexpr())


class Error(Exception):
    """Base class for errors in module `ParserCombinators`.
    """
    pass


##############################################################################
#
# Scanner / Preprocessor support
#
##############################################################################


RX_SCANNER_TOKEN = re.compile('\w+')
BEGIN_SCANNER_TOKEN = '\x1b'
END_SCANNER_TOKEN = '\x1c'


def make_token(token, argument=''):
    assert RX_SCANNER_TOKEN.match(token)
    assert argument.find(BEGIN_SCANNER_TOKEN) < 0
    assert argument.find(END_SCANNER_TOKEN) < 0
    return BEGIN_SCANNER_TOKEN + token + argument + END_SCANNER_TOKEN


nil_scanner = lambda text: text


##############################################################################
#
# Parser tree
#
##############################################################################

def line_col(text, pos):
    """Returns the 'pos' within text as (line, column)-tuple.
    """
    line = text.count("\n", 0, pos) + 1
    column = pos - text.rfind("\n", 0, pos)
    return line, column


class Node:
    def __init__(self, parser, result):
        # self.children = False # will be set by the following assignment
        self.result = result   # sets self.children to `True` if there are any
        self.parser = parser or ZOMBIE_PARSER
        self.errors = []
        self.fatal_error = any(r.fatal_error for r in self.result) \
            if self.children else False
        self.len_before_AST = len(self.result) if not self.children \
            else sum(child.len_before_AST for child in self.result)
        self.pos = 0

    def __str__(self):
        if self.children:
            # assert all(isinstance(child, Node) for child in self.result), \
            #     str(self.result)
            return "".join([str(child) for child in self.result])
        return str(self.result)

    @property
    def result(self):
        return self._result

    @result.setter
    def result(self, result):
        assert (isinstance(result, tuple) and
                all(isinstance(child, Node) for child in result)) or \
               isinstance(result, Node) or \
               isinstance(result, str)
        if isinstance(result, Node):
            result = (result,)
        self._result = result or ''
        self.children = result if isinstance(result, tuple) else ()

    @property
    def pos(self):
        return self._pos

    @pos.setter
    def pos(self, pos):
        self._pos = pos
        offset = 0
        for child in self.children:
            child.pos = pos + offset
            offset += child.len_before_AST

    def as_tree(self, tab, openF, closeF, dataF=lambda s: s):
        """Generates a tree representation of this node and its children
        in string from. This could be an XML-representation or a lisp-like
        S-expression. Exactly which form the tree representation takes is
        defined by the parameters of the function.

        Args:
            tab:      the tab string for indentation, e.g. '\t' or '    '
            openF:    a function that returns an opening string (e.g. an
                      XML-tag) for a given node.
            closeF:   a function that returns a closeF string (e.g. an
                      XML-tag for a given node.
            dataF:    filters data string before printing, e.g. to add
                      quotation marks
        Returns:
            a string that contains a (serialized) tree representation of the
            node and its children.
        """
        head = openF(self)
        tail = closeF(self)

        if not self.result:
            return head + tail

        head = head + '\n'        # place the head, tail and content
        tail = '\n' + tail        # of the node on different lines

        if self.children:
            content = []
            for child in self.result:
                subtree = child.as_tree(tab, openF, closeF, dataF).split('\n')
                content.append('\n'.join((tab + s) for s in subtree))
            return head + '\n'.join(content) + tail

        return head + '\n'.join([tab + dataF(s)
                                 for s in str(self.result).split('\n')]) + tail

    def as_sexpr(self, src=None):
        """Returns content as S-expression, i.e. in lisp-like form.

        Args:
            src:    The source text or `None`. In case the source text is given
                    the position of the element in the text will be reported as
                    line and column.
        """
        def opening(node):
224
            s = '(' + str(node.parser) # (node.parser.component or node.parser.__class__.__name__)
Eckhart Arnold's avatar
Eckhart Arnold committed
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
            # s += " '(pos %i)" % node.pos
            if src:
                s += " '(pos %i  %i %i)" % (node.pos, *line_col(src, node.pos))
            if node.errors:
                s += " '(err '(%s))" % ' '.join(str(err).replace('"', r'\"')
                                                for err in node.errors)
            return s
        return self.as_tree('    ', opening, lambda node: ')',
                            lambda s: '"' + s.replace('"', r'\"') + '"')

    def as_xml(self, src=None):
        """Returns content as S-expression, i.e. in lisp-like form.

        Args:
            src:    The source text or `None`. In case the source text is given
                    the position will also be reported as line and column.
        """

        def opening(node):
            s = '<' + (node.parser.component or node.parser.__class__.__name__)
            # s += ' pos="%i"' % node.pos
            if src:
                s += ' line="%i" col="%i"' % line_col(src, node.pos)
            if node.errors:
                s += ' err="%s"' % ''.join(str(err).replace('"', r'\"')
                                           for err in node.errors)
            s += ">"
            return s

        def closing(node):
            s = '</' + \
                (node.parser.component or node.parser.__class__.__name__) + '>'
            return s

        return self.as_tree('    ', opening, closing, lambda s: s)

    def add_error(self, error):
        self.errors.append(error)
        return self

    def collect_errors(self, clear=False):
        """Returns all errors of this node or any child node in the form of a
        list of tuples (position: int, error_message: string), where position
        is always relative to this node. If `clear` is true, errors messages
        are cleared after collecting.
        """
        errors = [(0, self.errors)] if self.errors else []
        if clear:
            self.errors = []
            self.fatal_error = False
        if self.children:
            offset = 0
            for child in self.result:
                errors.extend((pos + offset, err)
                              for pos, err in child.collect_errors(clear))
                offset += child.len_before_AST
        return errors


def error_messages(text, errors):
    """Converts the list of `errors` collected from the root node of the
    parse tree of `text` into a human readable (and IDE or editor parsable
    text) with line an column numbers. Error messages are separated by an
    empty line.
    """
    return "\n\n".join("line: %i, column: %i, error: %s" %
                       (*line_col(text, entry[0]), " and ".join(entry[1]))
                       for entry in errors)


##############################################################################
#
# Parser base classes
#
##############################################################################

301
302
LEFT_RECURSION_DEPTH = 10   # because of pythons recursion depth limit, this
                            # value ought not to be set too high
303
MAX_DROPOUTS = 25   # stop trying to recover parsing after so many errors
Eckhart Arnold's avatar
Eckhart Arnold committed
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324

WHITESPACE_KEYWORD = 'wspc__'
TOKEN_KEYWORD = 'token__'


def left_recursion_guard(callfunc):
    def call(parser, text):
        try:
            location = len(text)
            # if location has already been visited by the current parser,
            # return saved result
            #### if parser.component: print(parser.component, location, text[:10] + '...')
            if location in parser.visited:
                return parser.visited[location]
            # break left recursion at the maximum allowed depth
            if parser.recursion_counter.setdefault(location, 0) > \
                    LEFT_RECURSION_DEPTH:
                return None, text

            parser.recursion_counter[location] += 1

325
326
            parser.headquarter.call_stack.append(parser)
            parser.headquarter.moving_forward = True
Eckhart Arnold's avatar
Eckhart Arnold committed
327
328
329

            # run original __call__ method
            result = callfunc(parser, text)
330
331
332
333
334
335
            # if DEBUG: print(str(parser), len(result[1]))

            if parser.headquarter.moving_forward:  # and result[0] == None
                parser.headquarter.moving_forward = False
                st = "->".join((str(p) for p in parser.headquarter.call_stack))
                if result[0]:
336
337
                    # print("HIT!", st, '\t"%s"' % str(result[0]).replace('\n', ' '))
                    pass
338
                else:
Eckhart Arnold's avatar
Eckhart Arnold committed
339
340
341
                    # t = text[:20].replace('\n',' ')
                    # print("FAIL", st, '\t"%s"' % (t + ("..." if t else "")))
                    pass
342
            parser.headquarter.call_stack.pop()
Eckhart Arnold's avatar
Eckhart Arnold committed
343
344
345
346
347

            if result[0] is not None:
                # in case of a recursive call saves the result of the first
                # (or left-most) call that matches
                parser.visited[location] = result
348
                parser.headquarter.last_node = result[0]
Eckhart Arnold's avatar
Eckhart Arnold committed
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
            elif location in parser.visited:
                # if parser did non match but a saved result exits, assume
                # left recursion and use the saved result
                result = parser.visited[location]

            parser.recursion_counter[location] -= 1

        except RecursionError:
            node = Node(None, text[:min(10, max(1, text.find("\n")))] + " ...")
            node.add_error("maximum recursion depth of parser reached; "
                           "potentially due to too many errors!")
            node.fatal_error = True
            result = (node, '')

        return result

    return call


class ParserMetaClass(type):
    def __init__(C, name, bases, attrs):
Eckhart Arnold's avatar
Eckhart Arnold committed
370
371
372
373
374
        # The following condition is necessary for classes that don't override
        # the __call__() method, because in these cases the non-overridden
        # __call__()-method would be substituted a second time!
        if C.__call__.__code__ != left_recursion_guard(C.__call__).__code__:
            C.__call__ = left_recursion_guard(C.__call__)
Eckhart Arnold's avatar
Eckhart Arnold committed
375
376
377
        super(ParserMetaClass, C).__init__(name, bases, attrs)


378
379
380
381
382
383
384
385

def sane_parser_name(name):
    """"Checks whether given name is an acceptable parser name. Parser names
    must not be preceeded or succeeded by a double underscore '__'!
    """
    return name and name[:2] != '__' and name[-2:] != '__'


Eckhart Arnold's avatar
Eckhart Arnold committed
386
387
class Parser(metaclass=ParserMetaClass):
    def __init__(self, component=None):
Eckhart Arnold's avatar
Eckhart Arnold committed
388
        assert component is None or isinstance(component, str), str(component)
389
        self.component = component or ''
390
        self.headquarter = None          # head quater for global variables etc.
Eckhart Arnold's avatar
Eckhart Arnold committed
391
392
393
394
395
396
397
398
        self.visited = dict()
        self.recursion_counter = dict()
        self.cycle_detection = set()

    def __call__(self, text):
        raise NotImplementedError

    def __str__(self):
399
        return self.component or self.__class__.__name__
Eckhart Arnold's avatar
Eckhart Arnold committed
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414

    def apply(self, func):
        """Applies function `func(parser)` recursively to this parser and all
        descendendants of the tree of parsers. MIND THAT due to the current
        implementation of cycle detection one and the same function can never
        be applied twice!
        """
        if func in self.cycle_detection:
            return False
        else:
            self.cycle_detection.add(func)
            func(self)
            return True


415
class ParserHeadquarter:
416
417
418
419
420
421
422
423
424
425
426
427
428
    @classmethod
    def _connect_commponent_names_to_parsers(cls):
        """Initializes the `parser.component` fields of those
        Parser objects that are directly assigned to a class field with
        the field's name, e.g.
            class Grammar(ParserHeadquarter):
                ...
                symbol = RE('(?!\\d)\\w+')
        After the call of this method symbol.component == "symbol"
        holds. If the `component` field has been assigned a different
        name in the constructor, a ValueError will be raised.
        """
        Cdict = cls.__dict__
429
430
431
432
        for entry in Cdict:
            if sane_parser_name(entry):
                parser = Cdict[entry]
                if isinstance(parser, Parser):
433
                    # print(type(parser), parser.component, entry)
434
                    if isinstance(parser, Forward):
435
436
437
438
439
                        assert not parser.component or parser.component == entry
                        if parser.component and parser.component != entry:
                            raise ValueError(("Parser named %s should not be "
                                " assigned to field with different name: %s"
                                % (parser.component, entry)))
440
441
442
                        parser.parser.component = entry
                    else:
                        parser.component = entry
443
444
445
446


    def __init__(self):
        self._connect_commponent_names_to_parsers()
447
        self.root__ = copy.deepcopy(self.__class__.root__)
Eckhart Arnold's avatar
Eckhart Arnold committed
448
        self.root__.apply(self._add_parser)
449
        self.variables = dict()                 # support for Pop and Retrieve operators
Eckhart Arnold's avatar
Eckhart Arnold committed
450
        self.last_node = None
451
452
        self.call_stack = []
        self.moving_forward = True
Eckhart Arnold's avatar
Eckhart Arnold committed
453
454
        self.unused = True

455

Eckhart Arnold's avatar
Eckhart Arnold committed
456
    def _add_parser(self, parser):
457
        """Adds the copy of the parser object to this instance of ParserHeadquarter.
Eckhart Arnold's avatar
Eckhart Arnold committed
458
        """
459
        # print(parser.component)
460
461
        if sane_parser_name(parser.component):  # overwrite class variable with instance variable
            setattr(self, parser.component, parser)
462
        parser.headquarter = self
Eckhart Arnold's avatar
Eckhart Arnold committed
463
464
465
466
467
468
469
470
471
472
473
474

    def parse(self, document):
        """Parses a document with with parser-combinators.

        Args:
            document (str): The source text to be parsed.
            parser (Parser):  The root object of the parser combinator ensemble
                that is to be used for parsing the source text.
        Returns:
            Node: The root node ot the parse tree.
        """
        assert self.unused, ("Parser has been used up. Please create a new "
475
                             "instance of the ParserHeadquarter class!")
Eckhart Arnold's avatar
Eckhart Arnold committed
476
477
        self.unused = False
        parser = self.root__
478
        stitches = []
Eckhart Arnold's avatar
Eckhart Arnold committed
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
        rest = document
        while rest and len(stitches) < MAX_DROPOUTS:
            result, rest = parser(rest)
            if rest:
                fwd = rest.find("\n") + 1 or len(rest)
                skip, rest = rest[:fwd], rest[fwd:]
                if result is None:
                    error_msg = "Parser did not match! Invalid source file?"
                else:
                    stitches.append(result)
                    error_msg = "Parser stopped before end" + \
                                ("! trying to recover..."
                                 if len(stitches) < MAX_DROPOUTS
                                 else " too often! Terminating parser.")
                stitches.append(Node(None, skip))
                stitches[-1].add_error(error_msg)
        if stitches:
            if result and stitches[-1] != result:
                stitches.append(result)
            if rest:
                stitches.append(Node(None, rest))
        return result if not stitches else Node(None, tuple(stitches))


ZOMBIE_PARSER = Parser()  # zombie object to avoid distinction of cases
# for the Node.parser variable
RE_WSPC = Parser(WHITESPACE_KEYWORD)  # Dummy Parser for comments that were captured
506
                                      # by an RE Parser via the `comment`-parameter
Eckhart Arnold's avatar
Eckhart Arnold committed
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


##############################################################################
#
# Token and Regular Expression parser classes (i.e. leaf classes)
#
##############################################################################


class ScannerToken(Parser):
    def __init__(self, scanner_token):
        assert isinstance(scanner_token, str) and scanner_token and \
               scanner_token.isupper()
        assert RX_SCANNER_TOKEN.match(scanner_token)
        super(ScannerToken, self).__init__(scanner_token)

    def __call__(self, text):
        if text[0:1] == BEGIN_SCANNER_TOKEN:
            end = text.find(END_SCANNER_TOKEN, 1)
            if end < 0:
                node = Node(self, '').add_error(
                    'END_SCANNER_TOKEN delimiter missing from scanner token. '
                    '(Most likely due to a scanner bug!)')
                return node, text[1:]
            elif end == 0:
                node = Node(self, '').add_error(
                    'Scanner token cannot have zero length. '
                    '(Most likely due to a scanner bug!)')
                return node, text[2:]
            elif text.find(BEGIN_SCANNER_TOKEN, 1, end) >= 0:
                node = Node(self, text[len(self.component) + 1:end])
                node.add_error(
                    'Scanner tokens must not be nested or contain '
                    'BEGIN_SCANNER_TOKEN delimiter as part of their argument. '
                    '(Most likely due to a scanner bug!)')
                return node, text[end:]
            if text[1:len(self.component) + 1] == self.component:
                return Node(self, text[len(self.component) + 1:end]), \
                       text[end + 1:]
        return None, text


class RegExp(Parser):
550
    def __init__(self, regexp, orig_re = '', component=None):
Eckhart Arnold's avatar
Eckhart Arnold committed
551
        super(RegExp, self).__init__(component)
552
        self.component = component
Eckhart Arnold's avatar
Eckhart Arnold committed
553
554
555
556
557
558
559
560
561
562
        self.regexp = re.compile(regexp) if isinstance(regexp, str) else regexp
        self.orig_re = orig_re

    def __deepcopy__(self, memo):
        # this method is obsolete with the new `regex` module!
        try:
            regexp = copy.deepcopy(self.regexp)
        except TypeError:
            regexp = self.regexp.pattern
        duplicate = RegExp(self.component, regexp, self.orig_re)
563
564
565
        duplicate.component = self.component # this ist needed!!!!
        duplicate.regexp = self.regexp
        duplicate.orig_re = self.orig_re
566
        duplicate.headquarter = self.headquarter
Eckhart Arnold's avatar
Eckhart Arnold committed
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
        duplicate.visited = copy.deepcopy(self.visited, memo)
        duplicate.recursion_counter = copy.deepcopy(self.recursion_counter,
                                                    memo)
        return duplicate

    def __call__(self, text):
        match = text[0:1] != BEGIN_SCANNER_TOKEN and self.regexp.match(text)  # ESC starts a scanner token.
        if match:
            end = match.end()
            groups = set(match.groups())
            if len(groups) >= 1:
                split = sorted([i for i in reduce(lambda s, r: s | set(r),
                                                match.regs, set()) if i >= 0])
                parts = (text[i:j] for i, j in zip(split[:-1], split[1:]))
                result = tuple(Node(None if part in groups else RE_WSPC, part)
                               for part in parts)
                if all(r.parser == RE_WSPC for r in result):
                    return Node(RE_WSPC, text[:end]), text[end:]
                return Node(self, result), text[end:]
            return Node(self, match.group()), text[end:]
        return None, text

    def __str__(self):
590
        pattern = self.orig_re or self.regexp.pattern  # for readability of error messages !
591
        return Parser.__str__(self) + "/" + pattern + "/"
Eckhart Arnold's avatar
Eckhart Arnold committed
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610


def escape_re(s):
    """Returns `s` with all regular expression special characters escaped.
    """
    assert isinstance(s, str)
    re_chars = r"\.^$*+?{}[]()#<>=|!"
    for esc_ch in re_chars:
        s = s.replace(esc_ch, '\\' + esc_ch)
    return s


def mixin_comment(whitespace, comment):
    """Mixes comment-regexp into whitespace regexp.
    """
    wspc = '(?:' + whitespace + '(?:' + comment + whitespace + ')*)'
    return wspc


611
def RE(regexp, wspcL='', wspcR='', component=None):
Eckhart Arnold's avatar
Eckhart Arnold committed
612
613
614
    rA = '('
    rB = '\n)' if regexp.find('(?x)') >= 0 else ')'     # otherwise the closing bracket might erroneously
                                                        # be append to the end of a line comment!
615
616
    return RegExp(wspcL + rA + regexp + rB + wspcR, regexp,
                  component or TOKEN_KEYWORD)
Eckhart Arnold's avatar
Eckhart Arnold committed
617
618


619
620
def Token(token, wspcL='', wspcR='', component=None):
    return RE(escape_re(token), wspcL, wspcR, component)
Eckhart Arnold's avatar
Eckhart Arnold committed
621
622
623
624
625
626
627
628
629
630


##############################################################################
#
# Combinator parser classes (i.e. trunk classes of the parser tree)
#
##############################################################################


class UnaryOperator(Parser):
631
    def __init__(self, parser, component=None):
Eckhart Arnold's avatar
Eckhart Arnold committed
632
633
634
635
636
637
638
639
        super(UnaryOperator, self).__init__(component)
        assert isinstance(parser, Parser)
        self.parser = parser

    def apply(self, func):
        if super(UnaryOperator, self).apply(func):
            self.parser.apply(func)

640
641
642
    # def __str__(self):
    #     return Parser.__str__(self) + \
    #            ("" if self.component else "(" + str(self.parser) + ")")
Eckhart Arnold's avatar
Eckhart Arnold committed
643
644
645


class NaryOperator(Parser):
646
    def __init__(self, *parsers, component=None):
Eckhart Arnold's avatar
Eckhart Arnold committed
647
        super(NaryOperator, self).__init__(component)
648
        assert all([isinstance(parser, Parser) for parser in parsers]), str(parsers)
Eckhart Arnold's avatar
Eckhart Arnold committed
649
650
651
652
653
654
655
        self.parsers = parsers

    def apply(self, func):
        if super(NaryOperator, self).apply(func):
            for parser in self.parsers:
                parser.apply(func)

656
657
658
659
660
    # def __str__(self):
    #     return Parser.__str__(self) + \
    #            ("" if self.component else str([str(p) for p in self.parsers]))
    #     # return "(" + ",\n".join(["\n    ".join(str(parser).split("\n"))
    #     #                          for parser in self.parsers]) + ")"
Eckhart Arnold's avatar
Eckhart Arnold committed
661
662
663


class Optional(UnaryOperator):
664
665
    def __init__(self, parser, component=None):
        super(Optional, self).__init__(parser, component)
Eckhart Arnold's avatar
Eckhart Arnold committed
666
667
        assert isinstance(parser, Parser)
        assert not isinstance(parser, Optional), \
668
669
            "Nesting options would be redundant: %s(%s)" % \
            (str(component), str(parser.component))
Eckhart Arnold's avatar
Eckhart Arnold committed
670
        assert not isinstance(parser, Required), \
671
672
            "Nestion options with required elements is contradictory: " \
            "%s(%s)" % (str(component), str(parser.component))
Eckhart Arnold's avatar
Eckhart Arnold committed
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692

    def __call__(self, text):
        node, text = self.parser(text)
        if node:
            return Node(self, node), text
        return Node(self, ()), text


class ZeroOrMore(Optional):
    def __call__(self, text):
        results = ()
        while text:
            node, text = self.parser(text)
            if not node:
                break
            results += (node,)
        return Node(self, results), text


class OneOrMore(UnaryOperator):
693
694
    def __init__(self, parser, component=None):
        super(OneOrMore, self).__init__(parser, component)
Eckhart Arnold's avatar
Eckhart Arnold committed
695
        assert not isinstance(parser, Optional), \
696
697
            "Use ZeroOrMore instead of nesting OneOrMore and Optional: " \
            "%s(%s)" % (str(component), str(parser.component))
Eckhart Arnold's avatar
Eckhart Arnold committed
698
699
700
701
702
703
704
705
706

    def __call__(self, text):
        results = ()
        text_ = text
        while text_:
            node, text_ = self.parser(text_)
            if not node:
                break
            results += (node,)
707
        if results == ():       # TODO: Add debugging print statements or breakpoint for `Bedeutungsposition` here!!
Eckhart Arnold's avatar
Eckhart Arnold committed
708
709
710
711
712
            return None, text
        return Node(self, results), text_


class Sequence(NaryOperator):
713
714
    def __init__(self, *parsers, component=None):
        super(Sequence, self).__init__(*parsers, component=component)
Eckhart Arnold's avatar
Eckhart Arnold committed
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
        assert len(self.parsers) >= 1
        # commented, because sequences can be empty:
        # assert not all(isinstance(p, Optional) for p in self.parsers)

    def __call__(self, text):
        results = ()
        text_ = text
        for parser in self.parsers:
            node, text_ = parser(text_)
            if not node:
                return node, text
            if node.result:  # Nodes with zero-length result are silently omitted
                results += (node,)
            if node.fatal_error:
                break
        assert len(results) <= len(self.parsers)
        return Node(self, results), text_


class Alternative(NaryOperator):
735
736
    def __init__(self, *parsers, component=None):
        super(Alternative, self).__init__(*parsers, component=component)
Eckhart Arnold's avatar
Eckhart Arnold committed
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
        assert len(self.parsers) >= 1
        assert all(not isinstance(p, Optional) for p in self.parsers)

    def __call__(self, text):
        for parser in self.parsers:
            node, text_ = parser(text)
            if node:
                return Node(self, node), text_
        return None, text


##############################################################################
#
# Flow control operators
#
##############################################################################


class FlowOperator(UnaryOperator):
756
757
    def __init__(self, parser, component=None):
        super(FlowOperator, self).__init__(parser, component)
Eckhart Arnold's avatar
Eckhart Arnold committed
758
759
760


class Required(FlowOperator):
761
    # TODO: Add constructor that checks for logical errors, like `Required(Optional(...))` constructs
Eckhart Arnold's avatar
Eckhart Arnold committed
762
763
764
765
766
767
768
    def __call__(self, text):
        node, text_ = self.parser(text)
        if not node:
            m = re.search(r'\s(\S)', text)
            i = max(1, m.regs[1][0]) if m else 1
            node = Node(self, text[:i])
            text_ = text[i:]
Eckhart Arnold's avatar
Eckhart Arnold committed
769
            # assert False, "*"+text[:i]+"*"
Eckhart Arnold's avatar
Eckhart Arnold committed
770
771
772
773
774
775
            node.add_error('%s expected; "%s..." found!' %
                           (str(self.parser), text[:10]))
        return node, text_


class Lookahead(FlowOperator):
776
777
    def __init__(self, parser, component=None):
        super(Lookahead, self).__init__(parser, component)
Eckhart Arnold's avatar
Eckhart Arnold committed
778
779
780
781
782
783
784
785

    def __call__(self, text):
        node, text_ = self.parser(text)
        if self.sign(node is not None):
            return Node(self, ''), text
        else:
            return None, text

786
787
    def sign(self, bool_value):
        return bool_value
Eckhart Arnold's avatar
Eckhart Arnold committed
788
789


790
791
792
class NegativeLookahead(Lookahead):
    def sign(self, bool_value):
        return not bool_value
Eckhart Arnold's avatar
Eckhart Arnold committed
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807


def iter_right_branch(node):
    """Iterates over the right branch of `node` starting with node itself.
    Iteration is stopped if either there are no child nodes any more or
    if the parser of a node is a Lookahead parser. (Reason is: Since
    lookahead nodes do not advance the parser, it does not make sense
    to look back to them.)
    """
    while node and not isinstance(node.parser, Lookahead):  # the second condition should not be necessary
        yield node                                          # for well-formed EBNF code
        node = node.children[-1] if node.children else None


class Lookbehind(FlowOperator):
Eckhart Arnold's avatar
Eckhart Arnold committed
808
    def __init__(self, parser, component=None):
809
        super(Lookbehind, self).__init__(parser, component)
Eckhart Arnold's avatar
Eckhart Arnold committed
810
        print("WARNING: Lookbehind Operator is experimental!")
Eckhart Arnold's avatar
Eckhart Arnold committed
811
812

    def __call__(self, text):
813
        if isinstance(self.headquarter.last_node, Lookahead):
Eckhart Arnold's avatar
Eckhart Arnold committed
814
815
816
817
818
819
820
            return Node(self, '').add_error('Lookbehind right after Lookahead '
                                            'does not make sense!'), text
        if self.sign(self.condition()):
            return Node(self, ''), text
        else:
            return None, text

821
822
823
    def sign(self, bool_value):
        return bool_value

Eckhart Arnold's avatar
Eckhart Arnold committed
824
825
    def condition(self):
        node = None
826
        for node in iter_right_branch(self.headquarter.last_node):
Eckhart Arnold's avatar
Eckhart Arnold committed
827
828
829
830
831
832
833
834
            if node.parser.component == self.parser.component:
                return True
        if node and isinstance(self.parser, RegExp) and \
                self.parser.regexp.match(str(node)):    # Is there really a use case for this?
            return True
        return False


835
836
837
def NegativeLookbehind(Lookbehind):
    def sign(self, bool_value):
        return not bool_value
Eckhart Arnold's avatar
Eckhart Arnold committed
838
839
840
841
842
843
844
845
846
847


##############################################################################
#
# Capture and Retrieve operators (for passing variables in the parser)
#
##############################################################################


class Capture(UnaryOperator):
Eckhart Arnold's avatar
Eckhart Arnold committed
848
849
    def __init__(self, parser, component=None):
        super(Capture, self).__init__(parser, component)
Eckhart Arnold's avatar
Eckhart Arnold committed
850
851
852
853

    def __call__(self, text):
        node, text = self.parser(text)
        if node:
854
            stack = self.headquarter.variables.setdefault(self.component, [])
Eckhart Arnold's avatar
Eckhart Arnold committed
855
856
857
858
859
            stack.append(str(node))
        return Node(self, node), text


class Retrieve(Parser):
Eckhart Arnold's avatar
Eckhart Arnold committed
860
    def __init__(self, symbol, component=None):
Eckhart Arnold's avatar
Eckhart Arnold committed
861
        super(Retrieve, self).__init__(component)
862
        self.symbol = symbol # if isinstance(symbol, str) else symbol.component
Eckhart Arnold's avatar
Eckhart Arnold committed
863
864

    def __call__(self, text):
865
866
867
        symbol = self.symbol if isinstance(self.symbol, str) \
                             else self.symbol.component
        stack = self.headquarter.variables[symbol]
Eckhart Arnold's avatar
Eckhart Arnold committed
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
        value = self.pick_value(stack)
        if text.startswith(value):
            return Node(self, value), text[len(value):]
        else:
            return None, text

    def pick_value(self, stack):
        return stack[-1]


class Pop(Retrieve):
    def pick_value(self, stack):
        return stack.pop()


##############################################################################
#
# Forward class (for recursive symbols)
#
##############################################################################


class Forward(Parser):
    def __init__(self):
        Parser.__init__(self)
        self.parser = None
        self.cycle_reached = False

    def __call__(self, text):
        return self.parser(text)

    def __str__(self):
        if self.cycle_reached:
            if self.parser and self.parser.component:
                return str(self.parser.component)
            return "..."
        else:
            self.cycle_reached = True
            s = str(self.parser)
            self.cycle_reached = False
            return s

    def set(self, parser):
        assert isinstance(parser, Parser)
912
        self.component = parser.component  # redundant, because of constructor of ParserHeadquarter
Eckhart Arnold's avatar
Eckhart Arnold committed
913
914
915
916
917
918
919
920
921
        self.parser = parser

    def apply(self, func):
        if super(Forward, self).apply(func):
            assert not self.visited
            self.parser.apply(func)


PARSER_SYMBOLS = {'RegExp', 'mixin_comment', 'RE', 'Token', 'Required',
922
923
                  'Lookahead', 'NegativeLookahead', 'Optional',
                  'Lookbehind', 'NegativeLookbehind',
Eckhart Arnold's avatar
Eckhart Arnold committed
924
                  'ZeroOrMore', 'Sequence', 'Alternative', 'Forward',
925
926
                  'OneOrMore', 'ParserHeadquarter', 'Capture', 'Retrieve',
                  'Pop'}
Eckhart Arnold's avatar
Eckhart Arnold committed
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


##############################################################################
#
# Abstract syntax tree support
#
##############################################################################


def expand_table(compact_table):
    """Expands a table by separating keywords that are tuples or strings
    containing comma separated words into single keyword entries with
    the same values. Returns the expanded table.
    Example:
    expand_table({"a, b": 1, "b": 1, ('d','e','f'):5, "c":3}) yields
    {'a': 1, 'b': 1, 'c': 3, 'd': 5, 'e': 5, 'f': 5}
    """
    expanded_table = {}
    keys = list(compact_table.keys())
    for key in keys:
        value = compact_table[key]
        if isinstance(key, str):
            parts = (s.strip() for s in key.split(','))
        else:
            assert isinstance(key, collections.abc.Iterable)
            parts = key
        for p in parts:
            expanded_table[p] = value
    return expanded_table


def ASTTransform(node, transtable):
    """Transforms the parse tree starting with the given `node` into an
    abstract syntax tree by calling transformation functions registered in a
    transformation table.

    Args:
        node (Node): The root note of the parse tree (or sub-tree) to be
                transformed into the abstract syntax tree.
        trans_table (dict): A dictionary that assigns a transformation
                transformation functions to parser component strings.
    """
    # normalize transformation entries by turning single transformations
    # into lists with a single item
    table = {component: transformation
    if isinstance(transformation, collections.abc.Sequence)
    else [transformation]
             for component, transformation in list(transtable.items())}
    table = expand_table(table)

    def recursive_ASTTransform(node):
        if node.children:
            for child in node.result:
                recursive_ASTTransform(child)
        transformation = table.get(node.parser.component,
                                   table.get('*', [lambda node: None]))
        for transform in transformation:
Eckhart Arnold's avatar
Eckhart Arnold committed
984
            transform(node)
Eckhart Arnold's avatar
Eckhart Arnold committed
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000

    recursive_ASTTransform(node)


# ------------------------------------------------
#
# rearranging transformations:
#     - tree may be rearranged (flattened)
#     - order is preserved
#     - all leaves are kept
#
# ------------------------------------------------


def replace_by_single_child(node):
    """Remove single branch node, replacing it by its immediate descendant.