htsql-sqlascii-patch / src / htsql / core / tr / parse.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
#
# Copyright (c) 2006-2012, Prometheus Research, LLC
#


"""
:mod:`htsql.core.tr.parse`
==========================

This module implements the HTSQL parser.
"""


from ..mark import Mark
from .scan import scan
from .token import NameToken, StringToken, NumberToken, SymbolToken, EndToken
from .syntax import (QuerySyntax, SegmentSyntax, CommandSyntax, SelectorSyntax,
                     FunctionSyntax, MappingSyntax, OperatorSyntax,
                     QuotientSyntax, SieveSyntax, LinkSyntax, HomeSyntax,
                     AssignmentSyntax, SpecifierSyntax, GroupSyntax,
                     IdentifierSyntax, WildcardSyntax, ComplementSyntax,
                     ReferenceSyntax, StringSyntax, NumberSyntax)
from .error import ParseError


class Parser(object):
    """
    Implements an HTSQL parser.

    A parser takes a stream of tokens from the HTSQL scanner and
    produces a node of a syntax tree.

    This is an abstract class; see subclasses of :class:`Parser` for
    implementations of various parts of the HTSQL grammar.

    `input` (a string)
        The input HTSQL expression.
    """

    # FIXME: get rid of the metaclass and `<<`.  Implement `Parser`
    # as an adapter with matching by rule of an LL(n) grammar.

    class __metaclass__(type):
        # Implements a shortcut:
        #   Parser << tokens
        # to call
        #   Parser.process(tokens)

        def __lshift__(parser_class, tokens):
            return parser_class.process(tokens)

    def __init__(self, input):
        assert isinstance(input, (str, unicode))
        self.input = input

    def parse(self):
        """
        Parses the input expression; returns the corresponding syntax node.
        """
        # Tokenize the input query.
        tokens = scan(self.input)
        # Parse the input query.
        syntax = self.process(tokens)
        # Ensure that we reached the end of the token stream.
        if not tokens.pop(EndToken, do_force=False):
            token = tokens.pop()
            raise ParseError("expected the end of query; got '%s'" % token,
                             token.mark)
        return syntax

    @classmethod
    def process(cls, tokens):
        """
        Takes a stream of tokens; returns a syntax node.

        This function does not have to exhaust the token stream.

        The ``<<`` operator could be used as a synonym for :meth:`process`;
        the following expressions are equivalent::

            Parser << tokens
            Parser.process(tokens)

        `tokens` (:class:`htsql.core.tr.scan.TokenStream`)
            The stream of tokens to parse.
        """
        # Override in subclasses.
        raise NotImplementedError()


class QueryParser(Parser):
    """
    Parses an HTSQL query.

    Here is the grammar of HTSQL::

        input           ::= segment END

        segment         ::= '/' ( top command* )?
        command         ::= '/' ':' identifier ( '/' top? | call | flow )?

        top             ::= flow ( direction | mapping )*
        direction       ::= '+' | '-'
        mapping         ::= ':' identifier ( flow | call )?

        flow            ::= disjunction ( sieve | quotient | selection )*
        sieve           ::= '?' disjunction
        quotient        ::= '^' disjunction
        selection       ::= selector ( '.' atom )*

        disjunction     ::= conjunction ( '|' conjunction )*
        conjunction     ::= negation ( '&' negation )*
        negation        ::= '!' negation | comparison

        comparison      ::= expression ( ( '~' | '!~' |
                                           '<=' | '<' | '>=' |  '>' |
                                           '==' | '=' | '!==' | '!=' )
                                         expression )?

        expression      ::= term ( ( '+' | '-' ) term )*
        term            ::= factor ( ( '*' | '/' ) factor )*
        factor          ::= ( '+' | '-' ) factor | pointer

        pointer         ::= specifier ( link | assignment )?
        link            ::= '->' flow
        assignment      ::= ':=' top

        specifier       ::= atom ( '.' atom )*
        atom            ::= '@' atom | '*' index? | '^' | selector | group |
                            identifier call? | reference | literal
        index           ::= NUMBER | '(' NUMBER ')'

        group           ::= '(' top ')'
        call            ::= '(' arguments? ')'
        selector        ::= '{' arguments? '}'
        arguments       ::= argument ( ',' argument )* ','?
        argument        ::= segment | top
        reference       ::= '$' identifier

        identifier      ::= NAME
        literal         ::= STRING | NUMBER

    Note that this grammar is almost LL(1); one notable exception is
    the postfix ``+`` and ``-`` operators.
    """

    @classmethod
    def process(cls, tokens):
        # Expect:
        #   input       ::= segment END
        segment = SegmentParser << tokens
        return QuerySyntax(segment, segment.mark)


