File: parse_tree.py

package info (click to toggle)
blueprint-compiler 0.18.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,140 kB
  • sloc: python: 8,504; sh: 31; makefile: 6
file content (620 lines) | stat: -rw-r--r-- 20,001 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
# parse_tree.py
#
# Copyright 2021 James Westman <james@jwestman.net>
#
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This file is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: LGPL-3.0-or-later

"""Utilities for parsing an AST from a token stream."""

import typing as T
from enum import Enum

from . import utils
from .ast_utils import AstNode
from .errors import (
    CompileError,
    CompilerBugError,
    CompileWarning,
    UnexpectedTokenError,
    assert_true,
)
from .tokenizer import Range, Token, TokenType

SKIP_TOKENS = [TokenType.COMMENT, TokenType.WHITESPACE]


class ParseResult(Enum):
    """Represents the result of parsing. The extra EMPTY result is necessary
    to avoid freezing the parser: imagine a ZeroOrMore node containing a node
    that can match empty. It will repeatedly match empty and never advance
    the parser. So, ZeroOrMore stops when a failed *or empty* match is
    made."""

    SUCCESS = 0
    FAILURE = 1
    EMPTY = 2

    def matched(self):
        return self == ParseResult.SUCCESS

    def succeeded(self):
        return self != ParseResult.FAILURE

    def failed(self):
        return self == ParseResult.FAILURE


class ParseGroup:
    """A matching group. Match groups have an AST type, children grouped by
    type, and key=value pairs. At the end of parsing, the match groups will
    be converted to AST nodes by passing the children and key=value pairs to
    the AST node constructor."""

    def __init__(self, ast_type: T.Type[AstNode], start: int, text: str):
        self.ast_type = ast_type
        self.children: T.List[ParseGroup] = []
        self.keys: T.Dict[str, T.Any] = {}
        self.tokens: T.Dict[str, T.Optional[Token]] = {}
        self.ranges: T.Dict[str, Range] = {}
        self.start = start
        self.end: T.Optional[int] = None
        self.incomplete = False
        self.text = text

    def add_child(self, child: "ParseGroup"):
        self.children.append(child)

    def set_val(self, key: str, val: T.Any, token: T.Optional[Token]):
        assert_true(key not in self.keys)

        self.keys[key] = val
        self.tokens[key] = token
        if token:
            self.set_range(key, token.range)

    def set_range(self, key: str, range: Range):
        assert_true(key not in self.ranges)
        self.ranges[key] = range

    def to_ast(self):
        """Creates an AST node from the match group."""
        children = [child.to_ast() for child in self.children]

        try:
            return self.ast_type(self, children, self.keys, incomplete=self.incomplete)
        except TypeError:  # pragma: no cover
            raise CompilerBugError(
                f"Failed to construct ast.{self.ast_type.__name__} from ParseGroup. See the previous stacktrace."
            )


