Source

Kong / kong / parser.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
""":mod:`kong.parser` --- Tofu parser
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

"""
import collections
import numbers
import re
from .lexer import Token, SyntaxError
from .ast import (Expression, Identifier, Application, Attribute, Operator,
                  IdentifierLocalDefinition, IdentifierAssignment,
                  AttributeDefinition, ListLiteral, StringLiteral)


__all__ = 'parse_expression',


#: The :mod:`re` pattern that matches to string literal escape sequences.
STRING_LITERAL_ESCAPE_SEQUENCE_PATTERN = re.compile(
    r'\\(?P<literal>[^xuU])|\\x(?P<x>[0-9A-Fa-f]{2})|'
    r'\\u(?P<u>[0-9A-Fa-f]{4})|\\U(?P<U>[0-9A-Fa-f]{8})'
)

#: (:class:`dict`) The table of string literal escape sequences.
STRING_LITERAL_ESCAPE_SEQUENCE_TABLE = {
    'a': '\a', 'b': '\b', 't': '\t', 'n': '\n',
    'v': '\v', 'f': '\f', 'r': '\r'
}


class ParsedToken(collections.namedtuple('_ParsedToken', 'token expression')):
    """The namedtuple that contains parsed :attr:`token` and its result
    :attr:`expression`.

    :param token: parsed token
    :type token: :class:`~kong.lexer.Token`
    :param expression: parsing result
    :type expression: :class:`~kong.ast.Expression`

    .. attribute:: token

       (:class:`~kong.lexer.Token`) The parsed token.

    .. attribute:: expression

       (:class:`~kong.ast.Expression`) The parsing result.

    """

    def __new__(cls, token, expression):
        if isinstance(token, cls):
            token = token.token
        if not isinstance(token, Token):
            raise TypeError('token must be a kong.lexer.Token instance, not '
                            + repr(token))
        elif not isinstance(expression, Expression):
            raise TypeError('expression must be a kong.ast.Expression '
                            'instance, not ' + repr(expression))
        return super(ParsedToken, cls).__new__(cls, token, expression)

    @property
    def offset(self):
        """(:class:`numbers.Integral`) The :attr:`~kong.lexer.Token.offset`
        of :attr:`token`.

        """
        return self.token.offset

    @property
    def tag(self):
        """(:class:`basestring`) The :attr:`~kong.lexer.Token.tag` of
        :attr:`token`.

        """
        return self.token.tag

    @property
    def string(self):
        """(:class:`basestring`) The :attr:`~kong.lexer.Token.string` of
        :attr:`token`.

        """
        return self.token.string

    def isa(self, expression_type):
        """Predicate method that checks whether :attr:`expression` is an
        instance of ``expression_type``. It is equivalent to::

            isinstance(parsed_token.expression, expression_type)

        :param expression_type: a subtype of :class:`~kong.ast.Expression`,
                                or iterable of subtypes
        :type expression_type: :class:`type`, :class:`collections.Iterable`
        :returns: whether :attr:`expression` is an instance of
                  ``expression_type``
        :rtype: :class:`bool`

        """
        if isinstance(expression_type, collections.Iterable):
            return any(self.isa(t) for t in expression_type)
        if not isinstance(expression_type, type):
            raise TypeError('expected a type object, not ' +
                            repr(expression_type))
        elif not issubclass(expression_type, Expression):
            raise TypeError('expected a subtype of kong.ast.Expression, not '
                            + repr(expression_type))
        return isinstance(self.expression, expression_type)


