syntaxtree.py 39.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# syntaxtree.py - syntax tree classes for DHParser
#
# Copyright 2016  by Eckhart Arnold (arnold@badw.de)
#                 Bavarian Academy of Sciences an Humanities (badw.de)
#
# 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.
17 18 19


"""
20 21
Module ``syntaxtree`` defines the ``Node``-class for syntax trees as well
as an abstract base class for parser-objects. The latter is defined
eckhart's avatar
eckhart committed
22
here, because node-objects refer to parser-objects. All concrete
23 24 25
parser classes are defined in the ``parse`` module.
"""

26
from collections import OrderedDict
27
import copy
28

eckhart's avatar
eckhart committed
29
from DHParser.error import Error, ErrorCode, linebreaks, line_col
30
from DHParser.stringview import StringView
di68kap's avatar
di68kap committed
31 32
from DHParser.toolkit import re
from typing import Callable, cast, Iterator, List, AbstractSet, Set, Union, Tuple, Optional
33

34

di68kap's avatar
di68kap committed
35
__all__ = ('WHITESPACE_PTYPE',
36
           'TOKEN_PTYPE',
37 38
           'ZOMBIE_TAG',
           'PLACEHOLDER',
eckhart's avatar
eckhart committed
39 40 41
           'ResultType',
           'StrictResultType',
           'ChildrenType',
42
           'Node',
43
           'FrozenNode',
44
           'RootNode',
45
           'parse_sxpr',
46 47 48
           'parse_xml',
           'flatten_sxpr',
           'flatten_xml')
Eckhart Arnold's avatar
Eckhart Arnold committed
49 50


51 52 53 54 55 56 57 58
#######################################################################
#
# parser base and mock parsers
#
#######################################################################


WHITESPACE_PTYPE = ':Whitespace'
59
TOKEN_PTYPE = ':Token'
60

61
ZOMBIE_TAG = "__ZOMBIE__"
62

63 64 65 66 67 68 69
#######################################################################
#
# syntaxtree nodes
#
#######################################################################


70
ChildrenType = Tuple['Node', ...]
Eckhart Arnold's avatar
Eckhart Arnold committed
71
NoChildren = cast(ChildrenType, ())  # type: ChildrenType
eckhart's avatar
eckhart committed
72
StrictResultType = Union[ChildrenType, StringView, str]
73
ResultType = Union[ChildrenType, 'Node', StringView, str, None]
74 75


76
def flatten_sxpr(sxpr: str) -> str:
77 78
    """
    Returns S-expression ``sxpr`` as a one-liner without unnecessary
Eckhart Arnold's avatar
Eckhart Arnold committed
79 80 81
    whitespace.

    Example:
82
    >>> flatten_sxpr('(a\\n    (b\\n        c\\n    )\\n)\\n')
Eckhart Arnold's avatar
Eckhart Arnold committed
83 84
    '(a (b c))'
    """
85

86
    return re.sub(r'\s(?=\))', '', re.sub(r'\s+', ' ', sxpr)).strip()
Eckhart Arnold's avatar
Eckhart Arnold committed
87 88


89
def flatten_xml(xml: str) -> str:
90 91
    """
    Returns an XML-tree as a one liner without unnecessary whitespace,
92
    i.e. only whitespace within leaf-nodes is preserved.
93 94
    A more precise alternative to `flatten_xml` is to use Node.as_xml()
    ans passing a set containing the top level tag to parameter `inline_tags`.
95
    """
96

97 98 99 100
    # works only with regex
    # return re.sub(r'\s+(?=<\w)', '', re.sub(r'(?<=</\w+>)\s+', '', xml))
    def tag_only(m):
        return m.groupdict()['closing_tag']
101
    return re.sub(r'\s+(?=<[\w:])', '', re.sub(r'(?P<closing_tag></:?\w+>)\s+', tag_only, xml))
102 103


eckhart's avatar
eckhart committed
104
RX_AMP = re.compile(r'&(?!\w+;)')
105 106


Eckhart Arnold's avatar
Eckhart Arnold committed
107
class Node:  # (collections.abc.Sized): Base class omitted for cython-compatibility
108 109 110
    """
    Represents a node in the concrete or abstract syntax tree.

111 112
    TODO: Add some documentation and doc-tests here...

113
    Attributes:
114 115
        tag_name (str):  The name of the node, which is either its
            parser's name or, if that is empty, the parser's class name
116

117 118 119
        result (str or tuple):  The result of the parser which
            generated this node, which can be either a string or a
            tuple of child nodes.
120

121 122
        children (tuple):  The tuple of child nodes or an empty tuple
            if there are no child nodes. READ ONLY!
123

eckhart's avatar
eckhart committed
124 125 126 127
        content (str):  Yields the contents of the tree as string. The
            difference to ``str(node)`` is that ``node.content`` does
            not add the error messages to the returned string.

Eckhart Arnold's avatar
Eckhart Arnold committed
128
        parser (Parser):  The parser which generated this node.
129 130
            WARNING: In case you use mock syntax trees for testing or
            parser replacement during the AST-transformation: DO NOT
Eckhart Arnold's avatar
Eckhart Arnold committed
131 132
            rely on this being a real parser object in any phase after
            parsing (i.e. AST-transformation and compiling), for
133
            example by calling ``isinstance(node.parer, ...)``.
134

135 136 137
        len (int):  The full length of the node's string result if the
            node is a leaf node or, otherwise, the concatenated string
            result's of its descendants. The figure always represents
138
            the length before AST-transformation and will never change
139
            through AST-transformation. READ ONLY!
140

141 142
        pos (int):  the position of the node within the parsed text.

Eckhart Arnold's avatar
Eckhart Arnold committed
143
            The value of ``pos`` is -1 meaning invalid by default.
144
            Setting this value will set the positions of all child
Eckhart Arnold's avatar
Eckhart Arnold committed
145
            nodes relative to this value.
146 147

            To set the pos values of all nodes in a syntax tree, the
Eckhart Arnold's avatar
Eckhart Arnold committed
148
            pos value of the root node should be set to 0 right
149 150
            after parsing.

Eckhart Arnold's avatar
Eckhart Arnold committed
151
            Other than that, this value should be considered READ ONLY.
152 153
            At any rate, it should only be reassigned during the parsing
            stage and never during or after the AST-transformation.
154

155 156
        errors (list):  A list of all errors that occured on this node.

157 158
        attr (dict): An optional dictionary of XML-attr. This
            dictionary is created lazily upon first usage. The attr
159 160
            will only be shown in the XML-Representation, not in the
            S-Expression-output.
161
    """