class SegmentParser(Parser):
    """
    Parses a `segment` production.
    """

    @classmethod
    def process(cls, tokens):
        # Expect:
        #   segment     ::= '/' ( top command* )?
        #   command     ::= '/' ':' identifier ( '/' top? | call | flow )?
        head_token = tokens.pop(SymbolToken, [u'/'], do_force=False)
        if not head_token:
            token = tokens.pop()
            raise ParseError("query must start with symbol '/'", token.mark)
        branch = None
        if not (tokens.peek(EndToken) or
                tokens.peek(SymbolToken, [u',', u')', u'}'])):
            branch = TopParser << tokens
            while tokens.peek(SymbolToken, [u'/']):
                tail_token = tokens.pop(SymbolToken, [u'/'])
                if not (tokens.peek(EndToken) or
                        tokens.peek(SymbolToken, [u',', u')', u'}'])):
                    if not (tokens.pop(SymbolToken, [u':'], do_force=False) and
                            tokens.peek(NameToken)):
                        raise ParseError("symbol '/' must be followed by ':'"
                                         " and an identifier", tail_token.mark)
                    mark = Mark.union(head_token, branch)
                    lbranch = SegmentSyntax(branch, mark)
                    identifier = IdentifierParser << tokens
                    rbranches = []
                    if not (tokens.peek(EndToken) or
                            tokens.peek(SymbolToken, [u',', u')', u'}'])):
                        if tokens.peek(SymbolToken, [u'/']):
                            if not tokens.peek(SymbolToken, [u':'], ahead=1):
                                rbranch_token = tokens.pop(SymbolToken, [u'/'])
                                rbranch = None
                                if not (tokens.peek(EndToken) or
                                        tokens.peek(SymbolToken,
                                                    [u',', u')', u'}'])):
                                    rbranch = TopParser << tokens
                                mark = Mark.union(rbranch_token, rbranch)
                                rbranch = SegmentSyntax(rbranch, mark)
                                rbranches.append(rbranch)
                        elif tokens.peek(SymbolToken, [u'(']):
                            open_token = tokens.pop(SymbolToken, [u'('])
                            while not tokens.peek(SymbolToken, [u')']):
                                if tokens.peek(SymbolToken, [u'/']):
                                    rbranch = SegmentParser << tokens
                                else:
                                    rbranch = TopParser << tokens
                                rbranches.append(rbranch)
                                if tokens.peek(SymbolToken, [u',']):
                                    tokens.pop(SymbolToken, [u','])
                                elif not tokens.peek(SymbolToken, [u')']):
                                    mark = Mark.union(open_token, *rbranches)
                                    raise ParseError("cannot find a matching"
                                                     " ')'", mark)
                            tail_token = tokens.pop(SymbolToken, [u')'])
                        else:
                            rbranch = FlowParser << tokens
                            rbranches.append(rbranch)
                mark = Mark.union(lbranch, identifier, tail_token, *rbranches)
                branch = CommandSyntax(identifier, lbranch, rbranches, mark)
        mark = Mark.union(head_token, branch)
        segment = SegmentSyntax(branch, mark)
        return segment


