Parsing.py 132 KB
Newer Older
1
# cython: auto_cpdef=True, infer_types=True, language_level=3, py2_import=True
2
#
3
#   Parser
4 5
#

6 7
from __future__ import absolute_import

8 9
# This should be done automatically
import cython
10
cython.declare(Nodes=object, ExprNodes=object, EncodedString=object,
11
               bytes_literal=object, StringEncoding=object,
12
               FileSourceDescriptor=object, lookup_unicodechar=object, unicode_category=object,
13
               Future=object, Options=object, error=object, warning=object,
14 15
               Builtin=object, ModuleNode=object, Utils=object, _unicode=object, _bytes=object,
               re=object, sys=object, _parse_escape_sequences=object, _parse_escape_sequences_raw=object,
16 17
               partial=object, reduce=object, _IS_PY3=cython.bint, _IS_2BYTE_UNICODE=cython.bint,
               _CDEF_MODIFIERS=tuple)
18

19
from io import StringIO
20
import re
21
import sys
22
from unicodedata import lookup as lookup_unicodechar, category as unicode_category
23
from functools import partial, reduce
24

25
from .Scanning import PyrexScanner, FileSourceDescriptor, StringSourceDescriptor
26 27 28 29
from . import Nodes
from . import ExprNodes
from . import Builtin
from . import StringEncoding
30
from .StringEncoding import EncodedString, bytes_literal, _unicode, _bytes
31 32 33 34 35 36
from .ModuleNode import ModuleNode
from .Errors import error, warning
from .. import Utils
from . import Future
from . import Options

37
_IS_PY3 = sys.version_info[0] >= 3
38
_IS_2BYTE_UNICODE = sys.maxunicode == 0xffff
39
_CDEF_MODIFIERS = ('inline', 'nogil', 'api')
40

41

42 43 44 45 46 47 48 49 50
class Ctx(object):
    #  Parsing context
    level = 'other'
    visibility = 'private'
    cdef_flag = 0
    typedef_flag = 0
    api = 0
    overridable = 0
    nogil = 0
51
    namespace = None
Danilo Freitas's avatar
Danilo Freitas committed
52
    templates = None
53
    allow_struct_enum_decorator = False
54
    modifiers = []
55 56 57 58 59 60 61 62 63 64 65

    def __init__(self, **kwds):
        self.__dict__.update(kwds)

    def __call__(self, **kwds):
        ctx = Ctx()
        d = ctx.__dict__
        d.update(self.__dict__)
        d.update(kwds)
        return ctx

66

67
def p_ident(s, message="Expected an identifier"):
68
    if s.sy == 'IDENT':
69
        name = s.context.intern_ustring(s.systring)
70 71 72 73 74 75 76 77
        s.next()
        return name
    else:
        s.error(message)

def p_ident_list(s):
    names = []
    while s.sy == 'IDENT':
78
        names.append(s.context.intern_ustring(s.systring))
79
        s.next()
Stefan Behnel's avatar
Stefan Behnel committed
80
        if s.sy != ',':
81 82 83 84 85 86 87 88 89 90
            break
        s.next()
    return names

#------------------------------------------
#
#   Expressions
#
#------------------------------------------

91 92 93 94 95 96
def p_binop_operator(s):
    pos = s.position()
    op = s.sy
    s.next()
    return op, pos

97 98 99
def p_binop_expr(s, ops, p_sub_expr):
    n1 = p_sub_expr(s)
    while s.sy in ops:
100
        op, pos = p_binop_operator(s)
101 102
        n2 = p_sub_expr(s)
        n1 = ExprNodes.binop_node(pos, op, n1, n2)
103 104 105 106
        if op == '/':
            if Future.division in s.context.future_directives:
                n1.truedivision = True
            else:
107
                n1.truedivision = None  # unknown
108 109
    return n1

Stefan Behnel's avatar
Stefan Behnel committed
110 111 112 113 114 115 116 117 118 119
#lambdef: 'lambda' [varargslist] ':' test

def p_lambdef(s, allow_conditional=True):
    # s.sy == 'lambda'
    pos = s.position()
    s.next()
    if s.sy == ':':
        args = []
        star_arg = starstar_arg = None
    else:
120 121
        args, star_arg, starstar_arg = p_varargslist(
            s, terminator=':', annotated=False)
Stefan Behnel's avatar
Stefan Behnel committed
122 123
    s.expect(':')
    if allow_conditional:
124
        expr = p_test(s)
Stefan Behnel's avatar
Stefan Behnel committed
125 126 127 128 129 130 131 132 133 134 135 136
    else:
        expr = p_test_nocond(s)
    return ExprNodes.LambdaNode(
        pos, args = args,
        star_arg = star_arg, starstar_arg = starstar_arg,
        result_expr = expr)

#lambdef_nocond: 'lambda' [varargslist] ':' test_nocond

def p_lambdef_nocond(s):
    return p_lambdef(s, allow_conditional=False)

137
#test: or_test ['if' or_test 'else' test] | lambdef
138

139
def p_test(s):
140 141
    if s.sy == 'lambda':
        return p_lambdef(s)
142 143 144 145 146
    pos = s.position()
    expr = p_or_test(s)
    if s.sy == 'if':
        s.next()
        test = p_or_test(s)
Stefan Behnel's avatar
Stefan Behnel committed
147 148 149
        s.expect('else')
        other = p_test(s)
        return ExprNodes.CondExprNode(pos, test=test, true_val=expr, false_val=other)
150 151 152
    else:
        return expr

Stefan Behnel's avatar
Stefan Behnel committed
153 154 155 156 157 158 159
#test_nocond: or_test | lambdef_nocond

def p_test_nocond(s):
    if s.sy == 'lambda':
        return p_lambdef_nocond(s)
    else:
        return p_or_test(s)
160 161 162 163

#or_test: and_test ('or' and_test)*

def p_or_test(s):
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
    return p_rassoc_binop_expr(s, ('or',), p_and_test)

def p_rassoc_binop_expr(s, ops, p_subexpr):
    n1 = p_subexpr(s)
    if s.sy in ops:
        pos = s.position()
        op = s.sy
        s.next()
        n2 = p_rassoc_binop_expr(s, ops, p_subexpr)
        n1 = ExprNodes.binop_node(pos, op, n1, n2)
    return n1

#and_test: not_test ('and' not_test)*