162

163
    __slots__ = '_result', 'children', '_len', '_pos', 'tag_name', 'errors', '_xml_attr', '_content'
164

165
    def __init__(self, tag_name: str, result: ResultType, leafhint: bool = False) -> None:
166 167
        """
        Initializes the ``Node``-object with the ``Parser``-Instance
168 169
        that generated the node and the parser's result.
        """
Eckhart Arnold's avatar
Eckhart Arnold committed
170
        self.errors = []                # type: List[Error]
171
        self._pos = -1                  # type: int
172
        # Assignment to self.result initializes the attr _result, children and _len
di68kap's avatar
di68kap committed
173
        # The following if-clause is merely an optimization, i.e. a fast-path for leaf-Nodes
174
        if leafhint:
eckhart's avatar
eckhart committed
175
            self._result = result       # type: StrictResultType  # cast(StrictResultType, result)
eckhart's avatar
eckhart committed
176
            self._content = None        # type: Optional[str]
177
            self.children = NoChildren  # type: ChildrenType
178
            self._len = -1              # type: int  # lazy evaluation
179 180
        else:
            self.result = result
181 182
        # assert tag_name is not None
        self.tag_name = tag_name        # type: str
183

184 185
    def __deepcopy__(self, memo):
        if self.children:
186
            duplicate = self.__class__(self.tag_name, copy.deepcopy(self.children), False)
187
        else:
188
            duplicate = self.__class__(self.tag_name, self.result, True)
189 190 191
        duplicate.errors = copy.deepcopy(self.errors) if self.errors else []
        duplicate._pos = self._pos
        duplicate._len = self._len
eckhart's avatar
eckhart committed
192
        if self.attr_active():
di68kap's avatar
di68kap committed
193 194
            duplicate.attr.update(copy.deepcopy(self._xml_attr))
            # duplicate._xml_attr = copy.deepcopy(self._xml_attr)  # this is not cython compatible
195
        return duplicate
196

197
    def __str__(self):
198
        s = "".join(str(child) for child in self.children) if self.children else self.content
eckhart's avatar
eckhart committed
199
        if self.errors:
200
            return ' <<< Error on "%s" | %s >>> ' % \
eckhart's avatar
eckhart committed
201
                   (s, '; '.join(e.message for e in self.errors))
202
        return s
203

204

205
    def __repr__(self):
206
        # mpargs = {'name': self.parser.name, 'ptype': self.parser.ptype}
207 208
        # name, ptype = (self._tag_name.split(':') + [''])[:2]
        # parg = "MockParser({name}, {ptype})".format(name=name, ptype=ptype)
209
        rarg = str(self) if not self.children else \
eckhart's avatar
eckhart committed
210
            "(" + ", ".join(repr(child) for child in self.children) + ")"
211
        return "Node(%s, %s)" % (self.tag_name, rarg)
212

213

214
    def __len__(self):
215
        if self._len < 0:
216
            self._len = sum(len(child) for child in self.children) \
217
                if self.children else len(self._result)
218 219 220 221 222 223 224 225
        return self._len


    def __bool__(self):
        # A node that is not None is always True, even if it's empty
        return True


226
    def __eq__(self, other):
227 228 229
        """
        Equality of nodes: Two nodes are considered as equal, if their tag
        name is the same and if their results are equal.
230 231 232 233

        Note: It is not required that two nodes have the same errors attached.
        In case you need to check for error equality as well, compare a
        serialization that includes error messages, as_sxpr() will do!
234
        """
235
        return self.tag_name == other.tag_name and self.result == other.result
236

237

238
    def __hash__(self):
239
        return hash(self.tag_name)
240

241

242 243 244
    def __getitem__(self, index_or_tagname: Union[int, str]) -> Union['Node', Iterator['Node']]:
        """
        Returns the child node with the given index if ``index_or_tagname`` is
245
        an integer or the first child node with the given tag name. Examples::
246

247
            >>> tree = parse_sxpr('(a (b "X") (X (c "d")) (e (X "F")))')
248 249
            >>> flatten_sxpr(tree[0].as_sxpr())
            '(b "X")'
250 251
            >>> flatten_sxpr(tree["X"].as_sxpr())
            '(X (c "d"))'
252 253 254 255

        Args:
            index_or_tagname(str): Either an index of a child node or a
                tag name.
256
        Returns:
257 258
            Node: All nodes which have a given tag name.
        """
259 260 261
        if self.children:
            if isinstance(index_or_tagname, int):
                return self.children[index_or_tagname]
262
            else:
263 264 265 266 267
                for child in self.children:
                    if child.tag_name == index_or_tagname:
                        return child
                raise KeyError(index_or_tagname)
        raise ValueError('Leave nodes have no children that can be indexed!')
268 269 270 271


    def __contains__(self, tag_name: str) -> bool:
        """
272
        Returns true if a child with the given tag name exists.
273
        Args:
274 275
            tag_name (str): tag_name which will be searched among to immediate
                descendants of this node.
276 277 278 279
        Returns:
            bool:  True, if at least one descendant node with the given tag
                name exists, False otherwise
        """
280 281 282 283 284
        # assert isinstance(tag_name, str)
        if self.children:
            for child in self.children:
                if child.tag_name == tag_name:
                    return True
285
            return False
286
        raise ValueError('Leave node cannot contain other nodes')
287 288


289 290 291 292 293 294 295 296 297 298 299 300 301 302
    def get(self, index_or_tagname: Union[int, str],
            surrogate: Union['Node', Iterator['Node']]) -> Union['Node', Iterator['Node']]:
        """Returns the child node with the given index if ``index_or_tagname``
        is an integer or the first child node with the given tag name. If no
        child with the given index or tag_name exists, the ``surrogate`` is
        returned instead. This mimics the behaviour of Python's dictionary's
        get-method.
        """
        try:
            return self[index_or_tagname]
        except KeyError:
            return surrogate


303
    def is_anonymous(self):
304
        return self.tag_name[0] == ':'
305

306

307
    @property
Eckhart Arnold's avatar
Eckhart Arnold committed
308
    def result(self) -> StrictResultType:
309 310 311 312 313
        """
        Returns the result from the parser that created the node.
        Error messages are not included in the result. Use `self.content()`
        if the result plus any error messages is needed.
        """
314 315
        return self._result

316

317
    @result.setter
Eckhart Arnold's avatar
Eckhart Arnold committed
318
    def result(self, result: ResultType):
319
        # # made obsolete by static type checking with mypy
320 321 322
        # assert ((isinstance(result, tuple) and all(isinstance(child, Node) for child in result))
        #         or isinstance(result, Node)
        #         or isinstance(result, str)), str(result)
Eckhart Arnold's avatar
Eckhart Arnold committed
323 324
        # Possible optimization: Do not allow single nodes as argument:
        # assert not isinstance(result, Node)
325 326
        self._len = -1        # lazy evaluation
        self._content = None
327 328 329 330 331 332 333 334 335
        if isinstance(result, Node):
            self.children = (result,)
            self._result = self.children
        else:
            if isinstance(result, tuple):
                self.children = result
                self._result = result or ''
            else:
                self.children = NoChildren
eckhart's avatar
eckhart committed
336
                self._result = result  # cast(StrictResultType, result)
337

338 339

    @property
eckhart's avatar
eckhart committed
340
    def content(self) -> str:
341
        """
di68kap's avatar
di68kap committed
342 343 344
        Returns content as string, omitting error messages. If the node has
        child-nodes, the string content of the child-nodes is recursively read
        and then concatenated.
345
        """
346 347 348 349
        if self._content is None:
            if self.children:
                self._content = "".join(child.content for child in self.children)
            else:
350
                # self._content = self._result
351 352 353
                self._content = str(self._result)
                self._result = self._content  # self._result might be more efficient as a string!?
        return self._content
354 355 356 357 358
    #
    #
    # @content.setter
    # def content(self, content: str):
    #     self.result = content
di68kap's avatar
di68kap committed
359 360


361 362 363 364 365 366 367 368 369
    @property
    def structure(self) -> str:
        """
        Return structure (and content) as S-expression on a single line
        without any line breaks.
        """
        return flatten_sxpr(self.as_sxpr(showerrors=False))


370
    @property
371
    def pos(self) -> int:
eckhart's avatar
eckhart committed
372 373
        """Returns the position of the Node's content in the source text."""
        if self._pos < 0:
374
            raise AssertionError("Position value not initialized!")
375 376
        return self._pos

377

eckhart's avatar
eckhart committed
378
    def init_pos(self, pos: int) -> 'Node':
eckhart's avatar
eckhart committed
379 380 381 382 383 384 385 386 387
        """
        (Re-)initialize position value. Usually, the parser guard
        (`parsers.add_parser_guard()`) takes care of assigning the
        position in the document to newly created nodes. However,
        where Nodes are created outside the reach of the parser
        guard, their document-position must be assigned manually.
        This function recursively reassigns the position values
        of the child nodes, too.
        """
eckhart's avatar
eckhart committed
388 389
        assert self._pos < 0 or self.pos == pos, str("pos mismatch %i != %i" % (self._pos, pos))
        self._pos = pos
390
        # recursively adjust pos-values of all children
391
        offset = self.pos
392
        for child in self.children:
eckhart's avatar
eckhart committed
393
            child.init_pos(offset)
394 395 396
            offset = child.pos + len(child)
        return self

397

eckhart's avatar
eckhart committed
398 399 400 401 402 403 404 405 406 407 408 409 410
    def attr_active(self) -> bool:
        """
        Returns True, if XML-Attributes of this node have ever been set
        or queried, even if unsuccessfully.
        """
        try:
            if self._xml_attr is not None:
                return True
        except AttributeError:
            pass
        return False


411
    @property
412
    def attr(self):
413
        """
414
        Returns a dictionary of XML-attr attached to the node.
415
        """
eckhart's avatar
eckhart committed
416 417 418 419
        try:
            if self._xml_attr is None:          # cython compatibility
                self._xml_attr = OrderedDict()
        except AttributeError:
420 421 422
            self._xml_attr = OrderedDict()
        return self._xml_attr

423

424
    def _tree_repr(self, tab, open_fn, close_fn, data_fn=lambda i: i,
425
                   density=0, inline=False, inline_fn=lambda node: False) -> str:
426 427 428 429 430 431 432 433
        """
        Generates a tree representation of this node and its children
        in string from.

        The kind ot tree-representation that is determined by several
        function parameters. This could be an XML-representation or a
        lisp-like S-expression.

434
        Args:
435
            tab (str):  The indentation string, e.g. '\t' or '    '
eckhart's avatar
eckhart committed
436
            open_fn:   (Node->str) A function that returns an opening
437
                string (e.g. an XML-tag_name) for a given node
eckhart's avatar
eckhart committed
438
            close_fn:  (Node->str) A function that returns a closeF
439
                string (e.g. an XML-tag_name) for a given node.
eckhart's avatar
eckhart committed
440
            data_fn:   (str->str) A function that filters the data string
441 442 443 444 445 446
                before printing, e.g. to add quotation marks

        Returns (str):
            A string that contains a (serialized) tree representation
            of the node and its children.
        """
eckhart's avatar
eckhart committed
447 448
        head = open_fn(self)
        tail = close_fn(self)
449 450

        if not self.result:
451
            return head.rstrip() + tail.lstrip()
452

eckhart's avatar
eckhart committed
453
        tail = tail.lstrip(None if density & 2 else '')
454

455
        inline = inline or inline_fn(self)
456 457 458 459 460
        if inline:
            head = head.rstrip()
            tail = tail.lstrip()
            usetab, sep = '', ''
        else:
eckhart's avatar
eckhart committed
461 462
            usetab = tab if head else ''    # no indentation if tag is already omitted
            sep = '\n'
463

464 465
        if self.children:
            content = []
466
            for child in self.children:
467
                subtree = child._tree_repr(tab, open_fn, close_fn, data_fn,
468
                                           density, inline, inline_fn)
469
                if subtree:
eckhart's avatar
eckhart committed
470 471
                    st = [subtree] if inline else subtree.split('\n')
                    content.append((sep + usetab).join(s for s in st))
472
            return head + usetab + (sep + usetab).join(content) + tail
473

eckhart's avatar
eckhart committed
474
        res = self.content
475
        if not inline and not head:
eckhart's avatar
eckhart committed
476
            # strip whitespace for omitted non inline node, e.g. CharData in mixed elements
477
            res = res.strip()
478 479
        if density & 1 and res.find('\n') < 0:  # and head[0] == "<":
            # except for XML, add a gap between opening statement and content
480
            gap = ' ' if not inline and head and head.rstrip()[-1:] != '>' else ''
481
            return head.rstrip() + gap + data_fn(res) + tail.lstrip()
482
        else:
483
            return head + '\n'.join([usetab + data_fn(s) for s in res.split('\n')]) + tail
484

485

486 487 488
    def as_sxpr(self, src: str = None,
                showerrors: bool = True,
                indentation: int = 2,
489
                compact: bool = False) -> str:
490 491 492
        """
        Returns content as S-expression, i.e. in lisp-like form.

493
        Args:
494 495 496
            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.
497 498 499
            showerrors: If True, error messages will be shown.
            indentation: The number of whitespaces for indentation
            compact:  If True, a compact representation is returned where
500
                brackets are omitted and only the indentation indicates the
Eckhart Arnold's avatar
Eckhart Arnold committed
501
                tree structure.
502 503
        """

eckhart's avatar
eckhart committed
504
        left_bracket, right_bracket, density = ('', '', 1) if compact else ('(', '\n)', 0)
eckhart's avatar
eckhart committed
505
        lbreaks = linebreaks(src) if src else []  # type: List[int]
506

507
        def opening(node) -> str:
eckhart's avatar
eckhart committed
508
            """Returns the opening string for the representation of `node`."""
eckhart's avatar
eckhart committed
509
            txt = [left_bracket, node.tag_name]
510
            # s += " '(pos %i)" % node.add_pos
eckhart's avatar
eckhart committed
511
            if node.attr_active():
512
                txt.extend(' `(%s "%s")' % (k, v) for k, v in node.attr.items())
513
            if src:
514 515
                line, col = line_col(lbreaks, node.pos)
                txt.append(" `(pos %i %i %i)" % (node.pos, line, col))
516
            if showerrors and node.errors:
517
                txt.append(" `(err `%s)" % ' '.join(str(err) for err in node.errors))
518
            return "".join(txt) + '\n'
519

eckhart's avatar
eckhart committed
520 521 522
        def closing(node) -> str:
            """Returns the closing string for the representation of `node`."""
            return right_bracket
523

eckhart's avatar
eckhart committed
524 525 526 527 528
        def pretty(strg):
            """Encloses `strg` with the right kind of quotation marks."""
            return '"%s"' % strg if strg.find('"') < 0 \
                else "'%s'" % strg if strg.find("'") < 0 \
                else '"%s"' % strg.replace('"', r'\"')
529

530
        return self._tree_repr(' ' * indentation, opening, closing, pretty, density=density)
531

eckhart's avatar
eckhart committed
532

533 534 535
    def as_xml(self, src: str = None,
               showerrors: bool = True,
               indentation: int = 2,
eckhart's avatar
eckhart committed
536 537 538
               inline_tags: Set[str] = set(),
               omit_tags: Set[str] = set(),
               empty_tags: Set[str] = set()) -> str:
539 540 541
        """
        Returns content as XML-tree.

542
        Args:
543 544 545
            src:  The source text or `None`. In case the source text is
                given the position will also be reported as line and
                column.
546 547
            showerrors: If True, error messages will be shown.
            indentation: The number of whitespaces for indentation
548 549 550
            inline_tags:  A set of tag names, the content of which will always be written
                on a single line, unless it contains explicit line feeds ('\n').
            omit_tags:  A set of tags from which only the content will be printed, but
551
                neither the opening tag nor its attr nor the closing tag. This
552 553 554
                allows producing a mix of plain text and child tags in the output,
                which otherwise is not supported by the Node object, because it
                requires its content to be either a tuple of children or string content.
555 556
            empty_tags:  A set of tags which shall be rendered as empty elements, e.g.
                "<empty/>" instead of "<empty><empty>".
557 558
        """

559
        def opening(node) -> str:
560 561 562
            """Returns the opening string for the representation of `node`."""
            if node.tag_name in omit_tags:
                return ''
eckhart's avatar
eckhart committed
563
            txt = ['<', node.tag_name]
eckhart's avatar
eckhart committed
564
            has_reserved_attrs = node.attr_active() \
eckhart's avatar
eckhart committed
565
                and any(r in node.attr for r in {'err', 'line', 'col'})
eckhart's avatar
eckhart committed
566
            if node.attr_active():
567
                txt.extend(' %s="%s"' % (k, v) for k, v in node.attr.items())
568
            if src and not has_reserved_attrs:
eckhart's avatar
eckhart committed
569
                txt.append(' line="%i" col="%i"' % line_col(line_breaks, node.pos))
570
            if showerrors and node.errors and not has_reserved_attrs:
eckhart's avatar
eckhart committed
571 572
                txt.append(' err="%s"' % ''.join(str(err).replace('"', r'\"')
                                                 for err in node.errors))
573 574 575
            if node.tag_name in empty_tags:
                assert not node.result, ("Node %s with content %s is not an empty element!" %
                                         (node.tag_name, str(node)))
eckhart's avatar
eckhart committed
576
                ending = "/>\n" if not node.tag_name[0] == '?' else "?>\n"
577 578 579
            else:
                ending = ">\n"
            return "".join(txt + [ending])
580 581

        def closing(node):
582
            """Returns the closing string for the representation of `node`."""
583
            if node.tag_name in omit_tags or node.tag_name in empty_tags:
584
                return ''
585
            return ('\n</') + node.tag_name + '>'
586

587 588 589 590 591 592 593
        def sanitizer(content: str) -> str:
            """Substitute "&", "<", ">" in XML-content by the respective entities."""
            content = RX_AMP.sub('&amp;', content)
            content = content.replace('<', '&lt;').replace('>', '&gt;')
            return content


594 595 596 597 598
        def inlining(node):
            """Returns True, if `node`'s tag name is contained in `inline_tags`,
            thereby signalling that the children of this node shall not be
            printed on several lines to avoid unwanted gaps in the output.
            """
eckhart's avatar
eckhart committed
599
            return node.tag_name in inline_tags \
eckhart's avatar
eckhart committed
600
                or (node.attr_active()
eckhart's avatar
eckhart committed
601
                    and node.attr.get('xml:space', 'default') == 'preserve')
602

603
        line_breaks = linebreaks(src) if src else []
604
        return self._tree_repr(' ' * indentation, opening, closing, sanitizer,
605
                               density=1, inline_fn=inlining)
606

607

eckhart's avatar
eckhart committed
608
    def select(self, match_function: Callable, include_root: bool = False, reverse: bool = False) \
609
            -> Iterator['Node']:
eckhart's avatar
eckhart committed
610
        """
611
        Finds nodes in the tree that fulfill a given criterion.
eckhart's avatar
eckhart committed
612

613
        `select` is a generator that yields all nodes for which the
di68kap's avatar
di68kap committed
614
        given `match_function` evaluates to True. The tree is
615 616 617
        traversed pre-order.

        See function `Node.select_by_tag` for some examples.
eckhart's avatar
eckhart committed
618

619 620 621
        Args:
            match_function (function): A function  that takes as Node
                object as argument and returns True or False
622 623
            include_root (bool): If False, only descendant nodes will be
                checked for a match.
624 625
            reverse (bool): If True, the tree will be walked in reverse
                order, i.e. last children first.
626
        Yields:
627
            Node: All nodes of the tree for which
628 629
            ``match_function(node)`` returns True
        """
630
        if include_root and match_function(self):
631
            yield self
632 633 634
        child_iterator = reversed(self.children) if reverse else self.children
        for child in child_iterator:
            for node in child.select(match_function, True, reverse):
635
                yield node
636

637

eckhart's avatar
eckhart committed
638
    def select_by_tag(self, tag_names: Union[str, AbstractSet[str]],
eckhart's avatar
eckhart committed
639
                      include_root: bool = False) -> Iterator['Node']:
640
        """
641 642 643 644
        Returns an iterator that runs through all descendants that have one
        of the given tag names.

        Examples::
645

646
            >>> tree = parse_sxpr('(a (b "X") (X (c "d")) (e (X "F")))')
647
            >>> list(flatten_sxpr(item.as_sxpr()) for item in tree.select_by_tag("X", False))
648
            ['(X (c "d"))', '(X "F")']
649
            >>> list(flatten_sxpr(item.as_sxpr()) for item in tree.select_by_tag({"X", "b"}, False))
650
            ['(b "X")', '(X (c "d"))', '(X "F")']
651
            >>> any(tree.select_by_tag('a', False))
652
            False
653
            >>> list(flatten_sxpr(item.as_sxpr()) for item in tree.select_by_tag('a', True))
654
            ['(a (b "X") (X (c "d")) (e (X "F")))']
655 656
            >>> flatten_sxpr(next(tree.select_by_tag("X", False)).as_sxpr())
            '(X (c "d"))'
657 658

        Args:
659 660 661 662
            tag_name(set): A tag name or set of tag names that is being
                searched for
            include_root (bool): If False, only descendant nodes will be
                checked for a match.
663 664 665
        Yields:
            Node: All nodes which have a given tag name.
        """