class TopParser(Parser):
    """
    Parses a `top` production.
    """

    @classmethod
    def process(cls, tokens):
        # Expect:
        #   top         ::= flow ( direction | mapping )*
        #   direction   ::= '+' | '-'
        #   mapping     ::= ':' identifier ( flow | call )?
        #   FOLLOW(mapping) = ['+','-',':',',',')','}']
        top = FlowParser << tokens
        while tokens.peek(SymbolToken, [u'+', u'-', u':']):
            # Parse `direction` decorator.
            if tokens.peek(SymbolToken, [u'+', u'-']):
                symbol_token = tokens.pop(SymbolToken, [u'+', u'-'])
                symbol = symbol_token.value
                mark = Mark.union(top, symbol_token)
                top = OperatorSyntax(symbol, top, None, mark)
            # Parse `mapping` application.
            else:
                symbol_token = tokens.pop(SymbolToken, [u':'])
                if not tokens.peek(NameToken):
                    raise ParseError("symbol ':' must be followed by"
                                     " an identifier", symbol_token.mark)
                identifier = IdentifierParser << tokens
                lbranch = top
                rbranches = []
                # Mapping parameters in parentheses.
                if tokens.peek(SymbolToken, [u'(']):
                    open_token = tokens.pop(SymbolToken, [u'('])
                    while not tokens.peek(SymbolToken, [u')']):
                        if tokens.peek(SymbolToken, [u'/']):
                            rbranch = SegmentParser << tokens
                        else:
                            rbranch = TopParser << tokens
                        rbranches.append(rbranch)
                        if tokens.peek(SymbolToken, [u',']):
                            tokens.pop(SymbolToken, [u','])
                        elif not tokens.peek(SymbolToken, [u')']):
                            mark = Mark.union(open_token, *rbranches)
                            raise ParseError("cannot find a matching ')'",
                                             mark)
                    tail_token = tokens.pop(SymbolToken, [u')'])
                    mark = Mark.union(top, tail_token)
                # No parenthesis: either no parameters or a single parameter.
                else:
                    # Determine whether the mapping has a parameter or not.
                    # If not, must be followed by one of: `:` (next mapping),
                    # `,`, `)`, `}` (punctuation), or `+`, `-` (direction
                    # decorators).  We skip through `+` and `-` since they
                    # could also start a parameter as an unary prefix operator.
                    ahead = 0
                    while tokens.peek(SymbolToken, [u'+', u'-'], ahead=ahead):
                        ahead += 1
                    if not (tokens.peek(SymbolToken, [u':', u',', u')', u'}'],
                                                     ahead=ahead) or
                            tokens.peek(EndToken, ahead=ahead)):
                        rbranch = FlowParser << tokens
                        rbranches.append(rbranch)
                    mark = Mark.union(top, identifier, *rbranches)
                top = MappingSyntax(identifier, lbranch, rbranches, mark)
        return top


class FlowParser(Parser):
    """
    Parses a `flow` production.
    """

    @classmethod
    def process(cls, tokens):
        # Expect:
        #   flow        ::= disjunction ( sieve | quotient | selection )*
        #   sieve       ::= '?' disjunction
        #   quotient    ::= '^' disjunction
        #   selection   ::= selector ( '.' atom )*
        flow = DisjunctionParser << tokens
        while tokens.peek(SymbolToken, [u'?', u'^', u'{']):
            if tokens.peek(SymbolToken, [u'?'], do_pop=True):
                lbranch = flow
                rbranch = DisjunctionParser << tokens
                mark = Mark.union(lbranch, rbranch)
                flow = SieveSyntax(lbranch, rbranch, mark)
            elif tokens.peek(SymbolToken, [u'^'], do_pop=True):
                lbranch = flow
                rbranch = DisjunctionParser << tokens
                mark = Mark.union(lbranch, rbranch)
                flow = QuotientSyntax(lbranch, rbranch, mark)
            elif tokens.peek(SymbolToken, [u'{']):
                open_token = tokens.pop(SymbolToken, [u'{'])
                lbranch = flow
                rbranches = []
                while not tokens.peek(SymbolToken, [u'}']):
                    if tokens.peek(SymbolToken, [u'/']):
                        rbranch = SegmentParser << tokens
                    else:
                        rbranch = TopParser << tokens
                    rbranches.append(rbranch)
                    if tokens.peek(SymbolToken, [u',']):
                        tokens.pop(SymbolToken, [u','])
                    elif not tokens.peek(SymbolToken, [u'}']):
                        mark = Mark.union(open_token, *rbranches)
                        raise ParseError("cannot find a matching '}'",
                                         mark)
                tail_token = tokens.pop(SymbolToken, [u'}'])
                mark = Mark.union(flow, tail_token)
                flow = SelectorSyntax(lbranch, rbranches, mark)
                while tokens.peek(SymbolToken, [u'.'], do_pop=True):
                    lbranch = flow
                    rbranch = AtomParser << tokens
                    mark = Mark.union(flow, rbranch)
                    flow = SpecifierSyntax(lbranch, rbranch, mark)
            else:
                # Not reachable.
                assert False
        return flow