class ParseContext:
    """Contains the state of the parser."""

    def __init__(self, tokens: T.List[Token], text: str, index=0):
        self.tokens = tokens
        self.text = text

        self.binding_power = 0
        self.index = index
        self.start = index
        self.group: T.Optional[ParseGroup] = None
        self.group_keys: T.Dict[str, T.Tuple[T.Any, T.Optional[Token]]] = {}
        self.group_children: T.List[ParseGroup] = []
        self.group_ranges: T.Dict[str, Range] = {}
        self.last_group: T.Optional[ParseGroup] = None
        self.group_incomplete = False

        self.errors: T.List[CompileError] = []
        self.warnings: T.List[CompileWarning] = []

    def create_child(self) -> "ParseContext":
        """Creates a new ParseContext at this context's position. The new
        context will be used to parse one node. If parsing is successful, the
        new context will be applied to "self". If parsing fails, the new
        context will be discarded."""
        ctx = ParseContext(self.tokens, self.text, self.index)
        ctx.errors = self.errors
        ctx.warnings = self.warnings
        ctx.binding_power = self.binding_power
        return ctx

    def apply_child(self, other: "ParseContext"):
        """Applies a child context to this context."""

        if other.group is not None:
            # If the other context had a match group, collect all the matched
            # values into it and then add it to our own match group.
            for key, (val, token) in other.group_keys.items():
                other.group.set_val(key, val, token)
            for child in other.group_children:
                other.group.add_child(child)
            for key, range in other.group_ranges.items():
                other.group.set_range(key, range)
            other.group.end = other.tokens[other.index - 1].end
            other.group.incomplete = other.group_incomplete
            self.group_children.append(other.group)
        else:
            # If the other context had no match group of its own, collect all
            # its matched values
            self.group_keys = {**self.group_keys, **other.group_keys}
            self.group_children += other.group_children
            self.group_ranges = {**self.group_ranges, **other.group_ranges}
            self.group_incomplete |= other.group_incomplete

        self.index = other.index
        # Propagate the last parsed group down the stack so it can be easily
        # retrieved at the end of the process
        if other.group:
            self.last_group = other.group
        elif other.last_group:
            self.last_group = other.last_group

    def start_group(self, ast_type: T.Type[AstNode]):
        """Sets this context to have its own match group."""
        assert_true(self.group is None)
        self.group = ParseGroup(ast_type, self.tokens[self.index].start, self.text)

    def set_group_val(self, key: str, value: T.Any, token: T.Optional[Token]):
        """Sets a matched key=value pair on the current match group."""
        assert_true(key not in self.group_keys)
        self.group_keys[key] = (value, token)

    def set_mark(self, key: str):
        """Sets a zero-length range on the current match group at the current position."""
        self.group_ranges[key] = Range(
            self.tokens[self.index].start, self.tokens[self.index].start, self.text
        )

    def set_group_incomplete(self):
        """Marks the current match group as incomplete (it could not be fully
        parsed, but the parser recovered)."""
        self.group_incomplete = True

    def skip(self):
        """Skips whitespace and comments."""
        while (
            self.index < len(self.tokens)
            and self.tokens[self.index].type in SKIP_TOKENS
        ):
            self.index += 1

    def next_token(self) -> Token:
        """Advances the token iterator and returns the next token."""
        self.skip()
        token = self.tokens[self.index]
        self.index += 1
        return token

    def peek_token(self) -> Token:
        """Returns the next token without advancing the iterator."""
        self.skip()
        token = self.tokens[self.index]
        return token

    def skip_unexpected_token(self):
        """Skips a token and logs an "unexpected token" error."""

        self.skip()
        start = self.tokens[self.index].start
        self.next_token()
        self.skip()
        end = self.tokens[self.index - 1].end

        if (
            len(self.errors)
            and isinstance((err := self.errors[-1]), UnexpectedTokenError)
            and err.range.end == start
        ):
            err.range.end = end
        else:
            self.errors.append(UnexpectedTokenError(Range(start, end, self.text)))

    def is_eof(self) -> bool:
        return self.index >= len(self.tokens) or self.peek_token().type == TokenType.EOF


class ParseNode:
    """Base class for the nodes in the parser tree."""

    def parse(self, ctx: ParseContext) -> ParseResult:
        """Attempts to match the ParseNode at the context's current location."""
        start_idx = ctx.index
        inner_ctx = ctx.create_child()

        if self._parse(inner_ctx):
            ctx.apply_child(inner_ctx)
            if ctx.index == start_idx:
                return ParseResult.EMPTY
            else:
                return ParseResult.SUCCESS
        else:
            return ParseResult.FAILURE

    def _parse(self, ctx: ParseContext) -> bool:
        raise NotImplementedError()

    def err(self, message: str) -> "Err":
        """Causes this ParseNode to raise an exception if it fails to parse.
        This prevents the parser from backtracking, so you should understand
        what it does and how the parser works before using it."""
        return Err(self, message)

    def expected(self, expect: str) -> "Err":
        """Convenience method for err()."""
        return self.err("Expected " + expect)


class Err(ParseNode):
    """ParseNode that emits a compile error if it fails to parse."""

    def __init__(self, child, message: str):
        self.child = to_parse_node(child)
        self.message = message

    def _parse(self, ctx: ParseContext):
        if self.child.parse(ctx).failed():
            start_idx = ctx.start
            while ctx.tokens[start_idx].type in SKIP_TOKENS:
                start_idx += 1
            start_token = ctx.tokens[start_idx]

            raise CompileError(
                self.message, Range(start_token.start, start_token.start, ctx.text)
            )
        return True