def parse_expression(tokens):
    """Parses an expression.

    .. sourcecode:: pycon

       >>> from kong.lexer import tokenize
       >>> p = lambda s: parse_expression(tokenize(s))
       >>> p('f()')
       kong.ast.Application(kong.ast.Identifier(u'f'), [])
       >>> p('f(a, f2())')  # doctest: +NORMALIZE_WHITESPACE
       kong.ast.Application(kong.ast.Identifier(u'f'),
           [kong.ast.Identifier(u'a'),
            kong.ast.Application(kong.ast.Identifier(u'f2'), [])])
       >>> p('b <- 1 + (a <- 2) * 3')  # doctest: +NORMALIZE_WHITESPACE
       kong.ast.IdentifierLocalDefinition(lvalue=kong.ast.Identifier(u'b'),
        rvalue=kong.ast.Operator(operator=kong.ast.Identifier(u'*'),
         operands=[kong.ast.Operator(operator=kong.ast.Identifier(u'+'),
          operands=[kong.ast.StringLiteral(1),
           kong.ast.IdentifierLocalDefinition(lvalue=kong.ast.Identifier(u'a'),
            rvalue=kong.ast.StringLiteral(2))]),
          kong.ast.StringLiteral(3)]))
       >>> p('(1 + 2).*')  # doctest: +NORMALIZE_WHITESPACE
       kong.ast.Attribute(kong.ast.Operator(operator=kong.ast.Identifier(u'+'),
         operands=[kong.ast.StringLiteral(1), kong.ast.StringLiteral(2)]),
        attribute=kong.ast.Identifier(u'*'))
       >>> p('[]')
       kong.ast.ListLiteral([])
       >>> p('[a, 1]')  # doctest: +NORMALIZE_WHITESPACE
       kong.ast.ListLiteral([kong.ast.Identifier(u'a'),
                             kong.ast.StringLiteral(1)])
       >>> p('[1, [2, 3], +]')  # doctest: +NORMALIZE_WHITESPACE
       kong.ast.ListLiteral([kong.ast.StringLiteral(1),
           kong.ast.ListLiteral([kong.ast.StringLiteral(2),
               kong.ast.StringLiteral(3)]),
           kong.ast.Identifier(u'+')])

    :param tokens: tokens to parse
    :type tokens: :class:`collections.Iterable`
    :returns: parsed expression
    :rtype: :class:`kong.ast.Expression`
    :raises: :exc:`kong.lexer.SyntaxError` for invalid syntax

    """
    buffer = []
    def tag(token, *tags):
        return isinstance(token, Token) and token.tag in tags
    def rfind_token(tag, string=None):
        if buffer:
            i = len(buffer) - 1
            while i >= 0:
                t = buffer[i]
                if (isinstance(t, Token) and t.tag == tag and
                    (string is None or t.string == string)):
                    return i
                i -= 1
        raise LookupError()
    def commalist(i):
        list_elements = []
        element_buffer = []
        for list_el_token in buffer[i + 1:] + [None]:
            if (list_el_token is None or
                list_el_token.tag == 'comma'):
                if element_buffer:
                    list_element = associate(element_buffer)
                    if len(list_element) > 1:
                        raise SyntaxError(
                            list_element[1].offset,
                            'unexpected token ' + repr(list_element[1].string)
                        )
                    list_elements.append(
                        list_element[0].expression
                    )
                    element_buffer = []
                elif list_el_token is not None:
                    raise SyntaxError(list_el_token.offset,
                                      'empty argument or element')
            else:
                element_buffer.append(list_el_token)
        return list_elements
    for token in tokens:
        if not isinstance(token, Token):
            raise TypeError('expected iterable of kong.lexer.Token, not of ' +
                            repr(token))
        if tag(token, 'identifier'):
            ident = Identifier(token.string)
            buffer.append(ParsedToken(token, ident))
        elif tag(token, 'string', 'number'):
            string = parse_string_literal(token)
            buffer.append(ParsedToken(token, string))
        elif tag(token, 'parenthesis'):
            if token.string == u'(':
                buffer.append(token)
            else:
                try:
                    i = rfind_token('parenthesis', u'(')
                except LookupError:
                    raise SyntaxError(token.offset,
                                      'unexpected closing parenthesis ")"')
                else:
                    if (i > 0 and isinstance(buffer[i - 1], ParsedToken) and
                        (i < 2 or isinstance(buffer[i - 2], Token))):
                        args = commalist(i)
                        node = Application(buffer[i - 1].expression, args)
                        parsed = ParsedToken(buffer[i - 1].token, node)
                        buffer[i - 1:] = [parsed]
                    else:
                        buffer[i:] = associate(buffer[i + 1:])
        elif tag(token, 'square_bracket'):
            if token.string == u'[':
                buffer.append(token)
            else:
                try:
                    i = rfind_token('square_bracket', u'[')
                except LookupError:
                    raise SyntaxError(token.offset,
                                      'unexpected closing square bracket "]"')
                else:
                    node = ListLiteral(commalist(i))
                    buffer[i:] = [ParsedToken(buffer[i], node)]
        elif tag(token, 'period'):
            if not isinstance(buffer[-1], ParsedToken):
                raise SyntaxError(token.offset, 'unexpected period "."')
            buffer.append(token)
        elif tag(token, 'arrow', 'comma'):
            buffer.append(token)
    result = associate(buffer)
    if not result:
        raise SyntaxError(0, 'nothing to parse')
    elif len(result) > 1:
        token = result[1]
        raise SyntaxError(token.offset,
                          'unexpected token {0!r}'.format(token.string))
    return result[0][1]


def parse_string_literal(token):
    """Parses a string literal token.

    :param token: a string token
    :type token: :class:`kong.lexer.Token`
    :returns: parsed string literal
    :rtype: :class:`kong.ast.StringLiteral`

    """
    if not isinstance(token, Token):
        raise TypeError('expected a kong.lexer.Token, not ' + repr(token))
    elif token.tag == 'number':
        return StringLiteral(unicode(token.string))
    elif token.tag != 'string':
        raise ValueError('expected string token, not ' + token.tag)
    def repl(match):
        c = match.group('literal')
        if c:
            try:
                return STRING_LITERAL_ESCAPE_SEQUENCE_TABLE[c]
            except KeyError:
                return c
        u = match.group('x') or match.group('u') or match.group('U')
        return unichr(int(u, 16))
    s = STRING_LITERAL_ESCAPE_SEQUENCE_PATTERN.sub(repl, token.string[1:-1])
    return StringLiteral(unicode(s))