class DisjunctionParser(Parser):
    """
    Parses a `disjunction` production.
    """

    @classmethod
    def process(cls, tokens):
        # Parses the production:
        #   disjunction ::= conjunction ( '|' conjunction )*
        test = ConjunctionParser << tokens
        while tokens.peek(SymbolToken, [u'|']):
            symbol_token = tokens.pop(SymbolToken, [u'|'])
            symbol = symbol_token.value
            lbranch = test
            rbranch = ConjunctionParser << tokens
            mark = Mark.union(lbranch, rbranch)
            test = OperatorSyntax(symbol, lbranch, rbranch, mark)
        return test


class ConjunctionParser(Parser):
    """
    Parses a `conjunction` production.
    """

    @classmethod
    def process(cls, tokens):
        # Expect:
        #   conjunction ::= negation ( '&' negation )*
        test = NegationParser << tokens
        while tokens.peek(SymbolToken, [u'&']):
            symbol_token = tokens.pop(SymbolToken, [u'&'])
            symbol = symbol_token.value
            lbranch = test
            rbranch = NegationParser << tokens
            mark = Mark.union(lbranch, rbranch)
            test = OperatorSyntax(symbol, lbranch, rbranch, mark)
        return test


class NegationParser(Parser):
    """
    Parses a `negation` production.
    """

    @classmethod
    def process(cls, tokens):
        # Expect:
        #   negation    ::= '!' negation | comparison
        symbol_tokens = []
        while tokens.peek(SymbolToken, [u'!']):
            symbol_token = tokens.pop(SymbolToken, [u'!'])
            symbol_tokens.append(symbol_token)
        test = ComparisonParser << tokens
        while symbol_tokens:
            symbol_token = symbol_tokens.pop()
            symbol = symbol_token.value
            mark = Mark.union(symbol_token, test)
            test = OperatorSyntax(symbol, None, test, mark)
        return test


class ComparisonParser(Parser):
    """
    Parses a `comparison` production.
    """

    @classmethod
    def process(cls, tokens):
        # Expect:
        #   comparison  ::= expression ( ( '~' | '!~' |
        #                                  '<=' | '<' | '>=' |  '>' |
        #                                  '==' | '=' | '!==' | '!=' )
        #                                expression )?
        expression = ExpressionParser << tokens
        symbol_token = tokens.peek(SymbolToken,
                                   [u'~', u'!~', u'<=', u'<', u'>=', u'>',
                                    u'==', u'=', u'!==', u'!='], do_pop=True)
        if symbol_token is None:
            return expression
        symbol = symbol_token.value
        lbranch = expression
        rbranch = ExpressionParser << tokens
        mark = Mark.union(lbranch, rbranch)
        comparison = OperatorSyntax(symbol, lbranch, rbranch, mark)
        return comparison


class ExpressionParser(Parser):
    """
    Parses an `expression` production.
    """

    @classmethod
    def process(cls, tokens):
        # Expect:
        #   expression  ::= term ( ( '+' | '-' ) term )*
        expression = TermParser << tokens
        # Do a look-ahead to distinguish between infix and postfix `+` or `-`.
        while tokens.peek(SymbolToken, [u'+', u'-']):
            ahead = 1
            while tokens.peek(SymbolToken, [u'+', u'-'], ahead=ahead):
                ahead += 1
            if tokens.peek(SymbolToken, [u':', u',', u')', u'}'], ahead=ahead):
                break
            symbol_token = tokens.pop(SymbolToken, [u'+', u'-'])
            symbol = symbol_token.value
            lbranch = expression
            rbranch = TermParser << tokens
            mark = Mark.union(lbranch, rbranch)
            expression = OperatorSyntax(symbol, lbranch, rbranch, mark)
        return expression


class TermParser(Parser):
    """
    Parses a `term` production.
    """

    @classmethod
    def process(cls, tokens):
        # Expect:
        #   term        ::= factor ( ( '*' | '/' ) factor )*
        term = FactorParser << tokens
        while (tokens.peek(SymbolToken, [u'*'])
               or (tokens.peek(SymbolToken, [u'/'], ahead=0)
                   and not tokens.peek(SymbolToken, [u':'], ahead=1))):
            symbol_token = tokens.pop(SymbolToken, [u'*', u'/'])
            symbol = symbol_token.value
            lbranch = term
            rbranch = FactorParser << tokens
            mark = Mark.union(lbranch, rbranch)
            term = OperatorSyntax(symbol, lbranch, rbranch, mark)
        return term