class Fail(ParseNode):
    """ParseNode that emits a compile error if it parses successfully."""

    def __init__(self, child, message: str):
        self.child = to_parse_node(child)
        self.message = message

    def _parse(self, ctx: ParseContext):
        if self.child.parse(ctx).succeeded():
            start_idx = ctx.start
            while ctx.tokens[start_idx].type in SKIP_TOKENS:
                start_idx += 1

            start_token = ctx.tokens[start_idx]
            end_token = ctx.tokens[ctx.index]
            raise CompileError(
                self.message, Range.join(start_token.range, end_token.range)
            )
        return True


class Group(ParseNode):
    """ParseNode that creates a match group."""

    def __init__(self, ast_type: T.Type[AstNode], child):
        self.ast_type = ast_type
        self.child = to_parse_node(child)

    def _parse(self, ctx: ParseContext) -> bool:
        ctx.skip()
        ctx.start_group(self.ast_type)
        return self.child.parse(ctx).succeeded()


class Sequence(ParseNode):
    """ParseNode that attempts to match all of its children in sequence."""

    def __init__(self, *children):
        self.children = [to_parse_node(child) for child in children]

    def _parse(self, ctx) -> bool:
        for child in self.children:
            if child.parse(ctx).failed():
                return False
        return True


class Statement(ParseNode):
    """ParseNode that attempts to match all of its children in sequence. If any
    child raises an error, the error will be logged but parsing will continue."""

    def __init__(self, *children):
        self.children = [to_parse_node(child) for child in children]

    def _parse(self, ctx) -> bool:
        for child in self.children:
            try:
                if child.parse(ctx).failed():
                    return False
            except CompileError as e:
                ctx.errors.append(e)
                ctx.set_group_incomplete()
                return True

        token = ctx.peek_token()
        if str(token) != ";":
            ctx.errors.append(CompileError("Expected `;`", token.range))
        else:
            ctx.next_token()
        return True


class AnyOf(ParseNode):
    """ParseNode that attempts to match exactly one of its children. Child
    nodes are attempted in order."""

    def __init__(self, *children):
        self.children = children

    @property
    def children(self):
        return self._children

    @children.setter
    def children(self, children):
        self._children = [to_parse_node(child) for child in children]

    def _parse(self, ctx):
        for child in self.children:
            if child.parse(ctx).succeeded():
                return True
        return False


class Until(ParseNode):
    """ParseNode that repeats its child until a delimiting token is found. If
    the child does not match, one token is skipped and the match is attempted
    again."""

    def __init__(self, child, delimiter, between_delimiter=None):
        self.child = to_parse_node(child)
        self.delimiter = to_parse_node(delimiter)
        self.between_delimiter = (
            to_parse_node(between_delimiter) if between_delimiter is not None else None
        )

    def _parse(self, ctx: ParseContext):
        while not self.delimiter.parse(ctx).succeeded():
            if ctx.is_eof():
                return False

            try:
                if not self.child.parse(ctx).matched():
                    ctx.skip_unexpected_token()

                if (
                    self.between_delimiter is not None
                    and not self.between_delimiter.parse(ctx).succeeded()
                ):
                    if self.delimiter.parse(ctx).succeeded():
                        return True
                    else:
                        if ctx.is_eof():
                            return False
                        ctx.skip_unexpected_token()
            except CompileError as e:
                ctx.errors.append(e)
                ctx.next_token()

        return True


class ZeroOrMore(ParseNode):
    """ParseNode that matches its child any number of times (including zero
    times). It cannot fail to parse. If its child raises an exception, one token
    will be skipped and parsing will continue."""

    def __init__(self, child):
        self.child = to_parse_node(child)

    def _parse(self, ctx):
        while True:
            try:
                if not self.child.parse(ctx).matched():
                    return True
            except CompileError as e:
                ctx.errors.append(e)
                ctx.next_token()


class Delimited(ParseNode):
    """ParseNode that matches its first child any number of times (including zero
    times) with its second child in between and optionally at the end."""

    def __init__(self, child, delimiter):
        self.child = to_parse_node(child)
        self.delimiter = to_parse_node(delimiter)

    def _parse(self, ctx):
        while self.child.parse(ctx).matched() and self.delimiter.parse(ctx).matched():
            pass
        return True


class Optional(ParseNode):
    """ParseNode that matches its child zero or one times. It cannot fail to
    parse."""

    def __init__(self, child):
        self.child = to_parse_node(child)

    def _parse(self, ctx):
        self.child.parse(ctx)
        return True