def p_and_test(s):
    #return p_binop_expr(s, ('and',), p_not_test)
    return p_rassoc_binop_expr(s, ('and',), p_not_test)

#not_test: 'not' not_test | comparison

def p_not_test(s):
    if s.sy == 'not':
        pos = s.position()
        s.next()
        return ExprNodes.NotNode(pos, operand = p_not_test(s))
    else:
        return p_comparison(s)

#comparison: expr (comp_op expr)*
#comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'

def p_comparison(s):
196
    n1 = p_starred_expr(s)
197 198 199
    if s.sy in comparison_ops:
        pos = s.position()
        op = p_cmp_op(s)
200
        n2 = p_starred_expr(s)
201
        n1 = ExprNodes.PrimaryCmpNode(pos,
202 203 204 205 206
            operator = op, operand1 = n1, operand2 = n2)
        if s.sy in comparison_ops:
            n1.cascade = p_cascaded_cmp(s)
    return n1

207 208 209 210 211 212
def p_test_or_starred_expr(s):
    if s.sy == '*':
        return p_starred_expr(s)
    else:
        return p_test(s)

213
def p_starred_expr(s):
214
    pos = s.position()
215 216 217 218 219 220
    if s.sy == '*':
        starred = True
        s.next()
    else:
        starred = False
    expr = p_bit_expr(s)
221
    if starred:
222
        expr = ExprNodes.StarredUnpackingNode(pos, expr)
223 224
    return expr

225 226 227
def p_cascaded_cmp(s):
    pos = s.position()
    op = p_cmp_op(s)
228
    n2 = p_starred_expr(s)
229
    result = ExprNodes.CascadedCmpNode(pos,
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
        operator = op, operand2 = n2)
    if s.sy in comparison_ops:
        result.cascade = p_cascaded_cmp(s)
    return result

def p_cmp_op(s):
    if s.sy == 'not':
        s.next()
        s.expect('in')
        op = 'not_in'
    elif s.sy == 'is':
        s.next()
        if s.sy == 'not':
            s.next()
            op = 'is_not'
        else:
            op = 'is'
    else:
        op = s.sy
        s.next()
    if op == '<>':
        op = '!='
    return op
253