class FactorParser(Parser):
    """
    Parses a `pointer` production.
    """

    @classmethod
    def process(cls, tokens):
        # Expect:
        #   factor      ::= ( '+' | '-' ) factor | pointer
        symbol_tokens = []
        while tokens.peek(SymbolToken, [u'+', u'-']):
            symbol_token = tokens.pop(SymbolToken, [u'+', u'-'])
            symbol_tokens.append(symbol_token)
        factor = PointerParser << tokens
        while symbol_tokens:
            symbol_token = symbol_tokens.pop()
            symbol = symbol_token.value
            mark = Mark.union(symbol_token, factor)
            factor = OperatorSyntax(symbol, None, factor, mark)
        return factor


class PointerParser(Parser):
    """
    Parses a `pointer` production.
    """

    @classmethod
    def process(cls, tokens):
        # Expect:
        #   pointer     ::= specifier ( link | assignment )?
        #   link        ::= '->' flow
        #   assignment  ::= ':=' top
        pointer = SpecifierParser << tokens
        if tokens.peek(SymbolToken, [u'->'], do_pop=True):
            lbranch = pointer
            rbranch = FlowParser << tokens
            mark = Mark.union(lbranch, rbranch)
            pointer = LinkSyntax(lbranch, rbranch, mark)
        elif tokens.peek(SymbolToken, [u':='], do_pop=True):
            lbranch = pointer
            rbranch = TopParser << tokens
            mark = Mark.union(lbranch, rbranch)
            pointer = AssignmentSyntax(lbranch, rbranch, mark)
        return pointer


class SpecifierParser(Parser):
    """
    Parses a `specifier` production.
    """

    @classmethod
    def process(cls, tokens):
        # Expect:
        #   specifier   ::= atom ( '.' atom )*
        specifier = AtomParser << tokens
        while tokens.peek(SymbolToken, [u'.']):
            tokens.pop(SymbolToken, [u'.'])
            lbranch = specifier
            rbranch = AtomParser << tokens
            mark = Mark.union(lbranch, rbranch)
            specifier = SpecifierSyntax(lbranch, rbranch, mark)
        return specifier


class AtomParser(Parser):
    """
    Parses an `atom` production.
    """

    @classmethod
    def process(cls, tokens):
        # Expect:
        #   atom        ::= '@' atom | '*' index? | '^' | selector | group |
        #                   identifier call? | reference | literal
        #   index       ::= NUMBER | '(' NUMBER ')'
        #   call        ::= '(' arguments? ')'
        #   arguments   ::= argument ( ',' argument )* ','?
        #   argument    ::= segment | top
        #   reference   ::= '$' identifier
        #   literal     ::= STRING | NUMBER

        # A home indicator.
        if tokens.peek(SymbolToken, [u'@']):
            symbol_token = tokens.pop(SymbolToken, [u'@'])
            atom = AtomParser << tokens
            mark = Mark.union(symbol_token, atom)
            home = HomeSyntax(atom, mark)
            return home
        # A wildcard expression.
        if tokens.peek(SymbolToken, [u'*']):
            symbol_token = tokens.pop(SymbolToken, [u'*'])
            index = None
            if tokens.peek(NumberToken):
                index_token = tokens.pop(NumberToken)
                index = NumberSyntax(index_token.value, index_token.mark)
            mark = Mark.union(symbol_token, index)
            wildcard = WildcardSyntax(index, mark)
            return wildcard
        # A complement atom.
        if tokens.peek(SymbolToken, [u'^']):
            symbol_token = tokens.pop(SymbolToken, [u'^'])
            complement = ComplementSyntax(symbol_token.mark)
            return complement
        # An expression in parentheses.
        elif tokens.peek(SymbolToken, [u'(']):
            group = GroupParser << tokens
            return group
        # A selector.
        elif tokens.peek(SymbolToken, [u'{']):
            selector = SelectorParser << tokens
            return selector
        # An identifier or a function call.
        elif tokens.peek(NameToken):
            identifier = IdentifierParser << tokens
            if tokens.peek(SymbolToken, [u'(']):
                open_token = tokens.pop(SymbolToken, [u'('])
                branches = []
                while not tokens.peek(SymbolToken, [u')']):
                    if tokens.peek(SymbolToken, [u'/']):
                        rbranch = SegmentParser << tokens
                    else:
                        rbranch = TopParser << tokens
                    branches.append(rbranch)
                    if tokens.peek(SymbolToken, [u',']):
                        tokens.pop(SymbolToken, [u','])
                    elif not tokens.peek(SymbolToken, [u')']):
                        mark = Mark.union(open_token, *branches)
                        raise ParseError("cannot find a matching ')'", mark)
                tail_token = tokens.pop(SymbolToken, [u')'])
                mark = Mark.union(identifier, tail_token)
                function = FunctionSyntax(identifier, branches, mark)
                return function
            else:
                return identifier
        # A reference.
        elif tokens.peek(SymbolToken, [u'$']):
            head_token = tokens.pop(SymbolToken, [u'$'])
            if not tokens.peek(NameToken):
                raise ParseError("symbol '$' must be followed by an identifier",
                                 head_token.mark)
            identifier = IdentifierParser << tokens
            mark = Mark.union(head_token, identifier)
            reference = ReferenceSyntax(identifier, mark)
            return reference
        # A string literal.
        elif tokens.peek(StringToken):
            token = tokens.pop(StringToken)
            try:
                token.value.encode('latin1')
            except UnicodeEncodeError:
                raise ParseError("invalid literal encoding", token.mark)
            return StringSyntax(token.value, token.mark)
        # A numeric literal.
        elif tokens.peek(NumberToken):
            token = tokens.pop(NumberToken)
            return NumberSyntax(token.value, token.mark)
        # Can't find anything suitable; produce an error message.
        token = tokens.pop()
        if token.is_end:
            raise ParseError("unexpected end of query", token.mark)
        else:
            raise ParseError("unexpected symbol '%s'" % token, token.mark)
        # Not reachable.
        assert False