def associate(buffer):
    """Associates associative expressions from the given ``buffer``,
    a sequence of :class:`ParsedToken` and :class:`~kong.lexer.Token` objects.

    :param buffer: a sequence of :class:`ParsedToken` and
                   :class:`~kong.lexer.Token` objects
    :type buffer: :class:`collections.Sequence`
    :returns: associated result
    :rtype: :class:`collections.Sequence`

    """
    buffer = associate_attributes(buffer)
    buffer = associate_operator(buffer)
    buffer = associate_definitions(buffer)
    return buffer


def associate_attributes(buffer):
    """Associates :class:`~kong.ast.Attribute` expressions from the given
    ``buffer``, a sequence of :class:`ParsedToken` and
    :class:`~kong.lexer.Token` objects.

    :param buffer: a sequence of :class:`ParsedToken` and
                   :class:`~kong.lexer.Token` objects
    :type buffer: :class:`collections.Sequence`
    :returns: associated result
    :rtype: :class:`collections.Sequence`

    """
    if not isinstance(buffer, collections.Sequence):
        raise TypeError('buffer must be collections.Sequence, not ' +
                        repr(buffer))
    result = []
    length = len(buffer)
    skipto = -1
    for i, token in enumerate(buffer):
        if i <= skipto:
            continue
        elif isinstance(token, Token) and token.tag == 'period':
            if i < 1 or i >= length - 1:
                raise SyntaxError(token.offset, 'unexpected period "."')
            prev = result[-1]
            next = buffer[i + 1]
            if not (isinstance(prev, ParsedToken) and
                    isinstance(next, ParsedToken) and
                    next.isa(Identifier)):
                raise SyntaxError(token.offset, 'unexpected period "."')
            del result[-1]
            node = Attribute(prev.expression, attribute=next.expression)
            parsed = ParsedToken(token, node)
            result.append(parsed)
            skipto = i + 1
        else:
            result.append(token)
    return result


def associate_operator(buffer):
    """Associates :class:`~kong.ast.Operator` expressions from the given
    ``buffer``, a sequence of :class:`ParsedToken` and
    :class:`~kong.lexer.Token` objects.

    :param buffer: a sequence of :class:`ParsedToken` and
                   :class:`~kong.lexer.Token` objects
    :type buffer: :class:`collections.Sequence`
    :returns: associated result
    :rtype: :class:`collections.Sequence`

    """
    if not isinstance(buffer, collections.Sequence):
        raise TypeError('buffer must be collections.Sequence, not ' +
                        repr(buffer))
    result = []
    length = len(buffer)
    skipto = -1
    for i, token in enumerate(buffer):
        if i <= skipto:
            continue
        elif (isinstance(token, ParsedToken) and token.isa(Identifier) and
              0 < i < length - 1):
            prev = result[-1]
            next = buffer[i + 1]
            if not (isinstance(prev, ParsedToken) and
                    isinstance(next, ParsedToken)):
                raise SyntaxError(token.offset,
                                  'unexpected identifier ' +
                                  repr(token.string))
            operator = Operator(operator=token.expression,
                                operands=(prev.expression, next.expression))
            result[-1] = ParsedToken(token, operator)
            skipto = i + 1
        else:
            result.append(token)
    return result


def associate_definitions(buffer):
    """Associates :class:`~kong.ast.Definition` expressions from the given
    ``buffer``, a sequence of :class:`ParsedToken` and
    :class:`~kong.lexer.Token` objects.

    :param buffer: a sequence of :class:`ParsedToken` and
                   :class:`~kong.lexer.Token` objects
    :type buffer: :class:`collections.Sequence`
    :returns: associated result
    :rtype: :class:`collections.Sequence`

    """
    if not isinstance(buffer, collections.Sequence):
        raise TypeError('buffer must be collections.Sequence, not ' +
                        repr(buffer))
    result = []
    length = len(buffer)
    skipto = -1
    for i, token in enumerate(buffer):
        if i <= skipto:
            continue
        elif isinstance(token, Token) and token.tag == 'arrow':
            if i < 1 or i >= length - 1:
                raise SyntaxError(token.offset, 'unexpected arrow "<-"')
            prev = result[-1]
            next = buffer[i + 1]
            if not (isinstance(prev, ParsedToken) and
                    prev.isa((Identifier, Attribute)) and
                    isinstance(next, ParsedToken)):
                raise SyntaxError(token.offset, 'unexpected arrow "<-"')
            elif prev.isa(Attribute):
                devnodecls = AttributeDefinition
                skip = 1
            elif prev.isa(Identifier):
                if (i > 1 and isinstance(result[-2], Token) and
                    result[-2].tag == 'period'):
                    defnodecls = IdentifierAssignment
                    skip = 2
                else:
                    defnodecls = IdentifierLocalDefinition
                    skip = 1
                del result[-skip:]
                skipto = i + skip
            node = defnodecls(lvalue=prev.expression, rvalue=next.expression)
            parsed = ParsedToken(token, node)
            result.append(parsed)
        else:
            result.append(token)
    return result