254
comparison_ops = cython.declare(set, set([
255
    '<', '>', '==', '>=', '<=', '<>', '!=',
256
    'in', 'is', 'not'
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

#expr: xor_expr ('|' xor_expr)*

def p_bit_expr(s):
    return p_binop_expr(s, ('|',), p_xor_expr)

#xor_expr: and_expr ('^' and_expr)*

def p_xor_expr(s):
    return p_binop_expr(s, ('^',), p_and_expr)

#and_expr: shift_expr ('&' shift_expr)*

def p_and_expr(s):
    return p_binop_expr(s, ('&',), p_shift_expr)

#shift_expr: arith_expr (('<<'|'>>') arith_expr)*

def p_shift_expr(s):
    return p_binop_expr(s, ('<<', '>>'), p_arith_expr)

#arith_expr: term (('+'|'-') term)*

def p_arith_expr(s):
    return p_binop_expr(s, ('+', '-'), p_term)

284
#term: factor (('*'|'@'|'/'|'%'|'//') factor)*
285 286

def p_term(s):
287
    return p_binop_expr(s, ('*', '@', '/', '%', '//'), p_factor)
288 289 290 291

#factor: ('+'|'-'|'~'|'&'|typecast|sizeof) factor | power

def p_factor(s):
292 293 294 295
    # little indirection for C-ification purposes
    return _p_factor(s)

def _p_factor(s):
296 297 298 299 300 301
    sy = s.sy
    if sy in ('+', '-', '~'):
        op = s.sy
        pos = s.position()
        s.next()
        return ExprNodes.unop_node(pos, op, p_factor(s))
302 303 304 305 306 307 308 309 310 311
    elif not s.in_python_file:
        if sy == '&':
            pos = s.position()
            s.next()
            arg = p_factor(s)
            return ExprNodes.AmpersandNode(pos, operand = arg)
        elif sy == "<":
            return p_typecast(s)
        elif sy == 'IDENT' and s.systring == "sizeof":
            return p_sizeof(s)
312 313
        elif sy == 'IDENT' and s.systring == "consume":
            return p_consume(s)
314
    return p_power(s)
315 316 317 318 319 320

def p_typecast(s):
    # s.sy == "<"
    pos = s.position()
    s.next()
    base_type = p_c_base_type(s)
321
    is_memslice = isinstance(base_type, Nodes.MemoryViewSliceTypeNode)
Robert Bradshaw's avatar
Robert Bradshaw committed
322
    is_template = isinstance(base_type, Nodes.TemplatedTypeNode)
323
    is_const_volatile = isinstance(base_type, Nodes.CConstOrVolatileTypeNode)
324 325
    is_qualified = isinstance(base_type, Nodes.QualifiedCypclassNode)
    if not is_memslice and not is_template and not is_const_volatile and not is_qualified and base_type.name is None:
326
        s.error("Unknown type")
327
    declarator = p_c_declarator(s, empty = 1)
328 329 330 331 332
    if s.sy == '?':
        s.next()
        typecheck = 1
    else:
        typecheck = 0
333 334
    s.expect(">")
    operand = p_factor(s)
335
    if is_memslice:
Stefan Behnel's avatar
Stefan Behnel committed
336
        return ExprNodes.CythonArrayNode(pos, base_type_node=base_type, operand=operand)
337

338 339
    return ExprNodes.TypecastNode(pos,
        base_type = base_type,
340
        declarator = declarator,
341 342
        operand = operand,
        typecheck = typecheck)
343 344 345 346 347 348

def p_sizeof(s):
    # s.sy == ident "sizeof"
    pos = s.position()
    s.next()
    s.expect('(')
349
    # Here we decide if we are looking at an expression or type
350 351
    # If it is actually a type, but parsable as an expression,
    # we treat it as an expression here.
352
    if looking_at_expr(s):
353
        operand = p_test(s)
354 355
        node = ExprNodes.SizeofVarNode(pos, operand = operand)
    else:
356 357
        base_type = p_c_base_type(s)
        declarator = p_c_declarator(s, empty = 1)
358
        node = ExprNodes.SizeofTypeNode(pos,
359 360 361 362
            base_type = base_type, declarator = declarator)
    s.expect(')')
    return node

363 364 365 366 367 368 369
def p_consume(s):
    # s.sy == ident "consume"
    pos = s.position()
    s.next()
    operand = p_factor(s)
    return ExprNodes.ConsumeNode(pos, operand = operand)

370

371 372 373 374
def p_yield_expression(s):
    # s.sy == "yield"
    pos = s.position()
    s.next()
375 376 377 378
    is_yield_from = False
    if s.sy == 'from':
        is_yield_from = True
        s.next()
379
    if s.sy != ')' and s.sy not in statement_terminators:
380 381
        # "yield from" does not support implicit tuples, but "yield" does ("yield 1,2")
        arg = p_test(s) if is_yield_from else p_testlist(s)
382
    else:
383
        if is_yield_from:
384 385
            s.error("'yield from' requires a source argument",
                    pos=pos, fatal=False)
386
        arg = None
387 388 389 390
    if is_yield_from:
        return ExprNodes.YieldFromExprNode(pos, arg=arg)
    else:
        return ExprNodes.YieldExprNode(pos, arg=arg)
391

392

393 394 395 396
def p_yield_statement(s):
    # s.sy == "yield"
    yield_expr = p_yield_expression(s)
    return Nodes.ExprStatNode(yield_expr.pos, expr=yield_expr)
397

398 399 400 401 402 403 404 405 406 407 408 409

def p_async_statement(s, ctx, decorators):
    # s.sy >> 'async' ...
    if s.sy == 'def':
        # 'async def' statements aren't allowed in pxd files
        if 'pxd' in ctx.level:
            s.error('def statement not allowed here')
        s.level = ctx.level
        return p_def_statement(s, decorators, is_async_def=True)
    elif decorators:
        s.error("Decorators can only be followed by functions or classes")
    elif s.sy == 'for':
410
        return p_for_statement(s, is_async=True)
411
    elif s.sy == 'with':
412 413
        s.next()
        return p_with_items(s, is_async=True)
414 415 416 417 418 419
    else:
        s.error("expected one of 'def', 'for', 'with' after 'async'")


#power: atom_expr ('**' factor)*
#atom_expr: ['await'] atom trailer*
420 421

def p_power(s):
422
    if s.systring == 'new' and s.peek()[0] == 'IDENT':
423
        return p_new_expr(s)
424 425 426 427
    await_pos = None
    if s.sy == 'await':
        await_pos = s.position()
        s.next()
428 429 430
    n1 = p_atom(s)
    while s.sy in ('(', '[', '.'):
        n1 = p_trailer(s, n1)
431 432
    if await_pos:
        n1 = ExprNodes.AwaitExprNode(await_pos, arg=n1)
433 434 435 436 437 438 439
    if s.sy == '**':
        pos = s.position()
        s.next()
        n2 = p_factor(s)
        n1 = ExprNodes.binop_node(pos, '**', n1, n2)
    return n1

440

441
def p_new_expr(s):
Danilo Freitas's avatar
Danilo Freitas committed
442
    # s.systring == 'new'.
443 444
    pos = s.position()
    s.next()
445 446
    cppclass = p_c_base_type(s)
    return p_call(s, ExprNodes.NewExprNode(pos, cppclass = cppclass))
447

448 449 450 451 452 453 454 455
#trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME

def p_trailer(s, node1):
    pos = s.position()
    if s.sy == '(':
        return p_call(s, node1)
    elif s.sy == '[':
        return p_index(s, node1)
456
    else:  # s.sy == '.'
457
        s.next()
458
        name = p_ident(s)
459
        return ExprNodes.AttributeNode(pos,
460
            obj=node1, attribute=name)
461

462

463 464 465
# arglist:  argument (',' argument)* [',']
# argument: [test '='] test       # Really [keyword '='] test

466 467 468 469 470 471 472
# since PEP 448:
# argument: ( test [comp_for] |
#             test '=' test |
#             '**' expr |
#             star_expr )

def p_call_parse_args(s, allow_genexp=True):
473 474 475 476 477
    # s.sy == '('
    pos = s.position()
    s.next()
    positional_args = []
    keyword_args = []
478 479 480
    starstar_seen = False
    last_was_tuple_unpack = False
    while s.sy != ')':
481
        if s.sy == '*':
482 483 484 485 486 487
            if starstar_seen:
                s.error("Non-keyword arg following keyword arg", pos=s.position())
            s.next()
            positional_args.append(p_test(s))
            last_was_tuple_unpack = True
        elif s.sy == '**':
488
            s.next()
489 490
            keyword_args.append(p_test(s))
            starstar_seen = True
491
        else:
492
            arg = p_test(s)
493 494 495 496
            if s.sy == '=':
                s.next()
                if not arg.is_name:
                    s.error("Expected an identifier before '='",
497
                            pos=arg.pos)
498
                encoded_name = s.context.intern_ustring(arg.name)
499 500
                keyword = ExprNodes.IdentifierStringNode(
                    arg.pos, value=encoded_name)
501
                arg = p_test(s)
502 503 504
                keyword_args.append((keyword, arg))
            else:
                if keyword_args:
505 506 507 508 509 510
                    s.error("Non-keyword arg following keyword arg", pos=arg.pos)
                if positional_args and not last_was_tuple_unpack:
                    positional_args[-1].append(arg)
                else:
                    positional_args.append([arg])
                last_was_tuple_unpack = False
Stefan Behnel's avatar
Stefan Behnel committed
511
        if s.sy != ',':
512 513
            break
        s.next()
514

515
    if s.sy in ('for', 'async'):
516 517
        if not keyword_args and not last_was_tuple_unpack:
            if len(positional_args) == 1 and len(positional_args[0]) == 1:
518
                positional_args = [[p_genexp(s, positional_args[0][0])]]
519
    s.expect(')')
520
    return positional_args or [[]], keyword_args
521

522 523

def p_call_build_packed_args(pos, positional_args, keyword_args):
524
    keyword_dict = None
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

    subtuples = [
        ExprNodes.TupleNode(pos, args=arg) if isinstance(arg, list) else ExprNodes.AsTupleNode(pos, arg=arg)
        for arg in positional_args
    ]
    # TODO: implement a faster way to join tuples than creating each one and adding them
    arg_tuple = reduce(partial(ExprNodes.binop_node, pos, '+'), subtuples)

    if keyword_args:
        kwargs = []
        dict_items = []
        for item in keyword_args:
            if isinstance(item, tuple):
                key, value = item
                dict_items.append(ExprNodes.DictItemNode(pos=key.pos, key=key, value=value))
            elif item.is_dict_literal:
                # unpack "**{a:b}" directly
                dict_items.extend(item.key_value_pairs)
            else:
                if dict_items:
                    kwargs.append(ExprNodes.DictNode(
                        dict_items[0].pos, key_value_pairs=dict_items, reject_duplicates=True))
                    dict_items = []
                kwargs.append(item)

        if dict_items:
            kwargs.append(ExprNodes.DictNode(
                dict_items[0].pos, key_value_pairs=dict_items, reject_duplicates=True))

        if kwargs:
            if len(kwargs) == 1 and kwargs[0].is_dict_literal:
                # only simple keyword arguments found -> one dict
                keyword_dict = kwargs[0]
            else:
                # at least one **kwargs
560
                keyword_dict = ExprNodes.MergedDictNode(pos, keyword_args=kwargs)
561

562 563
    return arg_tuple, keyword_dict

564

565 566 567
def p_call(s, function):
    # s.sy == '('
    pos = s.position()
568
    positional_args, keyword_args = p_call_parse_args(s)
569

570 571
    if not keyword_args and len(positional_args) == 1 and isinstance(positional_args[0], list):
        return ExprNodes.SimpleCallNode(pos, function=function, args=positional_args[0])
572
    else:
573 574 575 576
        arg_tuple, keyword_dict = p_call_build_packed_args(pos, positional_args, keyword_args)
        return ExprNodes.GeneralCallNode(
            pos, function=function, positional_args=arg_tuple, keyword_args=keyword_dict)

577 578 579 580 581 582 583 584 585

#lambdef: 'lambda' [varargslist] ':' test

#subscriptlist: subscript (',' subscript)* [',']

def p_index(s, base):
    # s.sy == '['
    pos = s.position()
    s.next()
586 587
    subscripts, is_single_value = p_subscript_list(s)
    if is_single_value and len(subscripts[0]) == 2:
588
        start, stop = subscripts[0]
589
        result = ExprNodes.SliceIndexNode(pos,
590 591 592
            base = base, start = start, stop = stop)
    else:
        indexes = make_slice_nodes(pos, subscripts)
593
        if is_single_value:
594 595 596 597 598 599 600 601 602
            index = indexes[0]
        else:
            index = ExprNodes.TupleNode(pos, args = indexes)
        result = ExprNodes.IndexNode(pos,
            base = base, index = index)
    s.expect(']')
    return result

def p_subscript_list(s):
603
    is_single_value = True
604 605
    items = [p_subscript(s)]
    while s.sy == ',':
606
        is_single_value = False
607 608 609 610
        s.next()
        if s.sy == ']':
            break
        items.append(p_subscript(s))
611
    return items, is_single_value
612 613 614 615 616 617 618 619

#subscript: '.' '.' '.' | test | [test] ':' [test] [':' [test]]

def p_subscript(s):
    # Parse a subscript and return a list of
    # 1, 2 or 3 ExprNodes, depending on how
    # many slice elements were encountered.
    pos = s.position()
620 621 622 623 624 625 626 627 628 629
    start = p_slice_element(s, (':',))
    if s.sy != ':':
        return [start]
    s.next()
    stop = p_slice_element(s, (':', ',', ']'))
    if s.sy != ':':
        return [start, stop]
    s.next()
    step = p_slice_element(s, (':', ',', ']'))
    return [start, stop, step]
630 631 632 633 634

def p_slice_element(s, follow_set):
    # Simple expression which may be missing iff
    # it is followed by something in follow_set.
    if s.sy not in follow_set:
635
        return p_test(s)
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
    else:
        return None

def expect_ellipsis(s):
    s.expect('.')
    s.expect('.')
    s.expect('.')

def make_slice_nodes(pos, subscripts):
    # Convert a list of subscripts as returned
    # by p_subscript_list into a list of ExprNodes,
    # creating SliceNodes for elements with 2 or
    # more components.
    result = []
    for subscript in subscripts:
        if len(subscript) == 1:
            result.append(subscript[0])
        else:
            result.append(make_slice_node(pos, *subscript))
    return result

def make_slice_node(pos, start, stop = None, step = None):
    if not start:
        start = ExprNodes.NoneNode(pos)
    if not stop:
        stop = ExprNodes.NoneNode(pos)
    if not step:
        step = ExprNodes.NoneNode(pos)
    return ExprNodes.SliceNode(pos,
        start = start, stop = stop, step = step)

667
#atom: '(' [yield_expr|testlist_comp] ')' | '[' [listmaker] ']' | '{' [dict_or_set_maker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+
668 669 670 671 672 673 674 675

def p_atom(s):
    pos = s.position()
    sy = s.sy
    if sy == '(':
        s.next()
        if s.sy == ')':
            result = ExprNodes.TupleNode(pos, args = [])
676 677
        elif s.sy == 'yield':
            result = p_yield_expression(s)
678
        else:
679
            result = p_testlist_comp(s)
680 681 682 683 684
        s.expect(')')
        return result
    elif sy == '[':
        return p_list_maker(s)
    elif sy == '{':
685
        return p_dict_or_set_maker(s)
686 687
    elif sy == '`':
        return p_backquote_expr(s)
688 689 690
    elif sy == '.':
        expect_ellipsis(s)
        return ExprNodes.EllipsisNode(pos)
691
    elif sy == 'INT':
692
        return p_int_literal(s)
693 694 695 696 697 698 699 700
    elif sy == 'FLOAT':
        value = s.systring
        s.next()
        return ExprNodes.FloatNode(pos, value = value)
    elif sy == 'IMAG':
        value = s.systring[:-1]
        s.next()
        return ExprNodes.ImagNode(pos, value = value)
701
    elif sy == 'BEGIN_STRING':
702
        kind, bytes_value, unicode_value = p_cat_string_literal(s)
703
        if kind == 'c':
704
            return ExprNodes.CharNode(pos, value = bytes_value)
705
        elif kind == 'u':
706
            return ExprNodes.UnicodeNode(pos, value = unicode_value, bytes_value = bytes_value)
707
        elif kind == 'b':
708
            return ExprNodes.BytesNode(pos, value = bytes_value)
709 710 711
        elif kind == 'f':
            return ExprNodes.JoinedStrNode(pos, values = unicode_value)
        elif kind == '':
712
            return ExprNodes.StringNode(pos, value = bytes_value, unicode_value = unicode_value)
713 714
        else:
            s.error("invalid string kind '%s'" % kind)
715
    elif sy == 'IDENT':
716
        name = s.systring
717
        if name == "None":
718
            result = ExprNodes.NoneNode(pos)
719
        elif name == "True":
720
            result = ExprNodes.BoolNode(pos, value=True)
721
        elif name == "False":
722
            result = ExprNodes.BoolNode(pos, value=False)
723
        elif name == "NULL" and not s.in_python_file:
724
            result = ExprNodes.NullNode(pos)
725
        else:
726 727 728
            result = p_name(s, name)
        s.next()
        return result
729 730 731
    else:
        s.error("Expected an identifier or literal")

732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
def p_int_literal(s):
    pos = s.position()
    value = s.systring
    s.next()
    unsigned = ""
    longness = ""
    while value[-1] in u"UuLl":
        if value[-1] in u"Ll":
            longness += "L"
        else:
            unsigned += "U"
        value = value[:-1]
    # '3L' is ambiguous in Py2 but not in Py3.  '3U' and '3LL' are
    # illegal in Py2 Python files.  All suffixes are illegal in Py3
    # Python files.
    is_c_literal = None
    if unsigned:
        is_c_literal = True
    elif longness:
        if longness == 'LL' or s.context.language_level >= 3:
            is_c_literal = True
    if s.in_python_file:
        if is_c_literal:
            error(pos, "illegal integer literal syntax in Python source file")
        is_c_literal = False
    return ExprNodes.IntNode(pos,
                             is_c_literal = is_c_literal,
                             value = value,
                             unsigned = unsigned,
                             longness = longness)

763

764 765
def p_name(s, name):
    pos = s.position()
766 767
    if not s.compile_time_expr and name in s.compile_time_env:
        value = s.compile_time_env.lookup_here(name)
768 769 770 771 772 773 774 775
        node = wrap_compile_time_constant(pos, value)
        if node is not None:
            return node
    return ExprNodes.NameNode(pos, name=name)


def wrap_compile_time_constant(pos, value):
    rep = repr(value)
776 777
    if value is None:
        return ExprNodes.NoneNode(pos)
778 779
    elif value is Ellipsis:
        return ExprNodes.EllipsisNode(pos)
780
    elif isinstance(value, bool):
781 782
        return ExprNodes.BoolNode(pos, value=value)
    elif isinstance(value, int):
783
        return ExprNodes.IntNode(pos, value=rep, constant_result=value)
784
    elif isinstance(value, float):
785
        return ExprNodes.FloatNode(pos, value=rep, constant_result=value)
786 787 788 789 790 791 792 793 794
    elif isinstance(value, complex):
        node = ExprNodes.ImagNode(pos, value=repr(value.imag), constant_result=complex(0.0, value.imag))
        if value.real:
            # FIXME: should we care about -0.0 ?
            # probably not worth using the '-' operator for negative imag values
            node = ExprNodes.binop_node(
                pos, '+', ExprNodes.FloatNode(pos, value=repr(value.real), constant_result=value.real), node,
                constant_result=value)
        return node
795
    elif isinstance(value, _unicode):
796
        return ExprNodes.UnicodeNode(pos, value=EncodedString(value))
797
    elif isinstance(value, _bytes):
798 799
        bvalue = bytes_literal(value, 'ascii')  # actually: unknown encoding, but BytesLiteral requires one
        return ExprNodes.BytesNode(pos, value=bvalue, constant_result=value)
800 801 802 803 804
    elif isinstance(value, tuple):
        args = [wrap_compile_time_constant(pos, arg)
                for arg in value]
        if None not in args:
            return ExprNodes.TupleNode(pos, args=args)
805
        else:
806 807
            # error already reported
            return None
808
    elif not _IS_PY3 and isinstance(value, long):
809
        return ExprNodes.IntNode(pos, value=rep.rstrip('L'), constant_result=value)
810 811
    error(pos, "Invalid type for compile-time constant: %r (type %s)"
               % (value, value.__class__.__name__))
812 813
    return None

814

815 816
def p_cat_string_literal(s):
    # A sequence of one or more adjacent string literals.
817
    # Returns (kind, bytes_value, unicode_value)
818 819
    # where kind in ('b', 'c', 'u', 'f', '')
    pos = s.position()
820 821 822
    kind, bytes_value, unicode_value = p_string_literal(s)
    if kind == 'c' or s.sy != 'BEGIN_STRING':
        return kind, bytes_value, unicode_value
823
    bstrings, ustrings, positions = [bytes_value], [unicode_value], [pos]
824 825 826 827 828 829
    bytes_value = unicode_value = None
    while s.sy == 'BEGIN_STRING':
        pos = s.position()
        next_kind, next_bytes_value, next_unicode_value = p_string_literal(s)
        if next_kind == 'c':
            error(pos, "Cannot concatenate char literal with another string or char literal")
830
            continue
831
        elif next_kind != kind:
832
            # concatenating f strings and normal strings is allowed and leads to an f string
Stefan Behnel's avatar
Stefan Behnel committed
833
            if set([kind, next_kind]) in (set(['f', 'u']), set(['f', ''])):
834 835
                kind = 'f'
            else:
836 837
                error(pos, "Cannot mix string literals of different types, expected %s'', got %s''" % (
                    kind, next_kind))
838 839 840 841
                continue
        bstrings.append(next_bytes_value)
        ustrings.append(next_unicode_value)
        positions.append(pos)
842
    # join and rewrap the partial literals
843
    if kind in ('b', 'c', '') or kind == 'u' and None not in bstrings:
844
        # Py3 enforced unicode literals are parsed as bytes/unicode combination
845
        bytes_value = bytes_literal(StringEncoding.join_bytes(bstrings), s.source_encoding)
846
    if kind in ('u', ''):
Stefan Behnel's avatar
Stefan Behnel committed
847
        unicode_value = EncodedString(u''.join([u for u in ustrings if u is not None]))
848 849 850 851 852 853 854
    if kind == 'f':
        unicode_value = []
        for u, pos in zip(ustrings, positions):
            if isinstance(u, list):
                unicode_value += u
            else:
                # non-f-string concatenated into the f-string
Stefan Behnel's avatar
Stefan Behnel committed
855
                unicode_value.append(ExprNodes.UnicodeNode(pos, value=EncodedString(u)))
856 857
    return kind, bytes_value, unicode_value

Stefan Behnel's avatar
Stefan Behnel committed
858

859
def p_opt_string_literal(s, required_type='u'):
860
    if s.sy != 'BEGIN_STRING':
861
        return None
862 863 864 865 866 867 868 869 870 871
    pos = s.position()
    kind, bytes_value, unicode_value = p_string_literal(s, required_type)
    if required_type == 'u':
        if kind == 'f':
            s.error("f-string not allowed here", pos)
        return unicode_value
    elif required_type == 'b':
        return bytes_value
    else:
        s.error("internal parser configuration error")
872

Stefan Behnel's avatar
Stefan Behnel committed
873

874 875 876 877 878 879
def check_for_non_ascii_characters(string):
    for c in string:
        if c >= u'\x80':
            return True
    return False

Stefan Behnel's avatar
Stefan Behnel committed
880

881
def p_string_literal(s, kind_override=None):
882
    # A single string or char literal.  Returns (kind, bvalue, uvalue)
883
    # where kind in ('b', 'c', 'u', 'f', '').  The 'bvalue' is the source
884 885 886
    # code byte sequence of the string literal, 'uvalue' is the
    # decoded Unicode string.  Either of the two may be None depending
    # on the 'kind' of string, only unprefixed strings have both
887 888
    # representations. In f-strings, the uvalue is a list of the Unicode
    # strings and f-string expressions that make up the f-string.
889

890 891
    # s.sy == 'BEGIN_STRING'
    pos = s.position()
892
    is_python3_source = s.context.language_level >= 3
893
    has_non_ascii_literal_characters = False
894
    string_start_pos = (pos[0], pos[1], pos[2] + len(s.systring))
895
    kind_string = s.systring.rstrip('"\'').lower()
896 897 898 899 900 901 902 903 904
    if len(kind_string) > 1:
        if len(set(kind_string)) != len(kind_string):
            error(pos, 'Duplicate string prefix character')
        if 'b' in kind_string and 'u' in kind_string:
            error(pos, 'String prefixes b and u cannot be combined')
        if 'b' in kind_string and 'f' in kind_string:
            error(pos, 'String prefixes b and f cannot be combined')
        if 'u' in kind_string and 'f' in kind_string:
            error(pos, 'String prefixes u and f cannot be combined')
905 906 907 908 909 910 911

    is_raw = 'r' in kind_string

    if 'c' in kind_string:
        # this should never happen, since the lexer does not allow combining c
        # with other prefix characters
        if len(kind_string) != 1:
912
            error(pos, 'Invalid string prefix for character literal')
913 914
        kind = 'c'
    elif 'f' in kind_string:
915 916
        kind = 'f'     # u is ignored
        is_raw = True  # postpone the escape resolution
917 918 919 920 921
    elif 'b' in kind_string:
        kind = 'b'
    elif 'u' in kind_string:
        kind = 'u'
    else:
922
        kind = ''
923

924 925 926 927 928 929
    if kind == '' and kind_override is None and Future.unicode_literals in s.context.future_directives:
        chars = StringEncoding.StrLiteralBuilder(s.source_encoding)
        kind = 'u'
    else:
        if kind_override is not None and kind_override in 'ub':
            kind = kind_override
930
        if kind in ('u', 'f'):  # f-strings are scanned exactly like Unicode literals, but are parsed further later
931 932 933 934 935
            chars = StringEncoding.UnicodeLiteralBuilder()
        elif kind == '':
            chars = StringEncoding.StrLiteralBuilder(s.source_encoding)
        else:
            chars = StringEncoding.BytesLiteralBuilder(s.source_encoding)
936

937 938 939
    while 1:
        s.next()
        sy = s.sy
940
        systr = s.systring
941
        # print "p_string_literal: sy =", sy, repr(s.systring) ###
942
        if sy == 'CHARS':
943
            chars.append(systr)
944 945
            if is_python3_source and not has_non_ascii_literal_characters and check_for_non_ascii_characters(systr):
                has_non_ascii_literal_characters = True
946
        elif sy == 'ESCAPE':
947 948
            # in Py2, 'ur' raw unicode strings resolve unicode escapes but nothing else
            if is_raw and (is_python3_source or kind != 'u' or systr[1] not in u'Uu'):
949
                chars.append(systr)
950 951
                if is_python3_source and not has_non_ascii_literal_characters and check_for_non_ascii_characters(systr):
                    has_non_ascii_literal_characters = True
952
            else:
953
                _append_escape_sequence(kind, chars, systr, s)
954
        elif sy == 'NEWLINE':
955
            chars.append(u'\n')
956 957 958
        elif sy == 'END_STRING':
            break
        elif sy == 'EOF':
959
            s.error("Unclosed string literal", pos=pos)
960
        else:
961 962
            s.error("Unexpected token %r:%r in string literal" % (
                sy, s.systring))
963

964
    if kind == 'c':
965 966 967 968
        unicode_value = None
        bytes_value = chars.getchar()
        if len(bytes_value) != 1:
            error(pos, u"invalid character literal: %r" % bytes_value)
969
    else:
970
        bytes_value, unicode_value = chars.getstrings()
971 972
        if (has_non_ascii_literal_characters
                and is_python3_source and Future.unicode_literals in s.context.future_directives):
973
            # Python 3 forbids literal non-ASCII characters in byte strings
974
            if kind == 'b':
975
                s.error("bytes can only contain ASCII literal characters.", pos=pos)
976
            bytes_value = None
977
    if kind == 'f':
978
        unicode_value = p_f_string(s, unicode_value, string_start_pos, is_raw='r' in kind_string)
979
    s.next()
980
    return (kind, bytes_value, unicode_value)
981

982

983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
def _append_escape_sequence(kind, builder, escape_sequence, s):
    c = escape_sequence[1]
    if c in u"01234567":
        builder.append_charval(int(escape_sequence[1:], 8))
    elif c in u"'\"\\":
        builder.append(c)
    elif c in u"abfnrtv":
        builder.append(StringEncoding.char_from_escape_sequence(escape_sequence))
    elif c == u'\n':
        pass  # line continuation
    elif c == u'x':  # \xXX
        if len(escape_sequence) == 4:
            builder.append_charval(int(escape_sequence[2:], 16))
        else:
            s.error("Invalid hex escape '%s'" % escape_sequence, fatal=False)
    elif c in u'NUu' and kind in ('u', 'f', ''):  # \uxxxx, \Uxxxxxxxx, \N{...}
        chrval = -1
        if c == u'N':
1001
            uchar = None
1002
            try:
1003 1004
                uchar = lookup_unicodechar(escape_sequence[3:-1])
                chrval = ord(uchar)
1005 1006 1007
            except KeyError:
                s.error("Unknown Unicode character name %s" %
                        repr(escape_sequence[3:-1]).lstrip('u'), fatal=False)
1008 1009 1010 1011 1012 1013 1014 1015
            except TypeError:
                # 2-byte unicode build of CPython?
                if (uchar is not None and _IS_2BYTE_UNICODE and len(uchar) == 2 and
                        unicode_category(uchar[0]) == 'Cs' and unicode_category(uchar[1]) == 'Cs'):
                    # surrogate pair instead of single character
                    chrval = 0x10000 + (ord(uchar[0]) - 0xd800) >> 10 + (ord(uchar[1]) - 0xdc00)
                else:
                    raise
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
        elif len(escape_sequence) in (6, 10):
            chrval = int(escape_sequence[2:], 16)
            if chrval > 1114111:  # sys.maxunicode:
                s.error("Invalid unicode escape '%s'" % escape_sequence)
                chrval = -1
        else:
            s.error("Invalid unicode escape '%s'" % escape_sequence, fatal=False)
        if chrval >= 0:
            builder.append_uescape(chrval, escape_sequence)
    else:
        builder.append(escape_sequence)


1029
_parse_escape_sequences_raw, _parse_escape_sequences = [re.compile((
1030
    # escape sequences:
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
    br'(\\(?:' +
    (br'\\?' if is_raw else (
        br'[\\abfnrtv"\'{]|'
        br'[0-7]{2,3}|'
        br'N\{[^}]*\}|'
        br'x[0-9a-fA-F]{2}|'
        br'u[0-9a-fA-F]{4}|'
        br'U[0-9a-fA-F]{8}|'
        br'[NxuU]|'  # detect invalid escape sequences that do not match above
    )) +
1041 1042 1043 1044
    br')?|'
    # non-escape sequences:
    br'\{\{?|'
    br'\}\}?|'
1045 1046 1047
    br'[^\\{}]+)'
    ).decode('us-ascii')).match
    for is_raw in (True, False)]
1048 1049


1050 1051 1052 1053
def _f_string_error_pos(pos, string, i):
    return (pos[0], pos[1], pos[2] + i + 1)  # FIXME: handle newlines in string


1054
def p_f_string(s, unicode_value, pos, is_raw):
1055 1056 1057
    # Parses a PEP 498 f-string literal into a list of nodes. Nodes are either UnicodeNodes
    # or FormattedValueNodes.
    values = []
1058
    next_start = 0
1059
    size = len(unicode_value)
1060
    builder = StringEncoding.UnicodeLiteralBuilder()
1061
    _parse_seq = _parse_escape_sequences_raw if is_raw else _parse_escape_sequences
1062 1063 1064

    while next_start < size:
        end = next_start
1065
        match = _parse_seq(unicode_value, next_start)
1066
        if match is None:
1067
            error(_f_string_error_pos(pos, unicode_value, next_start), "Invalid escape sequence")
1068 1069 1070 1071 1072 1073 1074

        next_start = match.end()
        part = match.group()
        c = part[0]
        if c == '\\':
            if not is_raw and len(part) > 1:
                _append_escape_sequence('f', builder, part, s)
1075
            else:
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
                builder.append(part)
        elif c == '{':
            if part == '{{':
                builder.append('{')
            else:
                # start of an expression
                if builder.chars:
                    values.append(ExprNodes.UnicodeNode(pos, value=builder.getstring()))
                    builder = StringEncoding.UnicodeLiteralBuilder()
                next_start, expr_node = p_f_string_expr(s, unicode_value, pos, next_start, is_raw)
1086
                values.append(expr_node)
1087 1088 1089 1090
        elif c == '}':
            if part == '}}':
                builder.append('}')
            else:
1091 1092
                error(_f_string_error_pos(pos, unicode_value, end),
                      "f-string: single '}' is not allowed")
1093
        else:
1094
            builder.append(part)
1095

1096 1097
    if builder.chars:
        values.append(ExprNodes.UnicodeNode(pos, value=builder.getstring()))
1098 1099 1100
    return values


1101
def p_f_string_expr(s, unicode_value, pos, starting_index, is_raw):
1102 1103 1104 1105
    # Parses a {}-delimited expression inside an f-string. Returns a FormattedValueNode
    # and the index in the string that follows the expression.
    i = starting_index
    size = len(unicode_value)
1106
    conversion_char = terminal_char = format_spec = None
1107
    format_spec_str = None
1108
    NO_CHAR = 2**30
1109 1110

    nested_depth = 0
1111
    quote_char = NO_CHAR
1112
    in_triple_quotes = False
1113
    backslash_reported = False
1114 1115 1116

    while True:
        if i >= size:
1117
            break  # error will be reported below
1118 1119
        c = unicode_value[i]

1120
        if quote_char != NO_CHAR:
1121
            if c == '\\':
1122 1123 1124 1125 1126
                # avoid redundant error reports along '\' sequences
                if not backslash_reported:
                    error(_f_string_error_pos(pos, unicode_value, i),
                          "backslashes not allowed in f-strings")
                backslash_reported = True
1127 1128 1129 1130
            elif c == quote_char:
                if in_triple_quotes:
                    if i + 2 < size and unicode_value[i + 1] == c and unicode_value[i + 2] == c:
                        in_triple_quotes = False
1131
                        quote_char = NO_CHAR
1132 1133
                        i += 2
                else:
1134
                    quote_char = NO_CHAR
1135 1136 1137 1138 1139 1140
        elif c in '\'"':
            quote_char = c
            if i + 2 < size and unicode_value[i + 1] == c and unicode_value[i + 2] == c:
                in_triple_quotes = True
                i += 2
        elif c in '{[(':
1141 1142 1143 1144
            nested_depth += 1
        elif nested_depth != 0 and c in '}])':
            nested_depth -= 1
        elif c == '#':
1145 1146
            error(_f_string_error_pos(pos, unicode_value, i),
                  "format string cannot include #")
1147 1148 1149
        elif nested_depth == 0 and c in '!:}':
            # allow != as a special case
            if c == '!' and i + 1 < size and unicode_value[i + 1] == '=':
Jelle Zijlstra's avatar
Jelle Zijlstra committed
1150
                i += 1
1151 1152 1153 1154 1155 1156
                continue

            terminal_char = c
            break
        i += 1

1157 1158 1159 1160 1161
    # normalise line endings as the parser expects that
    expr_str = unicode_value[starting_index:i].replace('\r\n', '\n').replace('\r', '\n')
    expr_pos = (pos[0], pos[1], pos[2] + starting_index + 2)  # TODO: find exact code position (concat, multi-line, ...)

    if not expr_str.strip():
1162 1163
        error(_f_string_error_pos(pos, unicode_value, starting_index),
              "empty expression not allowed in f-string")
1164 1165 1166

    if terminal_char == '!':
        i += 1
1167
        if i + 2 > size:
1168
            pass  # error will be reported below
1169 1170 1171 1172
        else:
            conversion_char = unicode_value[i]
            i += 1
            terminal_char = unicode_value[i]
1173 1174

    if terminal_char == ':':
1175 1176
        in_triple_quotes = False
        in_string = False
1177 1178 1179 1180
        nested_depth = 0
        start_format_spec = i + 1
        while True:
            if i >= size:
1181
                break  # error will be reported below
1182
            c = unicode_value[i]
1183 1184 1185 1186
            if not in_triple_quotes and not in_string:
                if c == '{':
                    nested_depth += 1
                elif c == '}':
1187 1188 1189 1190 1191
                    if nested_depth > 0:
                        nested_depth -= 1
                    else:
                        terminal_char = c
                        break
1192 1193 1194 1195 1196 1197
            if c in '\'"':
                if not in_string and i + 2 < size and unicode_value[i + 1] == c and unicode_value[i + 2] == c:
                    in_triple_quotes = not in_triple_quotes
                    i += 2
                elif not in_triple_quotes:
                    in_string = not in_string
1198 1199 1200 1201 1202
            i += 1

        format_spec_str = unicode_value[start_format_spec:i]

    if terminal_char != '}':
1203 1204 1205
        error(_f_string_error_pos(pos, unicode_value, i),
              "missing '}' in format string expression" + (
                  ", found '%s'" % terminal_char if terminal_char else ""))
1206

1207 1208 1209
    # parse the expression as if it was surrounded by parentheses
    buf = StringIO('(%s)' % expr_str)
    scanner = PyrexScanner(buf, expr_pos[0], parent_scanner=s, source_encoding=s.source_encoding, initial_pos=expr_pos)
1210 1211 1212
    expr = p_testlist(scanner)  # TODO is testlist right here?

    # validate the conversion char
1213
    if conversion_char is not None and not ExprNodes.FormattedValueNode.find_conversion_func(conversion_char):
1214
        error(expr_pos, "invalid conversion character '%s'" % conversion_char)
1215 1216

    # the format spec is itself treated like an f-string
1217
    if format_spec_str:
1218
        format_spec = ExprNodes.JoinedStrNode(pos, values=p_f_string(s, format_spec_str, pos, is_raw))
1219 1220

    return i + 1, ExprNodes.FormattedValueNode(
1221
        pos, value=expr, conversion_char=conversion_char, format_spec=format_spec)
1222 1223


1224 1225 1226
# since PEP 448:
# list_display  ::=     "[" [listmaker] "]"
# listmaker     ::=     (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )
Stefan Behnel's avatar
Stefan Behnel committed
1227
# comp_iter     ::=     comp_for | comp_if
1228
# comp_for      ::=     ["async"] "for" expression_list "in" testlist [comp_iter]
1229
# comp_if       ::=     "if" test [comp_iter]
1230

1231 1232 1233 1234
def p_list_maker(s):
    # s.sy == '['
    pos = s.position()
    s.next()
Robert Bradshaw's avatar
Robert Bradshaw committed
1235 1236
    if s.sy == ']':
        s.expect(']')
1237 1238 1239
        return ExprNodes.ListNode(pos, args=[])

    expr = p_test_or_starred_expr(s)
1240
    if s.sy in ('for', 'async'):
1241 1242
        if expr.is_starred:
            s.error("iterable unpacking cannot be used in comprehension")
1243
        append = ExprNodes.ComprehensionAppendNode(pos, expr=expr)
1244
        loop = p_comp_for(s, append)
Robert Bradshaw's avatar
Robert Bradshaw committed
1245
        s.expect(']')
1246
        return ExprNodes.ComprehensionNode(
1247
            pos, loop=loop, append=append, type=Builtin.list_type,
1248
            # list comprehensions leak their loop variable in Py2
1249 1250 1251 1252 1253 1254
            has_local_scope=s.context.language_level >= 3)

    # (merged) list literal
    if s.sy == ',':
        s.next()
        exprs = p_test_or_starred_expr_list(s, expr)
Robert Bradshaw's avatar
Robert Bradshaw committed
1255
    else:
1256 1257 1258 1259
        exprs = [expr]
    s.expect(']')
    return ExprNodes.ListNode(pos, args=exprs)

1260

Stefan Behnel's avatar
Stefan Behnel committed
1261
def p_comp_iter(s, body):
1262
    if s.sy in ('for', 'async'):
1263
        return p_comp_for(s, body)
Robert Bradshaw's avatar
Robert Bradshaw committed
1264
    elif s.sy == 'if':
Stefan Behnel's avatar
Stefan Behnel committed
1265
        return p_comp_if(s, body)
Robert Bradshaw's avatar
Robert Bradshaw committed
1266
    else:
1267 1268
        # insert the 'append' operation into the loop
        return body
1269

1270
def p_comp_for(s, body):
Robert Bradshaw's avatar
Robert Bradshaw committed
1271
    pos = s.position()
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
    # [async] for ...
    is_async = False
    if s.sy == 'async':
        is_async = True
        s.next()

    # s.sy == 'for'
    s.expect('for')
    kw = p_for_bounds(s, allow_testlist=False, is_async=is_async)
    kw.update(else_clause=None, body=p_comp_iter(s, body), is_async=is_async)
Robert Bradshaw's avatar
Robert Bradshaw committed
1282
    return Nodes.ForStatNode(pos, **kw)
1283

Stefan Behnel's avatar
Stefan Behnel committed
1284
def p_comp_if(s, body):
Robert Bradshaw's avatar
Robert Bradshaw committed
1285 1286 1287
    # s.sy == 'if'
    pos = s.position()
    s.next()
Stefan Behnel's avatar
Stefan Behnel committed
1288
    test = p_test_nocond(s)