666
        if isinstance(tag_names, str):
eckhart's avatar
eckhart committed
667
            tag_names = frozenset({tag_names})
668
        return self.select(lambda node: node.tag_name in tag_names, include_root)
669 670


671 672 673 674
    def pick(self, tag_names: Union[str, Set[str]]) -> Optional['Node']:
        """
        Picks the first descendant with one of the given tag_names.

675
        This function is mostly just syntactic sugar for
676 677 678 679 680 681 682 683 684 685
        ``next(node.select_by_tag(tag_names, False))``. However, rather than
        raising a StopIterationError if no descendant with the given tag-name
        exists, it returns None.
        """
        try:
            return next(self.select_by_tag(tag_names, False))
        except StopIteration:
            return None


686
    def tree_size(self) -> int:
eckhart's avatar
eckhart committed
687 688 689
        """
        Recursively counts the number of nodes in the tree including the root node.
        """
690 691 692
        return sum(child.tree_size() for child in self.children) + 1


693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
class FrozenNode(Node):

    def __init__(self, tag_name: str, result: ResultType) -> None:
        if isinstance(result, str) or isinstance(result, StringView):
            result = str(result)
        else:
            raise TypeError('FrozenNode only accepts string as results. '
                            '(Only leaf-nodes can be frozen nodes.)')
        super(FrozenNode, self).__init__(tag_name, result, True)

    @property
    def result(self) -> StrictResultType:
        return self._result

    @result.setter
    def result(self, result: ResultType):
        raise TypeError('FrozenNode does not allow re-assignment of results.')

    def init_pos(self, pos: int) -> 'Node':
        pass


PLACEHOLDER = Node('__PLACEHOLDER__', '')
di68kap's avatar
di68kap committed
716 717


718
class RootNode(Node):
719
    """TODO: Add Documentation!!!
720

721
        all_errors (list):  A list of all errors that have occured so far during
722 723
                processing (i.e. parsing, AST-transformation, compiling)
                of this tree.
724

725 726
        error_flag (int):  the highest warning or error level of all errors
                that occurred.
727
    """
728

eckhart's avatar
eckhart committed
729
    def __init__(self, node: Optional[Node] = None):
730
        super().__init__(ZOMBIE_TAG, '')
eckhart's avatar
eckhart committed
731
        self.all_errors = []  # type: List[Error]
732
        self.error_flag = 0
eckhart's avatar
eckhart committed
733 734
        if node is not None:
            self.swallow(node)
735
        # customization for XML-Representation
eckhart's avatar
eckhart committed
736 737 738
        self.inline_tags = set()  # type: Set[str]
        self.omit_tags = set()  # type: Set[str]
        self.empty_tags = set()  # type: Set[str]
739

740 741 742 743 744 745 746 747 748 749 750
    def __deepcopy__(self, memodict={}):
        duplicate = self.__class__(None)
        if self.children:
            duplicate.children = copy.deepcopy(self.children)
            duplicate._result = duplicate.children
        else:
            duplicate.children = NoChildren
            duplicate._result = self._result
        duplicate.errors = copy.deepcopy(self.errors) if self.errors else []
        duplicate._pos = self._pos
        duplicate._len = self._len
eckhart's avatar
eckhart committed
751
        if self.attr_active():
di68kap's avatar
di68kap committed
752
            duplicate.attr.update(copy.deepcopy(self._xml_attr))
753
            # duplicate._xml_attr = copy.deepcopy(self._xml_attr)  # this is blocked by cython
754 755 756 757 758
        duplicate.all_errors = copy.deepcopy(self.all_errors)
        duplicate.error_flag = self.error_flag
        duplicate.inline_tags = self.inline_tags
        duplicate.omit_tags = self.omit_tags
        duplicate.empty_tags = self.empty_tags
759
        duplicate.tag_name = self.tag_name
760 761 762
        return duplicate


763
    def swallow(self, node: Node) -> 'RootNode':
764 765
        """
        Put `self` in the place of `node` by copying all its data.
766 767 768 769 770 771 772 773 774
        Returns self.

        This is done by the parse.Grammar object after
        parsing has finished, so that the Grammar object always
        returns a syntax tree rooted in a RootNode object.

        It is possible to add errors to a RootNode object, before it
        has actually swallowed the root of the syntax tree.
        """
775 776 777 778
        self._result = node._result
        self.children = node.children
        self._len = node._len
        self._pos = node._pos
779
        self.tag_name = node.tag_name
eckhart's avatar
eckhart committed
780
        if node.attr_active():
781
            self._xml_attr = node._xml_attr
782
        self._content = node._content
783
        return self
784

eckhart's avatar
eckhart committed
785
    def add_error(self, node: Node, error: Error) -> 'RootNode':
786 787 788
        """
        Adds an Error object to the tree, locating it at a specific node.
        """
di68kap's avatar
di68kap committed
789 790 791 792 793
        self.all_errors.append(error)
        self.error_flag = max(self.error_flag, error.code)
        node.errors.append(error)
        return self

