Source

htsql-firebird / src / htsql / core / tr / syntax.py

Full commit
  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
#
# Copyright (c) 2006-2012, Prometheus Research, LLC
# See `LICENSE` for license information, `AUTHORS` for the list of authors.
#


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

This module defines syntax nodes for the HTSQL grammar.
"""


from ..mark import Mark
from ..util import maybe, listof, Printable, Clonable, Comparable
import re


class Syntax(Printable, Comparable, Clonable):
    """
    Represents a syntax node.

    The syntax tree expresses the structure of the input HTSQL query, with each
    node corresponding to some rule in the HTSQL grammar.

    `mark` (:class:`htsql.core.mark.Mark`)
        The location of the node in the original query.
    """

    # The pattern to %-escape unsafe characters.
    escape_pattern = r"[\x00-\x1F%\x7F]"
    escape_regexp = re.compile(escape_pattern, re.U)
    escape_replace = (lambda s, m: u"%%%02X" % ord(m.group()))

    def __init__(self, mark, equality_vector):
        assert isinstance(mark, Mark)
        super(Syntax, self).__init__(equality_vector=equality_vector)
        self.mark = mark

    def __unicode__(self):
        """
        Returns a fragment of an HTSQL query that, when parsed back, produces
        the same syntax node.
        """
        # Override when subclassing.
        raise NotImplementedError()

    def __str__(self):
        """
        Returns a fragment of HTSQL encoded in UTF-8.
        """
        return unicode(self).encode('utf-8')


class QuerySyntax(Syntax):
    """
    Represents an HTSQL query.

    `segment` (:class:`SegmentSyntax`)
        The top-level segment.
    """

    def __init__(self, segment, mark):
        assert isinstance(segment, SegmentSyntax)

        super(QuerySyntax, self).__init__(mark, equality_vector=(segment,))
        self.segment = segment

    def __unicode__(self):
        # Generate an HTSQL query:
        #   /<segment>
        return unicode(self.segment)


class SegmentSyntax(Syntax):
    """
    Represents a segment expression.

    `branch` (:class:`Syntax` or ``None``)
        An expression.
    """

    def __init__(self, branch, mark):
        assert isinstance(branch, maybe(Syntax))

        super(SegmentSyntax, self).__init__(mark, equality_vector=(branch,))
        self.branch = branch

    def __unicode__(self):
        # Display:
        #   /<branch>
        if self.branch is None:
            return u'/'
        elif isinstance(self.branch, CommandSyntax):
            return unicode(self.branch)
        else:
            return u'/%s' % self.branch


class SelectorSyntax(Syntax):
    """
    Represents a selector expression.

    A selector is a comma-separated list of expression enclosed in
    curly brakets, with an optional selector base::

        {<rbranch>, ...}
        <lbranch>{<rbranch>, ...}

    `lbranch` (:class:`Syntax` or ``None``)
        The selector base.

    `rbranches` (a list of :class:`Syntax`)
        Selector elements.
    """

    def __init__(self, lbranch, rbranches, mark):
        assert isinstance(lbranch, maybe(Syntax))
        assert isinstance(rbranches, listof(Syntax))

        super(SelectorSyntax, self).__init__(mark,
                equality_vector=(lbranch, tuple(rbranches)))
        self.lbranch = lbranch
        self.rbranches = rbranches

    def __unicode__(self):
        # Generate an HTSQL fragment:
        #   {<rbranch>,...}
        # or
        #   <lbranch>{<rbranch>,...}
        chunks = []
        if self.lbranch is not None:
            chunks.append(unicode(self.lbranch))
        chunks.append(u'{')
        chunks.append(u','.join(unicode(rbranch)
                                for rbranch in self.rbranches))
        chunks.append(u'}')
        return u''.join(chunks)


class ApplicationSyntax(Syntax):
    """
    Represents a function or an operator call.

    This is an abstract class with three concrete subclasses
    corresponding to function calls, function calls in infix form
    and operators.

    `name` (a Unicode string)
        The name of the function or the operator.

    `arguments` (a list of :class:`Syntax`)
        The list of arguments.
    """

    def __init__(self, name, arguments, mark, equality_vector):
        assert isinstance(name, unicode)
        assert isinstance(arguments, listof(Syntax))
        super(ApplicationSyntax, self).__init__(mark, equality_vector)
        self.name = name
        self.arguments = arguments


class FunctionSyntax(ApplicationSyntax):
    """
    Represents a function call.

    A function call starts with the function name followed by
    the list of arguments enclosed in parentheses::

        <identifier>(<branch>, ...)

    `identifier` (:class:`IdentifierSyntax`)
        The function name.

    `branches` (a list of :class:`Syntax`)
        The list of arguments.
    """

    def __init__(self, identifier, branches, mark):
        assert isinstance(identifier, IdentifierSyntax)
        assert isinstance(branches, listof(Syntax))

        name = identifier.value
        arguments = branches
        super(FunctionSyntax, self).__init__(name, arguments, mark,
                equality_vector=(identifier, tuple(branches)))
        self.identifier = identifier
        self.branches = branches

    def __unicode__(self):
        # Generate a fragment:
        #   <identifier>(<branch>,...)
        chunks = []
        chunks.append(unicode(self.identifier))
        chunks.append(u'(%s)' % u','.join(unicode(branch)
                                          for branch in self.branches))
        return u''.join(chunks)


class MappingSyntax(ApplicationSyntax):
    """
    Represents a function call in infix or postfix form.

    This expression has one of the forms::

        <lbranch> :<identifier>
        <lbranch> :<identifier> <rbranch>
        <lbranch> :<identifier> (<rbranch>, ...)

    and is equivalent to a regular function call::

        <identifier>(<lbranch>, <rbranch>, ...)

    `identifier` (:class:`IdentifierSyntax`)
        The function name.

    `lbranch` (:class:`Syntax`)
        The left operand.

    `rbranches` (a list of :class:`Syntax`)
        The right operands.
    """

    def __init__(self, identifier, lbranch, rbranches, mark):
        assert isinstance(identifier, IdentifierSyntax)
        assert isinstance(lbranch, Syntax)
        assert isinstance(rbranches, listof(Syntax))

        name = identifier.value
        arguments = [lbranch] + rbranches
        super(MappingSyntax, self).__init__(name, arguments, mark,
                equality_vector=(identifier, lbranch, tuple(rbranches)))
        self.identifier = identifier
        self.lbranch = lbranch
        self.rbranches = rbranches

    def __unicode__(self):
        # Generate an HTSQL fragment:
        #   <lbranch>:<identifier>(<rbranch>,...)
        chunks = []
        chunks.append(unicode(self.lbranch))
        chunks.append(u':%s' % self.identifier)
        if self.rbranches:
            chunks.append(u'(%s)' % u','.join(unicode(rbranch)
                                              for rbranch in self.rbranches))
        return u''.join(chunks)


class CommandSyntax(MappingSyntax):

    def __init__(self, identifier, lbranch, rbranches, mark):
        assert isinstance(lbranch, SegmentSyntax)
        super(CommandSyntax, self).__init__(identifier,
                lbranch, rbranches, mark)

    def __unicode__(self):
        chunks = []
        chunks.append(unicode(self.lbranch))
        chunks.append(u'/:%s' % self.identifier)
        if self.rbranches:
            chunks.append(u'(%s)' % u','.join(unicode(rbranch)
                                              for rbranch in self.rbranches))
        return u''.join(chunks)


class OperatorSyntax(ApplicationSyntax):
    """
    Represents an operator expression.

    An operator expression has one of the forms::

        <lbranch> <symbol> <rbranch>
                  <symbol> <rbranch>
        <lbranch> <symbol>

    The operator name is composed from the symbol:

    * `<symbol>` for infix binary operators;
    * `<symbol>_` for prefix unary operators;
    * `_<symbol>` for postfix unary operators.

    Some operators (those with non-standard precedence) are separated
    into subclasses of :class:`OperatorSyntax`.

    `symbol` (a Unicode string)
        The operator symbol.

    `lbranch` (:class:`Syntax` or ``None``)
        The left operand.

    `rbranch` (:class:`Syntax` or ``None``)
        The right operand.
    """

    def __init__(self, symbol, lbranch, rbranch, mark):
        assert isinstance(symbol, unicode)
        assert isinstance(lbranch, maybe(Syntax))
        assert isinstance(rbranch, maybe(Syntax))
        assert lbranch is not None or rbranch is not None
        # The operator name is derived from the symbol by the rule:
        # * `<symbol>` for infix operators;
        # * `<symbol>_` for prefix operators;
        # * `_<symbol>` for postfix operators.
        # Thus, `a+b`, `+b` and `a+` are operators with the names `+`, `+_`
        # and `_+` respectively.
        name = symbol
        if lbranch is None:
            name = name+u'_'
        if rbranch is None:
            name = u'_'+name
        # Gather the arguments.  We distinguish prefix and postfix operators
        # by name, so we don't need to specifically note the original position
        # of the arguments.
        arguments = []
        if lbranch is not None:
            arguments.append(lbranch)
        if rbranch is not None:
            arguments.append(rbranch)
        super(OperatorSyntax, self).__init__(name, arguments, mark,
                equality_vector=(symbol, lbranch, rbranch))
        self.symbol = symbol
        self.lbranch = lbranch
        self.rbranch = rbranch

    def __unicode__(self):
        # Generate a fragment:
        #   <lbranch><symbol><rbranch>
        chunks = []
        if self.lbranch is not None:
            chunks.append(unicode(self.lbranch))
        chunks.append(self.symbol)
        if self.rbranch is not None:
            chunks.append(unicode(self.rbranch))
        return u''.join(chunks)


class QuotientSyntax(OperatorSyntax):
    """
    Represents a quotient operator.

    ::

        <lbranch> ^ <rbranch>
    """

    def __init__(self, lbranch, rbranch, mark):
        super(QuotientSyntax, self).__init__(u'^', lbranch, rbranch, mark)


class SieveSyntax(OperatorSyntax):
    """
    Represents a sieve operator.

    ::

        <lbranch> ? <rbranch>
    """

    def __init__(self, lbranch, rbranch, mark):
        super(SieveSyntax, self).__init__(u'?', lbranch, rbranch, mark)


class LinkSyntax(OperatorSyntax):
    """
    Represents a linking operator.

    ::

        <lbranch> -> <rbranch>
    """

    def __init__(self, lbranch, rbranch, mark):
        super(LinkSyntax, self).__init__(u'->', lbranch, rbranch, mark)


class HomeSyntax(OperatorSyntax):
    """
    Represents a home indicator.

    ::

        @ <rbranch>
    """
    def __init__(self, rbranch, mark):
        super(HomeSyntax, self).__init__(u'@', None, rbranch, mark)


class AssignmentSyntax(OperatorSyntax):
    """
    Represents an assignment operator.

    ::

        <lbranch> := <rbranch>
    """

    def __init__(self, lbranch, rbranch, mark):
        super(AssignmentSyntax, self).__init__(u':=', lbranch, rbranch, mark)


class SpecifierSyntax(OperatorSyntax):
    """
    Represents a specifier expression.

    ::

        <lbranch> . <rbranch>
    """

    def __init__(self, lbranch, rbranch, mark):
        super(SpecifierSyntax, self).__init__(u'.', lbranch, rbranch, mark)


class GroupSyntax(Syntax):
    """
    Represents an expression in parentheses.

    The parentheses are kept in the syntax tree to make sure the
    serialization from the syntax tree to HTSQL obeys the grammar.

    `branch` (:class:`Syntax`)
        The branch.
    """

    def __init__(self, branch, mark):
        assert isinstance(branch, Syntax)

        super(GroupSyntax, self).__init__(mark, equality_vector=(branch,))
        self.branch = branch

    def __unicode__(self):
        return u'(%s)' % self.branch


class IdentifierSyntax(Syntax):
    """
    Represents an identifier.

    `value` (a Unicode string)
        The identifier value.
    """

    def __init__(self, value, mark):
        assert isinstance(value, unicode)
        # FIXME: check for a valid identifier.

        super(IdentifierSyntax, self).__init__(mark, equality_vector=(value,))
        self.value = value

    def __unicode__(self):
        return self.value


class WildcardSyntax(Syntax):
    """
    Represents a wildcard expression.

    ::

        *
        * <index>

    `index` (:class:`NumberSyntax` or ``None``)
        The index in a wildcard expression.
    """

    def __init__(self, index, mark):
        assert isinstance(index, maybe(NumberSyntax))

        super(WildcardSyntax, self).__init__(mark, equality_vector=(index,))
        self.index = index

    def __unicode__(self):
        # Generate a fragment:
        #   *<index>
        # FIXME: may break if followed by a specifier (`.`) symbol.
        if self.index is not None:
            return u'*%s' % self.index
        return u'*'


class ComplementSyntax(Syntax):
    """
    Represents a complement expression.

    ::

        ^
    """

    def __init__(self, mark):
        super(ComplementSyntax, self).__init__(mark, equality_vector=())

    def __unicode__(self):
        return u'^'


class ReferenceSyntax(Syntax):
    """
    Represents a reference.

    A reference is an identifier preceded by symbol ``$``::

        $ <identifier>

    `identifier` (:class:`IdentifierSyntax`)
        The name of the reference.
    """

    def __init__(self, identifier, mark):
        assert isinstance(identifier, IdentifierSyntax)
        super(ReferenceSyntax, self).__init__(mark,
                equality_vector=(identifier,))
        self.identifier = identifier

    def __unicode__(self):
        return u'$%s' % self.identifier


class LiteralSyntax(Syntax):
    """
    Represents a literal expression.

    This is an abstract class with subclasses :class:`StringSyntax` and
    :class:`NumberSyntax`.

    `value` (a Unicode string)
        The value.
    """

    def __init__(self, value, mark):
        assert isinstance(value, unicode)
        super(LiteralSyntax, self).__init__(mark, equality_vector=(value,))
        self.value = value


class StringSyntax(LiteralSyntax):
    """
    Represents a string literal.
    """

    def __unicode__(self):
        # Quote and %-encode the value.
        value = u'\'%s\'' % self.value.replace(u'\'', u'\'\'')
        value = self.escape_regexp.sub(self.escape_replace, value)
        return value


class NumberSyntax(LiteralSyntax):
    """
    Represents a number literal.

    Attributes:

    `is_integer` (Boolean)
        Set if the number is in integer notation.

    `is_decimal` (Boolean)
        Set if the number is in decimal notation.

    `is_exponential` (Boolean)
        Set if the number is in exponential notation.
    """

    def __init__(self, value, mark):
        super(NumberSyntax, self).__init__(value, mark)

        # Determine the notation of the number.
        self.is_integer = False
        self.is_decimal = False
        self.is_exponential = False
        if u'e' in value or u'E' in value:
            self.is_exponential = True
        elif u'.' in value:
            self.is_decimal = True
        else:
            self.is_integer = True

    def __unicode__(self):
        # FIXME: may break when followed by a specifier (`.`) symbol.
        return self.value