class GroupParser(Parser):
    """
    Parses a `group` production.
    """

    @classmethod
    def process(self, tokens):
        # Expect:
        #   group       ::= '(' top ')'
        head_token = tokens.pop(SymbolToken, [u'('])
        branch = TopParser << tokens
        tail_token = tokens.pop(SymbolToken, [u')'], do_force=False)
        if tail_token is None:
            mark = Mark.union(head_token, branch)
            raise ParseError("cannot find a matching ')'", mark)
        mark = Mark.union(head_token, tail_token)
        group = GroupSyntax(branch, mark)
        return group


class SelectorParser(Parser):
    """
    Parses a `selector` production.
    """

    @classmethod
    def process(cls, tokens):
        # Expect:
        #   selector    ::= '{' arguments? '}'
        #   arguments   ::= argument ( ',' argument )* ','?
        #   argument    ::= segment | top
        head_token = tokens.pop(SymbolToken, [u'{'])
        branches = []
        while not tokens.peek(SymbolToken, [u'}']):
            if tokens.peek(SymbolToken, [u'/']):
                rbranch = SegmentParser << tokens
            else:
                rbranch = TopParser << tokens
            branches.append(rbranch)
            if tokens.peek(SymbolToken, [u',']):
                tokens.pop(SymbolToken, [u','])
            elif not tokens.peek(SymbolToken, [u'}']):
                mark = Mark.union(head_token, *branches)
                raise ParseError("cannot find a matching '}'", mark)
        tail_token = tokens.pop(SymbolToken, [u'}'])
        mark = Mark.union(head_token, tail_token)
        selector = SelectorSyntax(None, branches, mark)
        return selector


class IdentifierParser(Parser):
    """
    Parses an `identifier` production.
    """

    @classmethod
    def process(cls, tokens):
        # Expect:
        #   identifier      ::= NAME
        name_token = tokens.pop(NameToken)
        identifier = IdentifierSyntax(name_token.value, name_token.mark)
        return identifier


def parse(input, Parser=QueryParser):
    """
    Parses the input HTSQL query; returns the corresponding syntax node.

    In case of syntax errors, may raise :exc:`htsql.core.tr.error.ScanError`
    or :exc:`htsql.core.tr.error.ParseError`.

    `input` (a string)
        An HTSQL query or an HTSQL expression.

    `Parser` (a subclass of :class:`Parser`)
        The parser to use for parsing the input expression.  By default,
        `input` is treated as a complete HTSQL query.
    """
    parser = Parser(input)
    return parser.parse()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.