eckhart's avatar
eckhart committed
794
    def new_error(self,
795
                  node: Node,
796
                  message: str,
eckhart's avatar
eckhart committed
797
                  code: ErrorCode = Error.ERROR) -> 'RootNode':
798
        """
eckhart's avatar
eckhart committed
799
        Adds an error to this tree, locating it at a specific node.
800 801 802 803 804
        Parameters:
            pos(int):     The position of the error in the source text
            message(str): A string with the error message.abs
            code(int):    An error code to identify the kind of error
        """
805
        error = Error(message, node.pos, code)
eckhart's avatar
eckhart committed
806 807
        self.add_error(node, error)
        return self
di68kap's avatar
di68kap committed
808

eckhart's avatar
eckhart committed
809
    def collect_errors(self) -> List[Error]:
810 811
        """
        Returns the list of errors, ordered bv their position.
812
        """
813
        self.all_errors.sort(key=lambda e: e.pos)
814
        return self.all_errors
815

816
    def customized_XML(self):
817 818
        """
        Returns a customized XML representation of the tree.
819
        See the docstring of `Node.as_xml()` for an explanation of the
820 821
        customizations.
        """
eckhart's avatar
eckhart committed
822
        return self.as_xml(inline_tags=self.inline_tags,
823 824 825
                           omit_tags=self.omit_tags,
                           empty_tags=self.empty_tags)

826

di68kap's avatar
di68kap committed
827 828 829 830 831
#######################################################################
#
# S-expression- and XML-parsers
#
#######################################################################
eckhart's avatar
eckhart committed
832 833


eckhart's avatar
eckhart committed
834
def parse_sxpr(sxpr: Union[str, StringView]) -> Node:
835
    """
836 837 838 839 840
    Generates a tree of nodes from an S-expression.

    This can - among other things - be used for deserialization of trees that
    have been serialized with `Node.as_sxpr()` or as a convenient way to
    generate test data.
841 842

    Example:
843
    >>> parse_sxpr("(a (b c))").as_sxpr()
844
    '(a\\n  (b\\n    "c"\\n  )\\n)'
845
    """
846

eckhart's avatar
eckhart committed
847
    sxpr = StringView(sxpr).strip() if isinstance(sxpr, str) else sxpr.strip()
848
    # mock_parsers = dict()  # type: Dict[StringView, MockParser]
849

850
    def next_block(s: StringView):
eckhart's avatar
eckhart committed
851 852
        """Generator that yields all characters until the next closing bracket
        that does not match an opening bracket matched earlier within the same
853 854
        package.
        """
855
        s = s.strip()
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
        try:
            while s[0] != ')':
                if s[0] != '(':
                    raise ValueError('"(" expected, not ' + s[:10])
                # assert s[0] == '(', s
                level = 1
                k = 1
                while level > 0:
                    if s[k] == '(':
                        level += 1
                    elif s[k] == ')':
                        level -= 1
                    k += 1
                yield s[:k]
                s = s[k:].strip()
        except IndexError:
            errmsg = ('Malformed S-expression. Unprocessed part: "%s"' % s) if s \
                else 'Malformed S-expression. Closing bracket(s) ")" missing.'
            raise AssertionError(errmsg)
875

876 877 878 879 880 881 882 883 884
    def inner_parser(sxpr: StringView) -> Node:
        if sxpr[0] != '(':
            raise ValueError('"(" expected, not ' + sxpr[:10])
        # assert sxpr[0] == '(', sxpr
        sxpr = sxpr[1:].strip()
        match = sxpr.match(re.compile(r'[\w:]+'))
        if match is None:
            raise AssertionError('Malformed S-expression Node-tagname or identifier expected, '
                                 'not "%s"' % sxpr[:40].replace('\n', ''))
885
        end = sxpr.index(match.end())
886 887 888
        tagname = sxpr[:end]
        name, class_name = (tagname.split(':') + [''])[:2]
        sxpr = sxpr[end:].strip()
eckhart's avatar
eckhart committed
889
        attributes = OrderedDict()  # type: OrderedDict[str, str]
890
        if sxpr[0] == '(':
eckhart's avatar
eckhart committed
891
            result = tuple(inner_parser(block) for block in next_block(sxpr))  # type: ResultType
892 893 894
        else:
            lines = []
            while sxpr and sxpr[0:1] != ')':
895
                # parse attr
896 897 898 899 900
                while sxpr[:2] == "`(":
                    i = sxpr.find('"')
                    k = sxpr.find(')')
                    # read very special attribute pos
                    if sxpr[2:5] == "pos" and 0 < i < k:
eckhart's avatar
eckhart committed
901 902
                        # pos = int(sxpr[5:k].strip().split(' ')[0])
                        pass
903 904 905
                    # ignore very special attribute err
                    elif sxpr[2:5] == "err" and 0 <= sxpr.find('`', 5) < k:
                        m = sxpr.find('(', 5)
eckhart's avatar
eckhart committed
906
                        while 0 <= m < k:
907 908
                            m = sxpr.find('(', k)
                            k = max(k, sxpr.find(')', max(m, 0)))
909
                    # read attr
910 911 912 913
                    else:
                        attr = sxpr[2:i].strip()
                        value = sxpr[i:k].strip()[1:-1]
                        attributes[attr] = value
eckhart's avatar
eckhart committed
914
                    sxpr = sxpr[k + 1:].strip()
915 916 917 918
                # parse content
                for qtmark in ['"""', "'''", '"', "'"]:
                    match = sxpr.match(re.compile(qtmark + r'.*?' + qtmark, re.DOTALL))
                    if match:
919
                        end = sxpr.index(match.end())
920 921 922 923
                        i = len(qtmark)
                        lines.append(str(sxpr[i:end - i]))
                        sxpr = sxpr[end:].strip()
                        break
924
                else:
925
                    match = sxpr.match(re.compile(r'(?:(?!\)).)*', re.DOTALL))
926
                    end = sxpr.index(match.end())
927 928 929
                    lines.append(str(sxpr[:end]))
                    sxpr = sxpr[end:]
            result = "\n".join(lines)
930
        node = Node(name or ':' + class_name, result)
931
        if attributes:
932
            node.attr.update(attributes)
933 934
        return node

eckhart's avatar
eckhart committed
935
    return inner_parser(StringView(sxpr) if isinstance(sxpr, str) else sxpr)
936 937


938 939 940
RX_WHITESPACE_TAIL = re.compile(r'\s*$')


eckhart's avatar
eckhart committed
941
def parse_xml(xml: Union[str, StringView]) -> Node:
942 943 944
    """
    Generates a tree of nodes from a (Pseudo-)XML-source.
    """
945

eckhart's avatar
eckhart committed
946
    xml = StringView(str(xml))
947 948
    # PlainText = MockParser('', TOKEN_PTYPE)
    # mock_parsers = {TOKEN_PTYPE: PlainText}
949 950 951

    def parse_attributes(s: StringView) -> Tuple[StringView, OrderedDict]:
        """Parses a sqeuence of XML-Attributes. Returns the string-slice
952 953
        beginning after the end of the attr.
        """
eckhart's avatar
eckhart committed
954
        attributes = OrderedDict()  # type: OrderedDict[str, str]
955 956 957 958
        restart = 0
        for match in s.finditer(re.compile(r'\s*(?P<attr>\w+)\s*=\s*"(?P<value>.*)"\s*')):
            d = match.groupdict()
            attributes[d['attr']] = d['value']
959
            restart = s.index(match.end())
960 961 962 963
        return (s[restart:], attributes)

    def parse_opening_tag(s: StringView) -> Tuple[StringView, str, OrderedDict, bool]:
        """Parses an opening tag. Returns the string segment following the
964
        the opening tag, the tag name, a dictionary of attr and
965
        a flag indicating whether the tag is actually a solitary tag as
966 967
        indicated by a slash at the end, i.e. <br/>.
        """
968 969 970
        match = s.match(re.compile(r'<\s*(?P<tagname>[\w:]+)\s*'))
        assert match
        tagname = match.groupdict()['tagname']
971
        section = s[s.index(match.end()):]
972
        s, attributes = parse_attributes(section)
973 974
        i = s.find('>')
        assert i >= 0
eckhart's avatar
eckhart committed
975
        return s[i + 1:], tagname, attributes, s[i - 1] == "/"
976 977

    def parse_closing_tag(s: StringView) -> Tuple[StringView, str]:
978
        """Parses a closing tag and returns the string segment, just after
979 980
        the closing tag.
        """
981 982 983
        match = s.match(re.compile(r'</\s*(?P<tagname>[\w:]+)>'))
        assert match
        tagname = match.groupdict()['tagname']
984
        return s[s.index(match.end()):], tagname
985

eckhart's avatar
eckhart committed
986
    def parse_leaf_content(s: StringView) -> Tuple[StringView, StringView]:
987
        """Parses a piece of the content of a tag, just until the next opening,
988 989
        closing or solitary tag is reached.
        """
990
        i = 0
eckhart's avatar
eckhart committed
991
        while s[i] != "<" or s[max(0, i - 1)] == "\\":
992 993 994 995 996 997 998
            i = s.find("<", i)
        return s[i:], s[:i]

    def parse_full_content(s: StringView) -> Tuple[StringView, Node]:
        """Parses the full content of a tag, starting right at the beginning
        of the opening tag and ending right after the closing tag.
        """
eckhart's avatar
eckhart committed
999 1000
        res = []  # type: List[Node]
        s, tagname, _, solitary = parse_opening_tag(s)
1001 1002 1003 1004
        name, class_name = (tagname.split(":") + [''])[:2]
        if not solitary:
            while s and not s[:2] == "</":
                s, leaf = parse_leaf_content(s)
1005
                if leaf and (leaf.find('\n') < 0 or not leaf.match(RX_WHITESPACE_TAIL)):
1006
                    res.append(Node(TOKEN_PTYPE, leaf))
1007 1008
                if s[:1] == "<" and s[:2] != "</":
                    s, child = parse_full_content(s)
eckhart's avatar
eckhart committed
1009
                    res.append(child)
1010 1011
            s, closing_tagname = parse_closing_tag(s)
            assert tagname == closing_tagname
1012
        if len(res) == 1 and res[0].tag_name == TOKEN_PTYPE:
eckhart's avatar
eckhart committed
1013
            result = res[0].result
1014
        else:
eckhart's avatar
eckhart committed
1015
            result = tuple(res)
1016
        return s, Node(name or ':' + class_name, result)
1017

1018
    match_header = xml.search(re.compile(r'<(?!\?)'))
1019
    start = xml.index(match_header.start()) if match_header else 0
1020 1021 1022
    _, tree = parse_full_content(xml[start:])
    assert _.match(RX_WHITESPACE_TAIL)
    return tree
1023

1024
# if __name__ == "__main__":
1025
#     st = parse_sxpr("(alpha (beta (gamma i\nj\nk) (delta y)) (epsilon z))")
1026 1027
#     print(st.as_sxpr())
#     print(st.as_xml())