class Eof(ParseNode):
    """ParseNode that matches an EOF token."""

    def _parse(self, ctx: ParseContext) -> bool:
        token = ctx.next_token()
        return token.type == TokenType.EOF


class Match(ParseNode):
    """ParseNode that matches the given literal token."""

    def __init__(self, op: str):
        self.op = op

    def _parse(self, ctx: ParseContext) -> bool:
        token = ctx.next_token()
        return str(token) == self.op

    def expected(self, expect: T.Optional[str] = None):
        """Convenience method for err()."""
        if expect is None:
            return self.err(f"Expected '{self.op}'")
        else:
            return self.err("Expected " + expect)


class UseIdent(ParseNode):
    """ParseNode that matches any identifier and sets it in a key=value pair on
    the containing match group."""

    def __init__(self, key: str):
        self.key = key

    def _parse(self, ctx: ParseContext):
        token = ctx.next_token()
        if token.type != TokenType.IDENT:
            return False

        ctx.set_group_val(self.key, str(token), token)
        return True


class UseNumber(ParseNode):
    """ParseNode that matches a number and sets it in a key=value pair on
    the containing match group."""

    def __init__(self, key: str):
        self.key = key

    def _parse(self, ctx: ParseContext):
        token = ctx.next_token()
        if token.type != TokenType.NUMBER:
            return False

        number = token.get_number()
        ctx.set_group_val(self.key, number, token)
        return True


class UseNumberText(ParseNode):
    """ParseNode that matches a number, but sets its *original text* it in a
    key=value pair on the containing match group."""

    def __init__(self, key: str):
        self.key = key

    def _parse(self, ctx: ParseContext):
        token = ctx.next_token()
        if token.type != TokenType.NUMBER:
            return False

        ctx.set_group_val(self.key, str(token), token)
        return True


class UseQuoted(ParseNode):
    """ParseNode that matches a quoted string and sets it in a key=value pair
    on the containing match group."""

    def __init__(self, key: str):
        self.key = key

    def _parse(self, ctx: ParseContext):
        token = ctx.next_token()
        if token.type != TokenType.QUOTED:
            return False

        unescaped = None

        try:
            unescaped = utils.unescape_quote(str(token))
        except utils.UnescapeError as e:
            start = ctx.tokens[ctx.index - 1].start
            range = Range(start + e.start, start + e.end, ctx.text)
            ctx.errors.append(
                CompileError(f"Invalid escape sequence '{range.text}'", range)
            )

        ctx.set_group_val(self.key, unescaped, token)

        return True


class UseLiteral(ParseNode):
    """ParseNode that doesn't match anything, but rather sets a static key=value
    pair on the containing group. Useful for, e.g., property and signal flags:
    `Sequence(Keyword("swapped"), UseLiteral("swapped", True))`"""

    def __init__(self, key: str, literal: T.Any):
        self.key = key
        self.literal = literal

    def _parse(self, ctx: ParseContext):
        ctx.set_group_val(self.key, self.literal, None)
        return True


class UseExact(ParseNode):
    """Matches the given identifier and sets it as a named token."""

    def __init__(self, key: str, string: str):
        self.key = key
        self.string = string

    def _parse(self, ctx: ParseContext):
        token = ctx.next_token()
        ctx.set_group_val(self.key, self.string, token)
        return str(token) == self.string


class Keyword(ParseNode):
    """Matches the given identifier and sets it as a named token, with the name
    being the identifier itself."""

    def __init__(self, kw: str):
        self.kw = kw
        self.set_token = True

    def _parse(self, ctx: ParseContext):
        token = ctx.next_token()
        ctx.set_group_val(self.kw, True, token)
        return str(token) == self.kw


class Mark(ParseNode):
    def __init__(self, key: str):
        self.key = key

    def _parse(self, ctx: ParseContext):
        ctx.set_mark(self.key)
        return True


def to_parse_node(value) -> ParseNode:
    if isinstance(value, str):
        return Match(value)
    elif isinstance(value, list):
        return Sequence(*value)
    elif isinstance(value, type) and hasattr(value, "grammar"):
        return Group(value, getattr(value, "grammar"))
    elif isinstance(value, ParseNode):
        return value
    else:
        raise CompilerBugError()