322a2b8245f70a753979b9979335050fdd006468
[cython.git] / Cython / Compiler / Parsing.py
1 # cython: auto_cpdef=True, infer_types=True
2 #
3 #   Pyrex Parser
4 #
5
6 # This should be done automatically
7 import cython
8 cython.declare(Nodes=object, ExprNodes=object, EncodedString=object)
9
10 import os
11 import re
12 import sys
13
14 from Cython.Compiler.Scanning import PyrexScanner, FileSourceDescriptor
15 import Nodes
16 import ExprNodes
17 import StringEncoding
18 from StringEncoding import EncodedString, BytesLiteral, _unicode, _bytes
19 from ModuleNode import ModuleNode
20 from Errors import error, warning, InternalError
21 from Cython import Utils
22 import Future
23 import Options
24
25 class Ctx(object):
26     #  Parsing context
27     level = 'other'
28     visibility = 'private'
29     cdef_flag = 0
30     typedef_flag = 0
31     api = 0
32     overridable = 0
33     nogil = 0
34     namespace = None
35     templates = None
36
37     def __init__(self, **kwds):
38         self.__dict__.update(kwds)
39
40     def __call__(self, **kwds):
41         ctx = Ctx()
42         d = ctx.__dict__
43         d.update(self.__dict__)
44         d.update(kwds)
45         return ctx
46
47 def p_ident(s, message = "Expected an identifier"):
48     if s.sy == 'IDENT':
49         name = s.systring
50         s.next()
51         return name
52     else:
53         s.error(message)
54
55 def p_ident_list(s):
56     names = []
57     while s.sy == 'IDENT':
58         names.append(s.systring)
59         s.next()
60         if s.sy != ',':
61             break
62         s.next()
63     return names
64
65 #------------------------------------------
66 #
67 #   Expressions
68 #
69 #------------------------------------------
70
71 def p_binop_operator(s):
72     pos = s.position()
73     op = s.sy
74     s.next()
75     return op, pos
76
77 def p_binop_expr(s, ops, p_sub_expr):
78     n1 = p_sub_expr(s)
79     while s.sy in ops:
80         op, pos = p_binop_operator(s)
81         n2 = p_sub_expr(s)
82         n1 = ExprNodes.binop_node(pos, op, n1, n2)
83         if op == '/':
84             if Future.division in s.context.future_directives:
85                 n1.truedivision = True
86             else:
87                 n1.truedivision = None # unknown
88     return n1
89
90 #lambdef: 'lambda' [varargslist] ':' test
91
92 def p_lambdef(s, allow_conditional=True):
93     # s.sy == 'lambda'
94     pos = s.position()
95     s.next()
96     if s.sy == ':':
97         args = []
98         star_arg = starstar_arg = None
99     else:
100         args, star_arg, starstar_arg = p_varargslist(
101             s, terminator=':', annotated=False)
102     s.expect(':')
103     if allow_conditional:
104         expr = p_test(s)
105     else:
106         expr = p_test_nocond(s)
107     return ExprNodes.LambdaNode(
108         pos, args = args,
109         star_arg = star_arg, starstar_arg = starstar_arg,
110         result_expr = expr)
111
112 #lambdef_nocond: 'lambda' [varargslist] ':' test_nocond
113
114 def p_lambdef_nocond(s):
115     return p_lambdef(s, allow_conditional=False)
116
117 #test: or_test ['if' or_test 'else' test] | lambdef
118
119 def p_test(s):
120     if s.sy == 'lambda':
121         return p_lambdef(s)
122     pos = s.position()
123     expr = p_or_test(s)
124     if s.sy == 'if':
125         s.next()
126         test = p_or_test(s)
127         s.expect('else')
128         other = p_test(s)
129         return ExprNodes.CondExprNode(pos, test=test, true_val=expr, false_val=other)
130     else:
131         return expr
132
133 #test_nocond: or_test | lambdef_nocond
134
135 def p_test_nocond(s):
136     if s.sy == 'lambda':
137         return p_lambdef_nocond(s)
138     else:
139         return p_or_test(s)
140
141 #or_test: and_test ('or' and_test)*
142
143 def p_or_test(s):
144     return p_rassoc_binop_expr(s, ('or',), p_and_test)
145
146 def p_rassoc_binop_expr(s, ops, p_subexpr):
147     n1 = p_subexpr(s)
148     if s.sy in ops:
149         pos = s.position()
150         op = s.sy
151         s.next()
152         n2 = p_rassoc_binop_expr(s, ops, p_subexpr)
153         n1 = ExprNodes.binop_node(pos, op, n1, n2)
154     return n1
155
156 #and_test: not_test ('and' not_test)*
157
158 def p_and_test(s):
159     #return p_binop_expr(s, ('and',), p_not_test)
160     return p_rassoc_binop_expr(s, ('and',), p_not_test)
161
162 #not_test: 'not' not_test | comparison
163
164 def p_not_test(s):
165     if s.sy == 'not':
166         pos = s.position()
167         s.next()
168         return ExprNodes.NotNode(pos, operand = p_not_test(s))
169     else:
170         return p_comparison(s)
171
172 #comparison: expr (comp_op expr)*
173 #comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
174
175 def p_comparison(s):
176     n1 = p_starred_expr(s)
177     if s.sy in comparison_ops:
178         pos = s.position()
179         op = p_cmp_op(s)
180         n2 = p_starred_expr(s)
181         n1 = ExprNodes.PrimaryCmpNode(pos, 
182             operator = op, operand1 = n1, operand2 = n2)
183         if s.sy in comparison_ops:
184             n1.cascade = p_cascaded_cmp(s)
185     return n1
186
187 def p_test_or_starred_expr(s):
188     if s.sy == '*':
189         return p_starred_expr(s)
190     else:
191         return p_test(s)
192
193 def p_starred_expr(s):
194     pos = s.position()
195     if s.sy == '*':
196         starred = True
197         s.next()
198     else:
199         starred = False
200     expr = p_bit_expr(s)
201     if starred:
202         expr = ExprNodes.StarredTargetNode(pos, expr)
203     return expr
204
205 def p_cascaded_cmp(s):
206     pos = s.position()
207     op = p_cmp_op(s)
208     n2 = p_starred_expr(s)
209     result = ExprNodes.CascadedCmpNode(pos, 
210         operator = op, operand2 = n2)
211     if s.sy in comparison_ops:
212         result.cascade = p_cascaded_cmp(s)
213     return result
214
215 def p_cmp_op(s):
216     if s.sy == 'not':
217         s.next()
218         s.expect('in')
219         op = 'not_in'
220     elif s.sy == 'is':
221         s.next()
222         if s.sy == 'not':
223             s.next()
224             op = 'is_not'
225         else:
226             op = 'is'
227     else:
228         op = s.sy
229         s.next()
230     if op == '<>':
231         op = '!='
232     return op
233     
234 comparison_ops = (
235     '<', '>', '==', '>=', '<=', '<>', '!=', 
236     'in', 'is', 'not'
237 )
238
239 #expr: xor_expr ('|' xor_expr)*
240
241 def p_bit_expr(s):
242     return p_binop_expr(s, ('|',), p_xor_expr)
243
244 #xor_expr: and_expr ('^' and_expr)*
245
246 def p_xor_expr(s):
247     return p_binop_expr(s, ('^',), p_and_expr)
248
249 #and_expr: shift_expr ('&' shift_expr)*
250
251 def p_and_expr(s):
252     return p_binop_expr(s, ('&',), p_shift_expr)
253
254 #shift_expr: arith_expr (('<<'|'>>') arith_expr)*
255
256 def p_shift_expr(s):
257     return p_binop_expr(s, ('<<', '>>'), p_arith_expr)
258
259 #arith_expr: term (('+'|'-') term)*
260
261 def p_arith_expr(s):
262     return p_binop_expr(s, ('+', '-'), p_term)
263
264 #term: factor (('*'|'/'|'%') factor)*
265
266 def p_term(s):
267     return p_binop_expr(s, ('*', '/', '%', '//'), p_factor)
268
269 #factor: ('+'|'-'|'~'|'&'|typecast|sizeof) factor | power
270
271 def p_factor(s):
272     sy = s.sy
273     if sy in ('+', '-', '~'):
274         op = s.sy
275         pos = s.position()
276         s.next()
277         return ExprNodes.unop_node(pos, op, p_factor(s))
278     elif sy == '&':
279         pos = s.position()
280         s.next()
281         arg = p_factor(s)
282         return ExprNodes.AmpersandNode(pos, operand = arg)
283     elif sy == "<":
284         return p_typecast(s)
285     elif sy == 'IDENT' and s.systring == "sizeof":
286         return p_sizeof(s)
287     else:
288         return p_power(s)
289
290 def p_typecast(s):
291     # s.sy == "<"
292     pos = s.position()
293     s.next()
294     base_type = p_c_base_type(s)
295     if base_type.name is None:
296         s.error("Unknown type")
297     declarator = p_c_declarator(s, empty = 1)
298     if s.sy == '?':
299         s.next()
300         typecheck = 1
301     else:
302         typecheck = 0
303     s.expect(">")
304     operand = p_factor(s)
305     return ExprNodes.TypecastNode(pos, 
306         base_type = base_type, 
307         declarator = declarator,
308         operand = operand,
309         typecheck = typecheck)
310
311 def p_sizeof(s):
312     # s.sy == ident "sizeof"
313     pos = s.position()
314     s.next()
315     s.expect('(')
316     # Here we decide if we are looking at an expression or type
317     # If it is actually a type, but parsable as an expression, 
318     # we treat it as an expression here. 
319     if looking_at_expr(s):
320         operand = p_test(s)
321         node = ExprNodes.SizeofVarNode(pos, operand = operand)
322     else:
323         base_type = p_c_base_type(s)
324         declarator = p_c_declarator(s, empty = 1)
325         node = ExprNodes.SizeofTypeNode(pos, 
326             base_type = base_type, declarator = declarator)
327     s.expect(')')
328     return node
329
330 def p_yield_expression(s):
331     # s.sy == "yield"
332     pos = s.position()
333     s.next()
334     if s.sy != ')' and s.sy not in statement_terminators:
335         arg = p_testlist(s)
336     else:
337         arg = None
338     return ExprNodes.YieldExprNode(pos, arg=arg)
339
340 def p_yield_statement(s):
341     # s.sy == "yield"
342     yield_expr = p_yield_expression(s)
343     return Nodes.ExprStatNode(yield_expr.pos, expr=yield_expr)
344
345 #power: atom trailer* ('**' factor)*
346
347 def p_power(s):
348     if s.systring == 'new' and s.peek()[0] == 'IDENT':
349         return p_new_expr(s)
350     n1 = p_atom(s)
351     while s.sy in ('(', '[', '.'):
352         n1 = p_trailer(s, n1)
353     if s.sy == '**':
354         pos = s.position()
355         s.next()
356         n2 = p_factor(s)
357         n1 = ExprNodes.binop_node(pos, '**', n1, n2)
358     return n1
359
360 def p_new_expr(s):
361     # s.systring == 'new'.
362     pos = s.position()
363     s.next()
364     cppclass = p_c_base_type(s)
365     return p_call(s, ExprNodes.NewExprNode(pos, cppclass = cppclass))
366
367 #trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
368
369 def p_trailer(s, node1):
370     pos = s.position()
371     if s.sy == '(':
372         return p_call(s, node1)
373     elif s.sy == '[':
374         return p_index(s, node1)
375     else: # s.sy == '.'
376         s.next()
377         name = EncodedString( p_ident(s) )
378         return ExprNodes.AttributeNode(pos, 
379             obj = node1, attribute = name)
380
381 # arglist:  argument (',' argument)* [',']
382 # argument: [test '='] test       # Really [keyword '='] test
383
384 def p_call_parse_args(s, allow_genexp = True):
385     # s.sy == '('
386     pos = s.position()
387     s.next()
388     positional_args = []
389     keyword_args = []
390     star_arg = None
391     starstar_arg = None
392     while s.sy not in ('**', ')'):
393         if s.sy == '*':
394             if star_arg:
395                 s.error("only one star-arg parameter allowed",
396                     pos = s.position())
397             s.next()
398             star_arg = p_test(s)
399         else:
400             arg = p_test(s)
401             if s.sy == '=':
402                 s.next()
403                 if not arg.is_name:
404                     s.error("Expected an identifier before '='",
405                         pos = arg.pos)
406                 encoded_name = EncodedString(arg.name)
407                 keyword = ExprNodes.IdentifierStringNode(arg.pos, value = encoded_name)
408                 arg = p_test(s)
409                 keyword_args.append((keyword, arg))
410             else:
411                 if keyword_args:
412                     s.error("Non-keyword arg following keyword arg",
413                         pos = arg.pos)
414                 if star_arg:
415                     s.error("Non-keyword arg following star-arg",
416                         pos = arg.pos)
417                 positional_args.append(arg)
418         if s.sy != ',':
419             break
420         s.next()
421
422     if s.sy == 'for':
423         if len(positional_args) == 1 and not star_arg:
424             positional_args = [ p_genexp(s, positional_args[0]) ]
425     elif s.sy == '**':
426         s.next()
427         starstar_arg = p_test(s)
428         if s.sy == ',':
429             s.next()
430     s.expect(')')
431     return positional_args, keyword_args, star_arg, starstar_arg
432
433 def p_call_build_packed_args(pos, positional_args, keyword_args, star_arg):
434     arg_tuple = None
435     keyword_dict = None
436     if positional_args or not star_arg:
437         arg_tuple = ExprNodes.TupleNode(pos,
438             args = positional_args)
439     if star_arg:
440         star_arg_tuple = ExprNodes.AsTupleNode(pos, arg = star_arg)
441         if arg_tuple:
442             arg_tuple = ExprNodes.binop_node(pos,
443                 operator = '+', operand1 = arg_tuple,
444                 operand2 = star_arg_tuple)
445         else:
446             arg_tuple = star_arg_tuple
447     if keyword_args:
448         keyword_args = [ExprNodes.DictItemNode(pos=key.pos, key=key, value=value)
449                           for key, value in keyword_args]
450         keyword_dict = ExprNodes.DictNode(pos,
451             key_value_pairs = keyword_args)
452     return arg_tuple, keyword_dict
453
454 def p_call(s, function):
455     # s.sy == '('
456     pos = s.position()
457
458     positional_args, keyword_args, star_arg, starstar_arg = \
459                      p_call_parse_args(s)
460
461     if not (keyword_args or star_arg or starstar_arg):
462         return ExprNodes.SimpleCallNode(pos,
463             function = function,
464             args = positional_args)
465     else:
466         arg_tuple, keyword_dict = p_call_build_packed_args(
467             pos, positional_args, keyword_args, star_arg)
468         return ExprNodes.GeneralCallNode(pos, 
469             function = function,
470             positional_args = arg_tuple,
471             keyword_args = keyword_dict,
472             starstar_arg = starstar_arg)
473
474 #lambdef: 'lambda' [varargslist] ':' test
475
476 #subscriptlist: subscript (',' subscript)* [',']
477
478 def p_index(s, base):
479     # s.sy == '['
480     pos = s.position()
481     s.next()
482     subscripts = p_subscript_list(s)
483     if len(subscripts) == 1 and len(subscripts[0]) == 2:
484         start, stop = subscripts[0]
485         result = ExprNodes.SliceIndexNode(pos, 
486             base = base, start = start, stop = stop)
487     else:
488         indexes = make_slice_nodes(pos, subscripts)
489         if len(indexes) == 1:
490             index = indexes[0]
491         else:
492             index = ExprNodes.TupleNode(pos, args = indexes)
493         result = ExprNodes.IndexNode(pos,
494             base = base, index = index)
495     s.expect(']')
496     return result
497
498 def p_subscript_list(s):
499     items = [p_subscript(s)]
500     while s.sy == ',':
501         s.next()
502         if s.sy == ']':
503             break
504         items.append(p_subscript(s))
505     return items
506
507 #subscript: '.' '.' '.' | test | [test] ':' [test] [':' [test]]
508
509 def p_subscript(s):
510     # Parse a subscript and return a list of
511     # 1, 2 or 3 ExprNodes, depending on how
512     # many slice elements were encountered.
513     pos = s.position()
514     start = p_slice_element(s, (':',))
515     if s.sy != ':':
516         return [start]
517     s.next()
518     stop = p_slice_element(s, (':', ',', ']'))
519     if s.sy != ':':
520         return [start, stop]
521     s.next()
522     step = p_slice_element(s, (':', ',', ']'))
523     return [start, stop, step]
524
525 def p_slice_element(s, follow_set):
526     # Simple expression which may be missing iff
527     # it is followed by something in follow_set.
528     if s.sy not in follow_set:
529         return p_test(s)
530     else:
531         return None
532
533 def expect_ellipsis(s):
534     s.expect('.')
535     s.expect('.')
536     s.expect('.')
537
538 def make_slice_nodes(pos, subscripts):
539     # Convert a list of subscripts as returned
540     # by p_subscript_list into a list of ExprNodes,
541     # creating SliceNodes for elements with 2 or
542     # more components.
543     result = []
544     for subscript in subscripts:
545         if len(subscript) == 1:
546             result.append(subscript[0])
547         else:
548             result.append(make_slice_node(pos, *subscript))
549     return result
550
551 def make_slice_node(pos, start, stop = None, step = None):
552     if not start:
553         start = ExprNodes.NoneNode(pos)
554     if not stop:
555         stop = ExprNodes.NoneNode(pos)
556     if not step:
557         step = ExprNodes.NoneNode(pos)
558     return ExprNodes.SliceNode(pos,
559         start = start, stop = stop, step = step)
560
561 #atom: '(' [yield_expr|testlist_comp] ')' | '[' [listmaker] ']' | '{' [dict_or_set_maker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+
562
563 def p_atom(s):
564     pos = s.position()
565     sy = s.sy
566     if sy == '(':
567         s.next()
568         if s.sy == ')':
569             result = ExprNodes.TupleNode(pos, args = [])
570         elif s.sy == 'yield':
571             result = p_yield_expression(s)
572         else:
573             result = p_testlist_comp(s)
574         s.expect(')')
575         return result
576     elif sy == '[':
577         return p_list_maker(s)
578     elif sy == '{':
579         return p_dict_or_set_maker(s)
580     elif sy == '`':
581         return p_backquote_expr(s)
582     elif sy == '.':
583         expect_ellipsis(s)
584         return ExprNodes.EllipsisNode(pos)
585     elif sy == 'INT':
586         return p_int_literal(s)
587     elif sy == 'FLOAT':
588         value = s.systring
589         s.next()
590         return ExprNodes.FloatNode(pos, value = value)
591     elif sy == 'IMAG':
592         value = s.systring[:-1]
593         s.next()
594         return ExprNodes.ImagNode(pos, value = value)
595     elif sy == 'BEGIN_STRING':
596         kind, bytes_value, unicode_value = p_cat_string_literal(s)
597         if kind == 'c':
598             return ExprNodes.CharNode(pos, value = bytes_value)
599         elif kind == 'u':
600             return ExprNodes.UnicodeNode(pos, value = unicode_value, bytes_value = bytes_value)
601         elif kind == 'b':
602             return ExprNodes.BytesNode(pos, value = bytes_value)
603         else:
604             return ExprNodes.StringNode(pos, value = bytes_value, unicode_value = unicode_value)
605     elif sy == 'IDENT':
606         name = EncodedString( s.systring )
607         s.next()
608         if name == "None":
609             return ExprNodes.NoneNode(pos)
610         elif name == "True":
611             return ExprNodes.BoolNode(pos, value=True)
612         elif name == "False":
613             return ExprNodes.BoolNode(pos, value=False)
614         elif name == "NULL":
615             return ExprNodes.NullNode(pos)
616         else:
617             return p_name(s, name)
618     else:
619         s.error("Expected an identifier or literal")
620
621 def p_int_literal(s):
622     pos = s.position()
623     value = s.systring
624     s.next()
625     unsigned = ""
626     longness = ""
627     while value[-1] in u"UuLl":
628         if value[-1] in u"Ll":
629             longness += "L"
630         else:
631             unsigned += "U"
632         value = value[:-1]
633     # '3L' is ambiguous in Py2 but not in Py3.  '3U' and '3LL' are
634     # illegal in Py2 Python files.  All suffixes are illegal in Py3
635     # Python files.
636     is_c_literal = None
637     if unsigned:
638         is_c_literal = True
639     elif longness:
640         if longness == 'LL' or s.context.language_level >= 3:
641             is_c_literal = True
642     if s.in_python_file:
643         if is_c_literal:
644             error(pos, "illegal integer literal syntax in Python source file")
645         is_c_literal = False
646     return ExprNodes.IntNode(pos,
647                              is_c_literal = is_c_literal,
648                              value = value,
649                              unsigned = unsigned,
650                              longness = longness)
651
652 def p_name(s, name):
653     pos = s.position()
654     if not s.compile_time_expr and name in s.compile_time_env:
655         value = s.compile_time_env.lookup_here(name)
656         rep = repr(value)
657         if isinstance(value, bool):
658             return ExprNodes.BoolNode(pos, value = value)
659         elif isinstance(value, int):
660             return ExprNodes.IntNode(pos, value = rep)
661         elif isinstance(value, long):
662             return ExprNodes.IntNode(pos, value = rep, longness = "L")
663         elif isinstance(value, float):
664             return ExprNodes.FloatNode(pos, value = rep)
665         elif isinstance(value, _unicode):
666             return ExprNodes.UnicodeNode(pos, value = value)
667         elif isinstance(value, _bytes):
668             return ExprNodes.BytesNode(pos, value = value)
669         else:
670             error(pos, "Invalid type for compile-time constant: %s"
671                 % value.__class__.__name__)
672     return ExprNodes.NameNode(pos, name = name)
673
674 def p_cat_string_literal(s):
675     # A sequence of one or more adjacent string literals.
676     # Returns (kind, bytes_value, unicode_value)
677     # where kind in ('b', 'c', 'u', '')
678     kind, bytes_value, unicode_value = p_string_literal(s)
679     if kind == 'c' or s.sy != 'BEGIN_STRING':
680         return kind, bytes_value, unicode_value
681     bstrings, ustrings = [bytes_value], [unicode_value]
682     bytes_value = unicode_value = None
683     while s.sy == 'BEGIN_STRING':
684         pos = s.position()
685         next_kind, next_bytes_value, next_unicode_value = p_string_literal(s)
686         if next_kind == 'c':
687             error(pos, "Cannot concatenate char literal with another string or char literal")
688         elif next_kind != kind:
689             error(pos, "Cannot mix string literals of different types, expected %s'', got %s''" %
690                   (kind, next_kind))
691         else:
692             bstrings.append(next_bytes_value)
693             ustrings.append(next_unicode_value)
694     # join and rewrap the partial literals
695     if kind in ('b', 'c', '') or kind == 'u' and None not in bstrings:
696         # Py3 enforced unicode literals are parsed as bytes/unicode combination
697         bytes_value = BytesLiteral( StringEncoding.join_bytes(bstrings) )
698         bytes_value.encoding = s.source_encoding
699     if kind in ('u', ''):
700         unicode_value = EncodedString( u''.join([ u for u in ustrings if u is not None ]) )
701     return kind, bytes_value, unicode_value
702
703 def p_opt_string_literal(s, required_type='u'):
704     if s.sy == 'BEGIN_STRING':
705         kind, bytes_value, unicode_value = p_string_literal(s, required_type)
706         if required_type == 'u':
707             return unicode_value
708         elif required_type == 'b':
709             return bytes_value
710         else:
711             s.error("internal parser configuration error")
712     else:
713         return None
714
715 def check_for_non_ascii_characters(string):
716     for c in string:
717         if c >= u'\x80':
718             return True
719     return False
720
721 def p_string_literal(s, kind_override=None):
722     # A single string or char literal.  Returns (kind, bvalue, uvalue)
723     # where kind in ('b', 'c', 'u', '').  The 'bvalue' is the source
724     # code byte sequence of the string literal, 'uvalue' is the
725     # decoded Unicode string.  Either of the two may be None depending
726     # on the 'kind' of string, only unprefixed strings have both
727     # representations.
728
729     # s.sy == 'BEGIN_STRING'
730     pos = s.position()
731     is_raw = 0
732     is_python3_source = s.context.language_level >= 3
733     has_non_ASCII_literal_characters = False
734     kind = s.systring[:1].lower()
735     if kind == 'r':
736         kind = ''
737         is_raw = 1
738     elif kind in 'ub':
739         is_raw = s.systring[1:2].lower() == 'r'
740     elif kind != 'c':
741         kind = ''
742     if kind == '' and kind_override is None and Future.unicode_literals in s.context.future_directives:
743         chars = StringEncoding.StrLiteralBuilder(s.source_encoding)
744         kind = 'u'
745     else:
746         if kind_override is not None and kind_override in 'ub':
747             kind = kind_override
748         if kind == 'u':
749             chars = StringEncoding.UnicodeLiteralBuilder()
750         elif kind == '':
751             chars = StringEncoding.StrLiteralBuilder(s.source_encoding)
752         else:
753             chars = StringEncoding.BytesLiteralBuilder(s.source_encoding)
754     while 1:
755         s.next()
756         sy = s.sy
757         systr = s.systring
758         #print "p_string_literal: sy =", sy, repr(s.systring) ###
759         if sy == 'CHARS':
760             chars.append(systr)
761             if is_python3_source and not has_non_ASCII_literal_characters and check_for_non_ascii_characters(systr):
762                 has_non_ASCII_literal_characters = True
763         elif sy == 'ESCAPE':
764             if is_raw:
765                 if systr == u'\\\n':
766                     chars.append(u'\\\n')
767                 elif systr == u'\\\"':
768                     chars.append(u'"')
769                 elif systr == u'\\\'':
770                     chars.append(u"'")
771                 else:
772                     chars.append(systr)
773                     if is_python3_source and not has_non_ASCII_literal_characters \
774                            and check_for_non_ascii_characters(systr):
775                         has_non_ASCII_literal_characters = True
776             else:
777                 c = systr[1]
778                 if c in u"01234567":
779                     chars.append_charval( int(systr[1:], 8) )
780                 elif c in u"'\"\\":
781                     chars.append(c)
782                 elif c in u"abfnrtv":
783                     chars.append(
784                         StringEncoding.char_from_escape_sequence(systr))
785                 elif c == u'\n':
786                     pass
787                 elif c == u'x':
788                     chars.append_charval( int(systr[2:], 16) )
789                 elif c in u'Uu':
790                     if kind in ('u', ''):
791                         chrval = int(systr[2:], 16)
792                         if chrval > 1114111: # sys.maxunicode:
793                             s.error("Invalid unicode escape '%s'" % systr,
794                                     pos = pos)
795                     else:
796                         # unicode escapes in plain byte strings are not unescaped
797                         chrval = None
798                     chars.append_uescape(chrval, systr)
799                 else:
800                     chars.append(u'\\' + systr[1:])
801                     if is_python3_source and not has_non_ASCII_literal_characters \
802                            and check_for_non_ascii_characters(systr):
803                         has_non_ASCII_literal_characters = True
804         elif sy == 'NEWLINE':
805             chars.append(u'\n')
806         elif sy == 'END_STRING':
807             break
808         elif sy == 'EOF':
809             s.error("Unclosed string literal", pos = pos)
810         else:
811             s.error(
812                 "Unexpected token %r:%r in string literal" %
813                     (sy, s.systring))
814     if kind == 'c':
815         unicode_value = None
816         bytes_value = chars.getchar()
817         if len(bytes_value) != 1:
818             error(pos, u"invalid character literal: %r" % bytes_value)
819     else:
820         bytes_value, unicode_value = chars.getstrings()
821         if is_python3_source and has_non_ASCII_literal_characters:
822             # Python 3 forbids literal non-ASCII characters in byte strings
823             if kind != 'u':
824                 s.error("bytes can only contain ASCII literal characters.", pos = pos)
825             bytes_value = None
826     s.next()
827     return (kind, bytes_value, unicode_value)
828
829 # list_display      ::=      "[" [listmaker] "]"
830 # listmaker     ::=     expression ( comp_for | ( "," expression )* [","] )
831 # comp_iter     ::=     comp_for | comp_if
832 # comp_for     ::=     "for" expression_list "in" testlist [comp_iter]
833 # comp_if     ::=     "if" test [comp_iter]
834         
835 def p_list_maker(s):
836     # s.sy == '['
837     pos = s.position()
838     s.next()
839     if s.sy == ']':
840         s.expect(']')
841         return ExprNodes.ListNode(pos, args = [])
842     expr = p_test(s)
843     if s.sy == 'for':
844         target = ExprNodes.ListNode(pos, args = [])
845         append = ExprNodes.ComprehensionAppendNode(
846             pos, expr=expr, target=ExprNodes.CloneNode(target))
847         loop = p_comp_for(s, append)
848         s.expect(']')
849         return ExprNodes.ComprehensionNode(
850             pos, loop=loop, append=append, target=target,
851             # list comprehensions leak their loop variable in Py2
852             has_local_scope = s.context.language_level >= 3)
853     else:
854         if s.sy == ',':
855             s.next()
856             exprs = p_simple_expr_list(s, expr)
857         else:
858             exprs = [expr]
859         s.expect(']')
860         return ExprNodes.ListNode(pos, args = exprs)
861         
862 def p_comp_iter(s, body):
863     if s.sy == 'for':
864         return p_comp_for(s, body)
865     elif s.sy == 'if':
866         return p_comp_if(s, body)
867     else:
868         # insert the 'append' operation into the loop
869         return body
870
871 def p_comp_for(s, body):
872     # s.sy == 'for'
873     pos = s.position()
874     s.next()
875     kw = p_for_bounds(s, allow_testlist=False)
876     kw['else_clause'] = None
877     kw['body'] = p_comp_iter(s, body)
878     return Nodes.ForStatNode(pos, **kw)
879         
880 def p_comp_if(s, body):
881     # s.sy == 'if'
882     pos = s.position()
883     s.next()
884     test = p_test_nocond(s)
885     return Nodes.IfStatNode(pos, 
886         if_clauses = [Nodes.IfClauseNode(pos, condition = test,
887                                          body = p_comp_iter(s, body))],
888         else_clause = None )
889
890 #dictmaker: test ':' test (',' test ':' test)* [',']
891
892 def p_dict_or_set_maker(s):
893     # s.sy == '{'
894     pos = s.position()
895     s.next()
896     if s.sy == '}':
897         s.next()
898         return ExprNodes.DictNode(pos, key_value_pairs = [])
899     item = p_test(s)
900     if s.sy == ',' or s.sy == '}':
901         # set literal
902         values = [item]
903         while s.sy == ',':
904             s.next()
905             if s.sy == '}':
906                 break
907             values.append( p_test(s) )
908         s.expect('}')
909         return ExprNodes.SetNode(pos, args=values)
910     elif s.sy == 'for':
911         # set comprehension
912         target = ExprNodes.SetNode(pos, args=[])
913         append = ExprNodes.ComprehensionAppendNode(
914             item.pos, expr=item, target=ExprNodes.CloneNode(target))
915         loop = p_comp_for(s, append)
916         s.expect('}')
917         return ExprNodes.ComprehensionNode(
918             pos, loop=loop, append=append, target=target)
919     elif s.sy == ':':
920         # dict literal or comprehension
921         key = item
922         s.next()
923         value = p_test(s)
924         if s.sy == 'for':
925             # dict comprehension
926             target = ExprNodes.DictNode(pos, key_value_pairs = [])
927             append = ExprNodes.DictComprehensionAppendNode(
928                 item.pos, key_expr=key, value_expr=value,
929                 target=ExprNodes.CloneNode(target))
930             loop = p_comp_for(s, append)
931             s.expect('}')
932             return ExprNodes.ComprehensionNode(
933                 pos, loop=loop, append=append, target=target)
934         else:
935             # dict literal
936             items = [ExprNodes.DictItemNode(key.pos, key=key, value=value)]
937             while s.sy == ',':
938                 s.next()
939                 if s.sy == '}':
940                     break
941                 key = p_test(s)
942                 s.expect(':')
943                 value = p_test(s)
944                 items.append(
945                     ExprNodes.DictItemNode(key.pos, key=key, value=value))
946             s.expect('}')
947             return ExprNodes.DictNode(pos, key_value_pairs=items)
948     else:
949         # raise an error
950         s.expect('}')
951     return ExprNodes.DictNode(pos, key_value_pairs = [])
952
953 # NOTE: no longer in Py3 :)
954 def p_backquote_expr(s):
955     # s.sy == '`'
956     pos = s.position()
957     s.next()
958     args = [p_test(s)]
959     while s.sy == ',':
960         s.next()
961         args.append(p_test(s))
962     s.expect('`')
963     if len(args) == 1:
964         arg = args[0]
965     else:
966         arg = ExprNodes.TupleNode(pos, args = args)
967     return ExprNodes.BackquoteNode(pos, arg = arg)
968
969 def p_simple_expr_list(s, expr=None):
970     exprs = expr is not None and [expr] or []
971     while s.sy not in expr_terminators:
972         exprs.append( p_test(s) )
973         if s.sy != ',':
974             break
975         s.next()
976     return exprs
977
978 def p_test_or_starred_expr_list(s, expr=None):
979     exprs = expr is not None and [expr] or []
980     while s.sy not in expr_terminators:
981         exprs.append( p_test_or_starred_expr(s) )
982         if s.sy != ',':
983             break
984         s.next()
985     return exprs
986     
987
988 #testlist: test (',' test)* [',']
989
990 def p_testlist(s):
991     pos = s.position()
992     expr = p_test(s)
993     if s.sy == ',':
994         s.next()
995         exprs = p_simple_expr_list(s, expr)
996         return ExprNodes.TupleNode(pos, args = exprs)
997     else:
998         return expr
999
1000 # testlist_star_expr: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )
1001
1002 def p_testlist_star_expr(s):
1003     pos = s.position()
1004     expr = p_test_or_starred_expr(s)
1005     if s.sy == ',':
1006         s.next()
1007         exprs = p_test_or_starred_expr_list(s, expr)
1008         return ExprNodes.TupleNode(pos, args = exprs)
1009     else:
1010         return expr
1011
1012 # testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )
1013
1014 def p_testlist_comp(s):
1015     pos = s.position()
1016     expr = p_test_or_starred_expr(s)
1017     if s.sy == ',':
1018         s.next()
1019         exprs = p_test_or_starred_expr_list(s, expr)
1020         return ExprNodes.TupleNode(pos, args = exprs)
1021     elif s.sy == 'for':
1022         return p_genexp(s, expr)
1023     else:
1024         return expr
1025
1026 def p_genexp(s, expr):
1027     # s.sy == 'for'
1028     loop = p_comp_for(s, Nodes.ExprStatNode(
1029         expr.pos, expr = ExprNodes.YieldExprNode(expr.pos, arg=expr)))
1030     return ExprNodes.GeneratorExpressionNode(expr.pos, loop=loop)
1031
1032 expr_terminators = (')', ']', '}', ':', '=', 'NEWLINE')
1033
1034 #-------------------------------------------------------
1035 #
1036 #   Statements
1037 #
1038 #-------------------------------------------------------
1039
1040 def p_global_statement(s):
1041     # assume s.sy == 'global'
1042     pos = s.position()
1043     s.next()
1044     names = p_ident_list(s)
1045     return Nodes.GlobalNode(pos, names = names)
1046
1047 def p_expression_or_assignment(s):
1048     expr_list = [p_testlist_star_expr(s)]
1049     while s.sy == '=':
1050         s.next()
1051         if s.sy == 'yield':
1052             expr = p_yield_expression(s)
1053         else:
1054             expr = p_testlist_star_expr(s)
1055         expr_list.append(expr)
1056     if len(expr_list) == 1:
1057         if re.match(r"([+*/\%^\&|-]|<<|>>|\*\*|//)=", s.sy):
1058             lhs = expr_list[0]
1059             if not isinstance(lhs, (ExprNodes.AttributeNode, ExprNodes.IndexNode, ExprNodes.NameNode) ):
1060                 error(lhs.pos, "Illegal operand for inplace operation.")
1061             operator = s.sy[:-1]
1062             s.next()
1063             if s.sy == 'yield':
1064                 rhs = p_yield_expression(s)
1065             else:
1066                 rhs = p_testlist(s)
1067             return Nodes.InPlaceAssignmentNode(lhs.pos, operator = operator, lhs = lhs, rhs = rhs)
1068         expr = expr_list[0]
1069         if isinstance(expr, (ExprNodes.UnicodeNode, ExprNodes.StringNode, ExprNodes.BytesNode)):
1070             return Nodes.PassStatNode(expr.pos)
1071         else:
1072             return Nodes.ExprStatNode(expr.pos, expr = expr)
1073
1074     rhs = expr_list[-1]
1075     if len(expr_list) == 2:
1076         return Nodes.SingleAssignmentNode(rhs.pos, 
1077             lhs = expr_list[0], rhs = rhs)
1078     else:
1079         return Nodes.CascadedAssignmentNode(rhs.pos,
1080             lhs_list = expr_list[:-1], rhs = rhs)
1081
1082 def p_print_statement(s):
1083     # s.sy == 'print'
1084     pos = s.position()
1085     ends_with_comma = 0
1086     s.next()
1087     if s.sy == '>>':
1088         s.next()
1089         stream = p_test(s)
1090         if s.sy == ',':
1091             s.next()
1092             ends_with_comma = s.sy in ('NEWLINE', 'EOF')
1093     else:
1094         stream = None
1095     args = []
1096     if s.sy not in ('NEWLINE', 'EOF'):
1097         args.append(p_test(s))
1098         while s.sy == ',':
1099             s.next()
1100             if s.sy in ('NEWLINE', 'EOF'):
1101                 ends_with_comma = 1
1102                 break
1103             args.append(p_test(s))
1104     arg_tuple = ExprNodes.TupleNode(pos, args = args)
1105     return Nodes.PrintStatNode(pos,
1106         arg_tuple = arg_tuple, stream = stream,
1107         append_newline = not ends_with_comma)
1108
1109 def p_exec_statement(s):
1110     # s.sy == 'exec'
1111     pos = s.position()
1112     s.next()
1113     args = [ p_bit_expr(s) ]
1114     if s.sy == 'in':
1115         s.next()
1116         args.append(p_test(s))
1117         if s.sy == ',':
1118             s.next()
1119             args.append(p_test(s))
1120     else:
1121         error(pos, "'exec' currently requires a target mapping (globals/locals)")
1122     return Nodes.ExecStatNode(pos, args = args)
1123
1124 def p_del_statement(s):
1125     # s.sy == 'del'
1126     pos = s.position()
1127     s.next()
1128     # FIXME: 'exprlist' in Python
1129     args = p_simple_expr_list(s)
1130     return Nodes.DelStatNode(pos, args = args)
1131
1132 def p_pass_statement(s, with_newline = 0):
1133     pos = s.position()
1134     s.expect('pass')
1135     if with_newline:
1136         s.expect_newline("Expected a newline")
1137     return Nodes.PassStatNode(pos)
1138
1139 def p_break_statement(s):
1140     # s.sy == 'break'
1141     pos = s.position()
1142     s.next()
1143     return Nodes.BreakStatNode(pos)
1144
1145 def p_continue_statement(s):
1146     # s.sy == 'continue'
1147     pos = s.position()
1148     s.next()
1149     return Nodes.ContinueStatNode(pos)
1150
1151 def p_return_statement(s):
1152     # s.sy == 'return'
1153     pos = s.position()
1154     s.next()
1155     if s.sy not in statement_terminators:
1156         value = p_testlist(s)
1157     else:
1158         value = None
1159     return Nodes.ReturnStatNode(pos, value = value)
1160
1161 def p_raise_statement(s):
1162     # s.sy == 'raise'
1163     pos = s.position()
1164     s.next()
1165     exc_type = None
1166     exc_value = None
1167     exc_tb = None
1168     if s.sy not in statement_terminators:
1169         exc_type = p_test(s)
1170         if s.sy == ',':
1171             s.next()
1172             exc_value = p_test(s)
1173             if s.sy == ',':
1174                 s.next()
1175                 exc_tb = p_test(s)
1176     if exc_type or exc_value or exc_tb:
1177         return Nodes.RaiseStatNode(pos, 
1178             exc_type = exc_type,
1179             exc_value = exc_value,
1180             exc_tb = exc_tb)
1181     else:
1182         return Nodes.ReraiseStatNode(pos)
1183
1184 def p_import_statement(s):
1185     # s.sy in ('import', 'cimport')
1186     pos = s.position()
1187     kind = s.sy
1188     s.next()
1189     items = [p_dotted_name(s, as_allowed = 1)]
1190     while s.sy == ',':
1191         s.next()
1192         items.append(p_dotted_name(s, as_allowed = 1))
1193     stats = []
1194     for pos, target_name, dotted_name, as_name in items:
1195         dotted_name = EncodedString(dotted_name)
1196         if kind == 'cimport':
1197             stat = Nodes.CImportStatNode(pos, 
1198                 module_name = dotted_name,
1199                 as_name = as_name)
1200         else:
1201             if as_name and "." in dotted_name:
1202                 name_list = ExprNodes.ListNode(pos, args = [
1203                         ExprNodes.IdentifierStringNode(pos, value = EncodedString("*"))])
1204             else:
1205                 name_list = None
1206             stat = Nodes.SingleAssignmentNode(pos,
1207                 lhs = ExprNodes.NameNode(pos, 
1208                     name = as_name or target_name),
1209                 rhs = ExprNodes.ImportNode(pos, 
1210                     module_name = ExprNodes.IdentifierStringNode(
1211                         pos, value = dotted_name),
1212                     name_list = name_list))
1213         stats.append(stat)
1214     return Nodes.StatListNode(pos, stats = stats)
1215
1216 def p_from_import_statement(s, first_statement = 0):
1217     # s.sy == 'from'
1218     pos = s.position()
1219     s.next()
1220     (dotted_name_pos, _, dotted_name, _) = \
1221         p_dotted_name(s, as_allowed = 0)
1222     if s.sy in ('import', 'cimport'):
1223         kind = s.sy
1224         s.next()
1225     else:
1226         s.error("Expected 'import' or 'cimport'")
1227     is_cimport = kind == 'cimport'
1228     is_parenthesized = False
1229     if s.sy == '*':
1230         imported_names = [(s.position(), "*", None, None)]
1231         s.next()
1232     else:
1233         if s.sy == '(':
1234             is_parenthesized = True
1235             s.next()
1236         imported_names = [p_imported_name(s, is_cimport)]
1237     while s.sy == ',':
1238         s.next()
1239         if is_parenthesized and s.sy == ')':
1240             break
1241         imported_names.append(p_imported_name(s, is_cimport))
1242     if is_parenthesized:
1243         s.expect(')')
1244     dotted_name = EncodedString(dotted_name)
1245     if dotted_name == '__future__':
1246         if not first_statement:
1247             s.error("from __future__ imports must occur at the beginning of the file")
1248         else:
1249             for (name_pos, name, as_name, kind) in imported_names:
1250                 if name == "braces":
1251                     s.error("not a chance", name_pos)
1252                     break
1253                 try:
1254                     directive = getattr(Future, name)
1255                 except AttributeError:
1256                     s.error("future feature %s is not defined" % name, name_pos)
1257                     break
1258                 s.context.future_directives.add(directive)
1259         return Nodes.PassStatNode(pos)
1260     elif kind == 'cimport':
1261         return Nodes.FromCImportStatNode(pos,
1262             module_name = dotted_name,
1263             imported_names = imported_names)
1264     else:
1265         imported_name_strings = []
1266         items = []
1267         for (name_pos, name, as_name, kind) in imported_names:
1268             encoded_name = EncodedString(name)
1269             imported_name_strings.append(
1270                 ExprNodes.IdentifierStringNode(name_pos, value = encoded_name))
1271             items.append(
1272                 (name,
1273                  ExprNodes.NameNode(name_pos, 
1274                                     name = as_name or name)))
1275         import_list = ExprNodes.ListNode(
1276             imported_names[0][0], args = imported_name_strings)
1277         dotted_name = EncodedString(dotted_name)
1278         return Nodes.FromImportStatNode(pos,
1279             module = ExprNodes.ImportNode(dotted_name_pos,
1280                 module_name = ExprNodes.IdentifierStringNode(pos, value = dotted_name),
1281                 name_list = import_list),
1282             items = items)
1283
1284 imported_name_kinds = ('class', 'struct', 'union')
1285
1286 def p_imported_name(s, is_cimport):
1287     pos = s.position()
1288     kind = None
1289     if is_cimport and s.systring in imported_name_kinds:
1290         kind = s.systring
1291         s.next()
1292     name = p_ident(s)
1293     as_name = p_as_name(s)
1294     return (pos, name, as_name, kind)
1295
1296 def p_dotted_name(s, as_allowed):
1297     pos = s.position()
1298     target_name = p_ident(s)
1299     as_name = None
1300     names = [target_name]
1301     while s.sy == '.':
1302         s.next()
1303         names.append(p_ident(s))
1304     if as_allowed:
1305         as_name = p_as_name(s)
1306     return (pos, target_name, u'.'.join(names), as_name)
1307
1308 def p_as_name(s):
1309     if s.sy == 'IDENT' and s.systring == 'as':
1310         s.next()
1311         return p_ident(s)
1312     else:
1313         return None
1314
1315 def p_assert_statement(s):
1316     # s.sy == 'assert'
1317     pos = s.position()
1318     s.next()
1319     cond = p_test(s)
1320     if s.sy == ',':
1321         s.next()
1322         value = p_test(s)
1323     else:
1324         value = None
1325     return Nodes.AssertStatNode(pos, cond = cond, value = value)
1326
1327 statement_terminators = (';', 'NEWLINE', 'EOF')
1328
1329 def p_if_statement(s):
1330     # s.sy == 'if'
1331     pos = s.position()
1332     s.next()
1333     if_clauses = [p_if_clause(s)]
1334     while s.sy == 'elif':
1335         s.next()
1336         if_clauses.append(p_if_clause(s))
1337     else_clause = p_else_clause(s)
1338     return Nodes.IfStatNode(pos,
1339         if_clauses = if_clauses, else_clause = else_clause)
1340
1341 def p_if_clause(s):
1342     pos = s.position()
1343     test = p_test(s)
1344     body = p_suite(s)
1345     return Nodes.IfClauseNode(pos,
1346         condition = test, body = body)
1347
1348 def p_else_clause(s):
1349     if s.sy == 'else':
1350         s.next()
1351         return p_suite(s)
1352     else:
1353         return None
1354
1355 def p_while_statement(s):
1356     # s.sy == 'while'
1357     pos = s.position()
1358     s.next()
1359     test = p_test(s)
1360     body = p_suite(s)
1361     else_clause = p_else_clause(s)
1362     return Nodes.WhileStatNode(pos, 
1363         condition = test, body = body, 
1364         else_clause = else_clause)
1365
1366 def p_for_statement(s):
1367     # s.sy == 'for'
1368     pos = s.position()
1369     s.next()
1370     kw = p_for_bounds(s, allow_testlist=True)
1371     kw['body'] = p_suite(s)
1372     kw['else_clause'] = p_else_clause(s)
1373     return Nodes.ForStatNode(pos, **kw)
1374             
1375 def p_for_bounds(s, allow_testlist=True):
1376     target = p_for_target(s)
1377     if s.sy == 'in':
1378         s.next()
1379         iterator = p_for_iterator(s, allow_testlist)
1380         return { 'target': target, 'iterator': iterator }
1381     elif not s.in_python_file:
1382         if s.sy == 'from':
1383             s.next()
1384             bound1 = p_bit_expr(s)
1385         else:
1386             # Support shorter "for a <= x < b" syntax
1387             bound1, target = target, None
1388         rel1 = p_for_from_relation(s)
1389         name2_pos = s.position()
1390         name2 = p_ident(s)
1391         rel2_pos = s.position()
1392         rel2 = p_for_from_relation(s)
1393         bound2 = p_bit_expr(s)
1394         step = p_for_from_step(s)
1395         if target is None:
1396             target = ExprNodes.NameNode(name2_pos, name = name2)
1397         else:
1398             if not target.is_name:
1399                 error(target.pos, 
1400                     "Target of for-from statement must be a variable name")
1401             elif name2 != target.name:
1402                 error(name2_pos,
1403                     "Variable name in for-from range does not match target")
1404         if rel1[0] != rel2[0]:
1405             error(rel2_pos,
1406                 "Relation directions in for-from do not match")
1407         return {'target': target, 
1408                 'bound1': bound1, 
1409                 'relation1': rel1, 
1410                 'relation2': rel2,
1411                 'bound2': bound2,
1412                 'step': step }
1413     else:
1414         s.expect('in')
1415         return {}
1416
1417 def p_for_from_relation(s):
1418     if s.sy in inequality_relations:
1419         op = s.sy
1420         s.next()
1421         return op
1422     else:
1423         s.error("Expected one of '<', '<=', '>' '>='")
1424
1425 def p_for_from_step(s):
1426     if s.sy == 'by':
1427         s.next()
1428         step = p_bit_expr(s)
1429         return step
1430     else:
1431         return None
1432
1433 inequality_relations = ('<', '<=', '>', '>=')
1434
1435 def p_target(s, terminator):
1436     pos = s.position()
1437     expr = p_starred_expr(s)
1438     if s.sy == ',':
1439         s.next()
1440         exprs = [expr]
1441         while s.sy != terminator:
1442             exprs.append(p_starred_expr(s))
1443             if s.sy != ',':
1444                 break
1445             s.next()
1446         return ExprNodes.TupleNode(pos, args = exprs)
1447     else:
1448         return expr
1449
1450 def p_for_target(s):
1451     return p_target(s, 'in')
1452
1453 def p_for_iterator(s, allow_testlist=True):
1454     pos = s.position()
1455     if allow_testlist:
1456         expr = p_testlist(s)
1457     else:
1458         expr = p_or_test(s)
1459     return ExprNodes.IteratorNode(pos, sequence = expr)
1460
1461 def p_try_statement(s):
1462     # s.sy == 'try'
1463     pos = s.position()
1464     s.next()
1465     body = p_suite(s)
1466     except_clauses = []
1467     else_clause = None
1468     if s.sy in ('except', 'else'):
1469         while s.sy == 'except':
1470             except_clauses.append(p_except_clause(s))
1471         if s.sy == 'else':
1472             s.next()
1473             else_clause = p_suite(s)
1474         body = Nodes.TryExceptStatNode(pos,
1475             body = body, except_clauses = except_clauses,
1476             else_clause = else_clause)
1477         if s.sy != 'finally':
1478             return body
1479         # try-except-finally is equivalent to nested try-except/try-finally
1480     if s.sy == 'finally':
1481         s.next()
1482         finally_clause = p_suite(s)
1483         return Nodes.TryFinallyStatNode(pos,
1484             body = body, finally_clause = finally_clause)
1485     else:
1486         s.error("Expected 'except' or 'finally'")
1487
1488 def p_except_clause(s):
1489     # s.sy == 'except'
1490     pos = s.position()
1491     s.next()
1492     exc_type = None
1493     exc_value = None
1494     if s.sy != ':':
1495         exc_type = p_test(s)
1496         # normalise into list of single exception tests
1497         if isinstance(exc_type, ExprNodes.TupleNode):
1498             exc_type = exc_type.args
1499         else:
1500             exc_type = [exc_type]
1501         if s.sy == ',' or (s.sy == 'IDENT' and s.systring == 'as'):
1502             s.next()
1503             exc_value = p_test(s)
1504         elif s.sy == 'IDENT' and s.systring == 'as':
1505             # Py3 syntax requires a name here
1506             s.next()
1507             pos2 = s.position()
1508             name = p_ident(s)
1509             exc_value = ExprNodes.NameNode(pos2, name = name)
1510     body = p_suite(s)
1511     return Nodes.ExceptClauseNode(pos,
1512         pattern = exc_type, target = exc_value, body = body)
1513
1514 def p_include_statement(s, ctx):
1515     pos = s.position()
1516     s.next() # 'include'
1517     unicode_include_file_name = p_string_literal(s, 'u')[2]
1518     s.expect_newline("Syntax error in include statement")
1519     if s.compile_time_eval:
1520         include_file_name = unicode_include_file_name
1521         include_file_path = s.context.find_include_file(include_file_name, pos)
1522         if include_file_path:
1523             s.included_files.append(include_file_name)
1524             f = Utils.open_source_file(include_file_path, mode="rU")
1525             source_desc = FileSourceDescriptor(include_file_path)
1526             s2 = PyrexScanner(f, source_desc, s, source_encoding=f.encoding, parse_comments=s.parse_comments)
1527             try:
1528                 tree = p_statement_list(s2, ctx)
1529             finally:
1530                 f.close()
1531             return tree
1532         else:
1533             return None
1534     else:
1535         return Nodes.PassStatNode(pos)
1536
1537 def p_with_statement(s):
1538     s.next() # 'with'
1539     if s.systring == 'template' and not s.in_python_file:
1540         node = p_with_template(s)
1541     else:
1542         node = p_with_items(s)
1543     return node
1544
1545 def p_with_items(s):
1546     pos = s.position()
1547     if not s.in_python_file and s.sy == 'IDENT' and s.systring == 'nogil':
1548         state = s.systring
1549         s.next()
1550         if s.sy == ',':
1551             s.next()
1552             body = p_with_items(s)
1553         else:
1554             body = p_suite(s)
1555         return Nodes.GILStatNode(pos, state = state, body = body)
1556     else:
1557         manager = p_test(s)
1558         target = None
1559         if s.sy == 'IDENT' and s.systring == 'as':
1560             s.next()
1561             target = p_starred_expr(s)
1562         if s.sy == ',':
1563             s.next()
1564             body = p_with_items(s)
1565         else:
1566             body = p_suite(s)
1567     return Nodes.WithStatNode(pos, manager = manager, 
1568                               target = target, body = body)
1569
1570 def p_with_template(s):
1571     pos = s.position()
1572     templates = []
1573     s.next()
1574     s.expect('[')
1575     templates.append(s.systring)
1576     s.next()
1577     while s.systring == ',':
1578         s.next()
1579         templates.append(s.systring)
1580         s.next()
1581     s.expect(']')
1582     if s.sy == ':':
1583         s.next()
1584         s.expect_newline("Syntax error in template function declaration")
1585         s.expect_indent()
1586         body_ctx = Ctx()
1587         body_ctx.templates = templates
1588         func_or_var = p_c_func_or_var_declaration(s, pos, body_ctx)
1589         s.expect_dedent()
1590         return func_or_var
1591     else:
1592         error(pos, "Syntax error in template function declaration")
1593
1594 def p_simple_statement(s, first_statement = 0):
1595     #print "p_simple_statement:", s.sy, s.systring ###
1596     if s.sy == 'global':
1597         node = p_global_statement(s)
1598     elif s.sy == 'print':
1599         node = p_print_statement(s)
1600     elif s.sy == 'exec':
1601         node = p_exec_statement(s)
1602     elif s.sy == 'del':
1603         node = p_del_statement(s)
1604     elif s.sy == 'break':
1605         node = p_break_statement(s)
1606     elif s.sy == 'continue':
1607         node = p_continue_statement(s)
1608     elif s.sy == 'return':
1609         node = p_return_statement(s)
1610     elif s.sy == 'raise':
1611         node = p_raise_statement(s)
1612     elif s.sy in ('import', 'cimport'):
1613         node = p_import_statement(s)
1614     elif s.sy == 'from':
1615         node = p_from_import_statement(s, first_statement = first_statement)
1616     elif s.sy == 'yield':
1617         node = p_yield_statement(s)
1618     elif s.sy == 'assert':
1619         node = p_assert_statement(s)
1620     elif s.sy == 'pass':
1621         node = p_pass_statement(s)
1622     else:
1623         node = p_expression_or_assignment(s)
1624     return node
1625
1626 def p_simple_statement_list(s, ctx, first_statement = 0):
1627     # Parse a series of simple statements on one line
1628     # separated by semicolons.
1629     stat = p_simple_statement(s, first_statement = first_statement)
1630     if s.sy == ';':
1631         stats = [stat]
1632         while s.sy == ';':
1633             #print "p_simple_statement_list: maybe more to follow" ###
1634             s.next()
1635             if s.sy in ('NEWLINE', 'EOF'):
1636                 break
1637             stats.append(p_simple_statement(s))
1638         stat = Nodes.StatListNode(stats[0].pos, stats = stats)
1639     s.expect_newline("Syntax error in simple statement list")
1640     return stat
1641
1642 def p_compile_time_expr(s):
1643     old = s.compile_time_expr
1644     s.compile_time_expr = 1
1645     expr = p_testlist(s)
1646     s.compile_time_expr = old
1647     return expr
1648
1649 def p_DEF_statement(s):
1650     pos = s.position()
1651     denv = s.compile_time_env
1652     s.next() # 'DEF'
1653     name = p_ident(s)
1654     s.expect('=')
1655     expr = p_compile_time_expr(s)
1656     value = expr.compile_time_value(denv)
1657     #print "p_DEF_statement: %s = %r" % (name, value) ###
1658     denv.declare(name, value)
1659     s.expect_newline()
1660     return Nodes.PassStatNode(pos)
1661
1662 def p_IF_statement(s, ctx):
1663     pos = s.position()
1664     saved_eval = s.compile_time_eval
1665     current_eval = saved_eval
1666     denv = s.compile_time_env
1667     result = None
1668     while 1:
1669         s.next() # 'IF' or 'ELIF'
1670         expr = p_compile_time_expr(s)
1671         s.compile_time_eval = current_eval and bool(expr.compile_time_value(denv))
1672         body = p_suite(s, ctx)
1673         if s.compile_time_eval:
1674             result = body
1675             current_eval = 0
1676         if s.sy != 'ELIF':
1677             break
1678     if s.sy == 'ELSE':
1679         s.next()
1680         s.compile_time_eval = current_eval
1681         body = p_suite(s, ctx)
1682         if current_eval:
1683             result = body
1684     if not result:
1685         result = Nodes.PassStatNode(pos)
1686     s.compile_time_eval = saved_eval
1687     return result
1688
1689 def p_statement(s, ctx, first_statement = 0):
1690     cdef_flag = ctx.cdef_flag
1691     decorators = None
1692     if s.sy == 'ctypedef':
1693         if ctx.level not in ('module', 'module_pxd'):
1694             s.error("ctypedef statement not allowed here")
1695         #if ctx.api:
1696         #    error(s.position(), "'api' not allowed with 'ctypedef'")
1697         return p_ctypedef_statement(s, ctx)
1698     elif s.sy == 'DEF':
1699         return p_DEF_statement(s)
1700     elif s.sy == 'IF':
1701         return p_IF_statement(s, ctx)
1702     elif s.sy == 'DECORATOR':
1703         if ctx.level not in ('module', 'class', 'c_class', 'function', 'property', 'module_pxd', 'c_class_pxd'):
1704             print ctx.level
1705             s.error('decorator not allowed here')
1706         s.level = ctx.level
1707         decorators = p_decorators(s)
1708         if s.sy not in ('def', 'cdef', 'cpdef', 'class'):
1709             s.error("Decorators can only be followed by functions or classes")
1710     elif s.sy == 'pass' and cdef_flag:
1711         # empty cdef block
1712         return p_pass_statement(s, with_newline = 1)
1713
1714     overridable = 0
1715     if s.sy == 'cdef':
1716         cdef_flag = 1
1717         s.next()
1718     elif s.sy == 'cpdef':
1719         cdef_flag = 1
1720         overridable = 1
1721         s.next()
1722     if cdef_flag:
1723         if ctx.level not in ('module', 'module_pxd', 'function', 'c_class', 'c_class_pxd'):
1724             s.error('cdef statement not allowed here')
1725         s.level = ctx.level
1726         node = p_cdef_statement(s, ctx(overridable = overridable))
1727         if decorators is not None:
1728             if not isinstance(node, (Nodes.CFuncDefNode, Nodes.CVarDefNode, Nodes.CClassDefNode)):
1729                 s.error("Decorators can only be followed by functions or classes")
1730             node.decorators = decorators
1731         return node
1732     else:
1733         if ctx.api:
1734             s.error("'api' not allowed with this statement")
1735         elif s.sy == 'def':
1736             # def statements aren't allowed in pxd files, except
1737             # as part of a cdef class
1738             if ('pxd' in ctx.level) and (ctx.level != 'c_class_pxd'):
1739                 s.error('def statement not allowed here')
1740             s.level = ctx.level
1741             return p_def_statement(s, decorators)
1742         elif s.sy == 'class':
1743             if ctx.level != 'module':
1744                 s.error("class definition not allowed here")
1745             return p_class_statement(s, decorators)
1746         elif s.sy == 'include':
1747             if ctx.level not in ('module', 'module_pxd'):
1748                 s.error("include statement not allowed here")
1749             return p_include_statement(s, ctx)
1750         elif ctx.level == 'c_class' and s.sy == 'IDENT' and s.systring == 'property':
1751             return p_property_decl(s)
1752         elif s.sy == 'pass' and ctx.level != 'property':
1753             return p_pass_statement(s, with_newline = 1)
1754         else:
1755             if ctx.level in ('c_class_pxd', 'property'):
1756                 s.error("Executable statement not allowed here")
1757             if s.sy == 'if':
1758                 return p_if_statement(s)
1759             elif s.sy == 'while':
1760                 return p_while_statement(s)
1761             elif s.sy == 'for':
1762                 return p_for_statement(s)
1763             elif s.sy == 'try':
1764                 return p_try_statement(s)
1765             elif s.sy == 'with':
1766                 return p_with_statement(s)
1767             else:
1768                 return p_simple_statement_list(
1769                     s, ctx, first_statement = first_statement)
1770
1771 def p_statement_list(s, ctx, first_statement = 0):
1772     # Parse a series of statements separated by newlines.
1773     pos = s.position()
1774     stats = []
1775     while s.sy not in ('DEDENT', 'EOF'):
1776         stats.append(p_statement(s, ctx, first_statement = first_statement))
1777         first_statement = 0
1778     if len(stats) == 1:
1779         return stats[0]
1780     else:
1781         return Nodes.StatListNode(pos, stats = stats)
1782
1783 def p_suite(s, ctx = Ctx(), with_doc = 0, with_pseudo_doc = 0):
1784     pos = s.position()
1785     s.expect(':')
1786     doc = None
1787     stmts = []
1788     if s.sy == 'NEWLINE':
1789         s.next()
1790         s.expect_indent()
1791         if with_doc or with_pseudo_doc:
1792             doc = p_doc_string(s)
1793         body = p_statement_list(s, ctx)
1794         s.expect_dedent()
1795     else:
1796         if ctx.api:
1797             s.error("'api' not allowed with this statement")
1798         if ctx.level in ('module', 'class', 'function', 'other'):
1799             body = p_simple_statement_list(s, ctx)
1800         else:
1801             body = p_pass_statement(s)
1802             s.expect_newline("Syntax error in declarations")
1803     if with_doc:
1804         return doc, body
1805     else:
1806         return body
1807
1808 def p_positional_and_keyword_args(s, end_sy_set, templates = None):
1809     """
1810     Parses positional and keyword arguments. end_sy_set
1811     should contain any s.sy that terminate the argument list.
1812     Argument expansion (* and **) are not allowed.
1813
1814     Returns: (positional_args, keyword_args)
1815     """
1816     positional_args = []
1817     keyword_args = []
1818     pos_idx = 0
1819
1820     while s.sy not in end_sy_set:
1821         if s.sy == '*' or s.sy == '**':
1822             s.error('Argument expansion not allowed here.')
1823
1824         parsed_type = False
1825         if s.sy == 'IDENT' and s.peek()[0] == '=':
1826             ident = s.systring
1827             s.next() # s.sy is '='
1828             s.next()
1829             if looking_at_expr(s):
1830                 arg = p_test(s)
1831             else:
1832                 base_type = p_c_base_type(s, templates = templates)
1833                 declarator = p_c_declarator(s, empty = 1)
1834                 arg = Nodes.CComplexBaseTypeNode(base_type.pos, 
1835                     base_type = base_type, declarator = declarator)
1836                 parsed_type = True
1837             keyword_node = ExprNodes.IdentifierStringNode(
1838                 arg.pos, value = EncodedString(ident))
1839             keyword_args.append((keyword_node, arg))
1840             was_keyword = True
1841                 
1842         else:
1843             if looking_at_expr(s):
1844                 arg = p_test(s)
1845             else:
1846                 base_type = p_c_base_type(s, templates = templates)
1847                 declarator = p_c_declarator(s, empty = 1)
1848                 arg = Nodes.CComplexBaseTypeNode(base_type.pos, 
1849                     base_type = base_type, declarator = declarator)
1850                 parsed_type = True
1851             positional_args.append(arg)
1852             pos_idx += 1
1853             if len(keyword_args) > 0:
1854                 s.error("Non-keyword arg following keyword arg",
1855                         pos = arg.pos)
1856
1857         if s.sy != ',':
1858             if s.sy not in end_sy_set:
1859                 if parsed_type:
1860                     s.error("Unmatched %s" % " or ".join(end_sy_set))
1861             break
1862         s.next()
1863     return positional_args, keyword_args
1864
1865 def p_c_base_type(s, self_flag = 0, nonempty = 0, templates = None):
1866     # If self_flag is true, this is the base type for the
1867     # self argument of a C method of an extension type.
1868     if s.sy == '(':
1869         return p_c_complex_base_type(s)
1870     else:
1871         return p_c_simple_base_type(s, self_flag, nonempty = nonempty, templates = templates)
1872
1873 def p_calling_convention(s):
1874     if s.sy == 'IDENT' and s.systring in calling_convention_words:
1875         result = s.systring
1876         s.next()
1877         return result
1878     else:
1879         return ""
1880
1881 calling_convention_words = ("__stdcall", "__cdecl", "__fastcall")
1882
1883 def p_c_complex_base_type(s):
1884     # s.sy == '('
1885     pos = s.position()
1886     s.next()
1887     base_type = p_c_base_type(s)
1888     declarator = p_c_declarator(s, empty = 1)
1889     s.expect(')')
1890     return Nodes.CComplexBaseTypeNode(pos, 
1891         base_type = base_type, declarator = declarator)
1892
1893 def p_c_simple_base_type(s, self_flag, nonempty, templates = None):
1894     #print "p_c_simple_base_type: self_flag =", self_flag, nonempty
1895     is_basic = 0
1896     signed = 1
1897     longness = 0
1898     complex = 0
1899     module_path = []
1900     pos = s.position()
1901     if not s.sy == 'IDENT':
1902         error(pos, "Expected an identifier, found '%s'" % s.sy)
1903     if looking_at_base_type(s):
1904         #print "p_c_simple_base_type: looking_at_base_type at", s.position()
1905         is_basic = 1
1906         if s.sy == 'IDENT' and s.systring in special_basic_c_types:
1907             signed, longness = special_basic_c_types[s.systring]
1908             name = s.systring
1909             s.next()
1910         else:
1911             signed, longness = p_sign_and_longness(s)
1912             if s.sy == 'IDENT' and s.systring in basic_c_type_names:
1913                 name = s.systring
1914                 s.next()
1915             else:
1916                 name = 'int'
1917         if s.sy == 'IDENT' and s.systring == 'complex':
1918             complex = 1
1919             s.next()
1920     elif looking_at_dotted_name(s):
1921         #print "p_c_simple_base_type: looking_at_type_name at", s.position()
1922         name = s.systring
1923         s.next()
1924         while s.sy == '.':
1925             module_path.append(name)
1926             s.next()
1927             name = p_ident(s)
1928     else:
1929         name = s.systring
1930         s.next()
1931         if nonempty and s.sy != 'IDENT':
1932             # Make sure this is not a declaration of a variable or function.  
1933             if s.sy == '(':
1934                 s.next()
1935                 if s.sy == '*' or s.sy == '**' or s.sy == '&':
1936                     s.put_back('(', '(')
1937                 else:
1938                     s.put_back('(', '(')
1939                     s.put_back('IDENT', name)
1940                     name = None
1941             elif s.sy not in ('*', '**', '[', '&'):
1942                 s.put_back('IDENT', name)
1943                 name = None
1944
1945     type_node = Nodes.CSimpleBaseTypeNode(pos, 
1946         name = name, module_path = module_path,
1947         is_basic_c_type = is_basic, signed = signed,
1948         complex = complex, longness = longness, 
1949         is_self_arg = self_flag, templates = templates)
1950
1951     if s.sy == '[':
1952         type_node = p_buffer_or_template(s, type_node, templates)
1953     
1954     if s.sy == '.':
1955         s.next()
1956         name = p_ident(s)
1957         type_node = Nodes.CNestedBaseTypeNode(pos, base_type = type_node, name = name)
1958     
1959     return type_node
1960
1961 def p_buffer_or_template(s, base_type_node, templates):
1962     # s.sy == '['
1963     pos = s.position()
1964     s.next()
1965     # Note that buffer_positional_options_count=1, so the only positional argument is dtype. 
1966     # For templated types, all parameters are types. 
1967     positional_args, keyword_args = (
1968         p_positional_and_keyword_args(s, (']',), templates)
1969     )
1970     s.expect(']')
1971
1972     keyword_dict = ExprNodes.DictNode(pos,
1973         key_value_pairs = [
1974             ExprNodes.DictItemNode(pos=key.pos, key=key, value=value)
1975             for key, value in keyword_args
1976         ])
1977     result = Nodes.TemplatedTypeNode(pos,
1978         positional_args = positional_args,
1979         keyword_args = keyword_dict,
1980         base_type_node = base_type_node)
1981     return result
1982     
1983
1984 def looking_at_name(s):
1985     return s.sy == 'IDENT' and not s.systring in calling_convention_words
1986
1987 def looking_at_expr(s):
1988     if s.systring in base_type_start_words:
1989         return False
1990     elif s.sy == 'IDENT':
1991         is_type = False
1992         name = s.systring
1993         dotted_path = []
1994         s.next()
1995         while s.sy == '.':
1996             s.next()
1997             dotted_path.append(s.systring)
1998             s.expect('IDENT')
1999         saved = s.sy, s.systring
2000         if s.sy == 'IDENT':
2001             is_type = True
2002         elif s.sy == '*' or s.sy == '**':
2003             s.next()
2004             is_type = s.sy == ')'
2005             s.put_back(*saved)
2006         elif s.sy == '(':
2007             s.next()
2008             is_type = s.sy == '*'
2009             s.put_back(*saved)
2010         elif s.sy == '[':
2011             s.next()
2012             is_type = s.sy == ']'
2013             s.put_back(*saved)
2014         dotted_path.reverse()
2015         for p in dotted_path:
2016             s.put_back('IDENT', p)
2017             s.put_back('.', '.')
2018         s.put_back('IDENT', name)
2019         return not is_type
2020     else:
2021         return True
2022
2023 def looking_at_base_type(s):
2024     #print "looking_at_base_type?", s.sy, s.systring, s.position()
2025     return s.sy == 'IDENT' and s.systring in base_type_start_words
2026
2027 def looking_at_dotted_name(s):
2028     if s.sy == 'IDENT':
2029         name = s.systring
2030         s.next()
2031         result = s.sy == '.'
2032         s.put_back('IDENT', name)
2033         return result
2034     else:
2035         return 0
2036
2037 basic_c_type_names = ("void", "char", "int", "float", "double", "bint")
2038
2039 special_basic_c_types = {
2040     # name : (signed, longness)
2041     "Py_UNICODE" : (0, 0),
2042     "Py_ssize_t" : (2, 0),
2043     "ssize_t"    : (2, 0),
2044     "size_t"     : (0, 0),
2045 }
2046
2047 sign_and_longness_words = ("short", "long", "signed", "unsigned")
2048
2049 base_type_start_words = \
2050     basic_c_type_names + sign_and_longness_words + tuple(special_basic_c_types)
2051
2052 def p_sign_and_longness(s):
2053     signed = 1
2054     longness = 0
2055     while s.sy == 'IDENT' and s.systring in sign_and_longness_words:
2056         if s.systring == 'unsigned':
2057             signed = 0
2058         elif s.systring == 'signed':
2059             signed = 2
2060         elif s.systring == 'short':
2061             longness = -1
2062         elif s.systring == 'long':
2063             longness += 1
2064         s.next()
2065     return signed, longness
2066
2067 def p_opt_cname(s):
2068     literal = p_opt_string_literal(s, 'u')
2069     if literal is not None:
2070         cname = EncodedString(literal)
2071         cname.encoding = s.source_encoding
2072     else:
2073         cname = None
2074     return cname
2075
2076 def p_c_declarator(s, ctx = Ctx(), empty = 0, is_type = 0, cmethod_flag = 0,
2077                    assignable = 0, nonempty = 0,
2078                    calling_convention_allowed = 0):
2079     # If empty is true, the declarator must be empty. If nonempty is true,
2080     # the declarator must be nonempty. Otherwise we don't care.
2081     # If cmethod_flag is true, then if this declarator declares
2082     # a function, it's a C method of an extension type.
2083     pos = s.position()
2084     if s.sy == '(':
2085         s.next()
2086         if s.sy == ')' or looking_at_name(s):
2087             base = Nodes.CNameDeclaratorNode(pos, name = EncodedString(u""), cname = None)
2088             result = p_c_func_declarator(s, pos, ctx, base, cmethod_flag)
2089         else:
2090             result = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
2091                                     cmethod_flag = cmethod_flag,
2092                                     nonempty = nonempty,
2093                                     calling_convention_allowed = 1)
2094             s.expect(')')
2095     else:
2096         result = p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag,
2097                                        assignable, nonempty)
2098     if not calling_convention_allowed and result.calling_convention and s.sy != '(':
2099         error(s.position(), "%s on something that is not a function"
2100             % result.calling_convention)
2101     while s.sy in ('[', '('):
2102         pos = s.position()
2103         if s.sy == '[':
2104             result = p_c_array_declarator(s, result)
2105         else: # sy == '('
2106             s.next()
2107             result = p_c_func_declarator(s, pos, ctx, result, cmethod_flag)
2108         cmethod_flag = 0
2109     return result
2110
2111 def p_c_array_declarator(s, base):
2112     pos = s.position()
2113     s.next() # '['
2114     if s.sy != ']':
2115         dim = p_testlist(s)
2116     else:
2117         dim = None
2118     s.expect(']')
2119     return Nodes.CArrayDeclaratorNode(pos, base = base, dimension = dim)
2120
2121 def p_c_func_declarator(s, pos, ctx, base, cmethod_flag):
2122     #  Opening paren has already been skipped
2123     args = p_c_arg_list(s, ctx, cmethod_flag = cmethod_flag,
2124                         nonempty_declarators = 0)
2125     ellipsis = p_optional_ellipsis(s)
2126     s.expect(')')
2127     nogil = p_nogil(s)
2128     exc_val, exc_check = p_exception_value_clause(s)
2129     with_gil = p_with_gil(s)
2130     return Nodes.CFuncDeclaratorNode(pos, 
2131         base = base, args = args, has_varargs = ellipsis,
2132         exception_value = exc_val, exception_check = exc_check,
2133         nogil = nogil or ctx.nogil or with_gil, with_gil = with_gil)
2134
2135 supported_overloaded_operators = cython.set([
2136     '+', '-', '*', '/', '%', 
2137     '++', '--', '~', '|', '&', '^', '<<', '>>', ',',
2138     '==', '!=', '>=', '>', '<=', '<',
2139     '[]', '()',
2140 ])
2141
2142 def p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag,
2143                           assignable, nonempty):
2144     pos = s.position()
2145     calling_convention = p_calling_convention(s)
2146     if s.sy == '*':
2147         s.next()
2148         base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
2149                               cmethod_flag = cmethod_flag,
2150                               assignable = assignable, nonempty = nonempty)
2151         result = Nodes.CPtrDeclaratorNode(pos, 
2152             base = base)
2153     elif s.sy == '**': # scanner returns this as a single token
2154         s.next()
2155         base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
2156                               cmethod_flag = cmethod_flag,
2157                               assignable = assignable, nonempty = nonempty)
2158         result = Nodes.CPtrDeclaratorNode(pos,
2159             base = Nodes.CPtrDeclaratorNode(pos,
2160                 base = base))
2161     elif s.sy == '&':
2162         s.next()
2163         base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
2164                               cmethod_flag = cmethod_flag,
2165                               assignable = assignable, nonempty = nonempty)
2166         result = Nodes.CReferenceDeclaratorNode(pos, base = base)
2167     else:
2168         rhs = None
2169         if s.sy == 'IDENT':
2170             name = EncodedString(s.systring)
2171             if empty:
2172                 error(s.position(), "Declarator should be empty")
2173             s.next()
2174             cname = p_opt_cname(s)
2175             if name != 'operator' and s.sy == '=' and assignable:
2176                 s.next()
2177                 rhs = p_test(s)
2178         else:
2179             if nonempty:
2180                 error(s.position(), "Empty declarator")
2181             name = ""
2182             cname = None
2183         if cname is None and ctx.namespace is not None and nonempty:
2184             cname = ctx.namespace + "::" + name
2185         if name == 'operator' and ctx.visibility == 'extern' and nonempty:
2186             op = s.sy
2187             if [c in '+-*/<=>!%&|([^~,' for c in op]:
2188                 s.next()
2189                 # Handle diphthong operators.
2190                 if op == '(':
2191                     s.expect(')')
2192                     op = '()'
2193                 elif op == '[':
2194                     s.expect(']')
2195                     op = '[]'
2196                 if op in ['-', '+', '|', '&'] and s.sy == op:
2197                     op = op*2
2198                     s.next()
2199                 if s.sy == '=':
2200                     op += s.sy
2201                     s.next()
2202                 if op not in supported_overloaded_operators:
2203                     s.error("Overloading operator '%s' not yet supported." % op)
2204                 name = name+op
2205         result = Nodes.CNameDeclaratorNode(pos,
2206             name = name, cname = cname, default = rhs)
2207     result.calling_convention = calling_convention
2208     return result
2209
2210 def p_nogil(s):
2211     if s.sy == 'IDENT' and s.systring == 'nogil':
2212         s.next()
2213         return 1
2214     else:
2215         return 0
2216
2217 def p_with_gil(s):
2218     if s.sy == 'with':
2219         s.next()
2220         s.expect_keyword('gil')
2221         return 1
2222     else:
2223         return 0
2224
2225 def p_exception_value_clause(s):
2226     exc_val = None
2227     exc_check = 0
2228     if s.sy == 'except':
2229         s.next()
2230         if s.sy == '*':
2231             exc_check = 1
2232             s.next()
2233         elif s.sy == '+':
2234             exc_check = '+'
2235             s.next()
2236             if s.sy == 'IDENT':
2237                 name = s.systring
2238                 s.next()
2239                 exc_val = p_name(s, name)
2240         else:
2241             if s.sy == '?':
2242                 exc_check = 1
2243                 s.next()
2244             exc_val = p_test(s)
2245     return exc_val, exc_check
2246
2247 c_arg_list_terminators = ('*', '**', '.', ')')
2248
2249 def p_c_arg_list(s, ctx = Ctx(), in_pyfunc = 0, cmethod_flag = 0,
2250                  nonempty_declarators = 0, kw_only = 0, annotated = 1):
2251     #  Comma-separated list of C argument declarations, possibly empty.
2252     #  May have a trailing comma.
2253     args = []
2254     is_self_arg = cmethod_flag
2255     while s.sy not in c_arg_list_terminators:
2256         args.append(p_c_arg_decl(s, ctx, in_pyfunc, is_self_arg,
2257             nonempty = nonempty_declarators, kw_only = kw_only,
2258             annotated = annotated))
2259         if s.sy != ',':
2260             break
2261         s.next()
2262         is_self_arg = 0
2263     return args
2264
2265 def p_optional_ellipsis(s):
2266     if s.sy == '.':
2267         expect_ellipsis(s)
2268         return 1
2269     else:
2270         return 0
2271
2272 def p_c_arg_decl(s, ctx, in_pyfunc, cmethod_flag = 0, nonempty = 0,
2273                  kw_only = 0, annotated = 1):
2274     pos = s.position()
2275     not_none = or_none = 0
2276     default = None
2277     annotation = None
2278     if s.in_python_file:
2279         # empty type declaration
2280         base_type = Nodes.CSimpleBaseTypeNode(pos,
2281             name = None, module_path = [],
2282             is_basic_c_type = 0, signed = 0,
2283             complex = 0, longness = 0,
2284             is_self_arg = cmethod_flag, templates = None)
2285     else:
2286         base_type = p_c_base_type(s, cmethod_flag, nonempty = nonempty)
2287     declarator = p_c_declarator(s, ctx, nonempty = nonempty)
2288     if s.sy in ('not', 'or') and not s.in_python_file:
2289         kind = s.sy
2290         s.next()
2291         if s.sy == 'IDENT' and s.systring == 'None':
2292             s.next()
2293         else:
2294             s.error("Expected 'None'")
2295         if not in_pyfunc:
2296             error(pos, "'%s None' only allowed in Python functions" % kind)
2297         or_none = kind == 'or'
2298         not_none = kind == 'not'
2299     if annotated and s.sy == ':':
2300         s.next()
2301         annotation = p_test(s)
2302     if s.sy == '=':
2303         s.next()
2304         if 'pxd' in s.level:
2305             if s.sy not in ['*', '?']:
2306                 error(pos, "default values cannot be specified in pxd files, use ? or *")
2307             default = ExprNodes.BoolNode(1)
2308             s.next()
2309         else:
2310             default = p_test(s)
2311     return Nodes.CArgDeclNode(pos,
2312         base_type = base_type,
2313         declarator = declarator,
2314         not_none = not_none,
2315         or_none = or_none,
2316         default = default,
2317         annotation = annotation,
2318         kw_only = kw_only)
2319
2320 def p_api(s):
2321     if s.sy == 'IDENT' and s.systring == 'api':
2322         s.next()
2323         return 1
2324     else:
2325         return 0
2326
2327 def p_cdef_statement(s, ctx):
2328     pos = s.position()
2329     ctx.visibility = p_visibility(s, ctx.visibility)
2330     ctx.api = ctx.api or p_api(s)
2331     if ctx.api:
2332         if ctx.visibility not in ('private', 'public'):
2333             error(pos, "Cannot combine 'api' with '%s'" % ctx.visibility)
2334     if (ctx.visibility == 'extern') and s.sy == 'from':
2335         return p_cdef_extern_block(s, pos, ctx)
2336     elif s.sy == 'import':
2337         s.next()
2338         return p_cdef_extern_block(s, pos, ctx)
2339     elif p_nogil(s):
2340         ctx.nogil = 1
2341         if ctx.overridable:
2342             error(pos, "cdef blocks cannot be declared cpdef")
2343         return p_cdef_block(s, ctx)
2344     elif s.sy == ':':
2345         if ctx.overridable:
2346             error(pos, "cdef blocks cannot be declared cpdef")
2347         return p_cdef_block(s, ctx)
2348     elif s.sy == 'class':
2349         if ctx.level not in ('module', 'module_pxd'):
2350             error(pos, "Extension type definition not allowed here")
2351         if ctx.overridable:
2352             error(pos, "Extension types cannot be declared cpdef")
2353         return p_c_class_definition(s, pos, ctx)
2354     elif s.sy == 'IDENT' and s.systring == 'cppclass':
2355         if ctx.visibility != 'extern':
2356             error(pos, "C++ classes need to be declared extern")
2357         return p_cpp_class_definition(s, pos, ctx)
2358     elif s.sy == 'IDENT' and s.systring in ("struct", "union", "enum", "packed"):
2359         if ctx.level not in ('module', 'module_pxd'):
2360             error(pos, "C struct/union/enum definition not allowed here")
2361         if ctx.overridable:
2362             error(pos, "C struct/union/enum cannot be declared cpdef")
2363         if s.systring == "enum":
2364             return p_c_enum_definition(s, pos, ctx)
2365         else:
2366             return p_c_struct_or_union_definition(s, pos, ctx)
2367     else:
2368         return p_c_func_or_var_declaration(s, pos, ctx)
2369
2370 def p_cdef_block(s, ctx):
2371     return p_suite(s, ctx(cdef_flag = 1))
2372
2373 def p_cdef_extern_block(s, pos, ctx):
2374     if ctx.overridable:
2375         error(pos, "cdef extern blocks cannot be declared cpdef")
2376     include_file = None
2377     s.expect('from')
2378     if s.sy == '*':
2379         s.next()
2380     else:
2381         include_file = p_string_literal(s, 'u')[2]
2382     ctx = ctx(cdef_flag = 1, visibility = 'extern')
2383     if s.systring == "namespace":
2384         s.next()
2385         ctx.namespace = p_string_literal(s, 'u')[2]
2386     if p_nogil(s):
2387         ctx.nogil = 1
2388     body = p_suite(s, ctx)
2389     return Nodes.CDefExternNode(pos,
2390         include_file = include_file,
2391         body = body,
2392         namespace = ctx.namespace)
2393
2394 def p_c_enum_definition(s, pos, ctx):
2395     # s.sy == ident 'enum'
2396     s.next()
2397     if s.sy == 'IDENT':
2398         name = s.systring
2399         s.next()
2400         cname = p_opt_cname(s)
2401         if cname is None and ctx.namespace is not None:
2402             cname = ctx.namespace + "::" + name
2403     else:
2404         name = None
2405         cname = None
2406     items = None
2407     s.expect(':')
2408     items = []
2409     if s.sy != 'NEWLINE':
2410         p_c_enum_line(s, ctx, items)
2411     else:
2412         s.next() # 'NEWLINE'
2413         s.expect_indent()
2414         while s.sy not in ('DEDENT', 'EOF'):
2415             p_c_enum_line(s, ctx, items)
2416         s.expect_dedent()
2417     return Nodes.CEnumDefNode(
2418         pos, name = name, cname = cname, items = items,
2419         typedef_flag = ctx.typedef_flag, visibility = ctx.visibility,
2420         in_pxd = ctx.level == 'module_pxd')
2421
2422 def p_c_enum_line(s, ctx, items):
2423     if s.sy != 'pass':
2424         p_c_enum_item(s, ctx, items)
2425         while s.sy == ',':
2426             s.next()
2427             if s.sy in ('NEWLINE', 'EOF'):
2428                 break
2429             p_c_enum_item(s, ctx, items)
2430     else:
2431         s.next()
2432     s.expect_newline("Syntax error in enum item list")
2433
2434 def p_c_enum_item(s, ctx, items):
2435     pos = s.position()
2436     name = p_ident(s)
2437     cname = p_opt_cname(s)
2438     if cname is None and ctx.namespace is not None:
2439         cname = ctx.namespace + "::" + name
2440     value = None
2441     if s.sy == '=':
2442         s.next()
2443         value = p_test(s)
2444     items.append(Nodes.CEnumDefItemNode(pos, 
2445         name = name, cname = cname, value = value))
2446
2447 def p_c_struct_or_union_definition(s, pos, ctx):
2448     packed = False
2449     if s.systring == 'packed':
2450         packed = True
2451         s.next()
2452         if s.sy != 'IDENT' or s.systring != 'struct':
2453             s.expected('struct')
2454     # s.sy == ident 'struct' or 'union'
2455     kind = s.systring
2456     s.next()
2457     name = p_ident(s)
2458     cname = p_opt_cname(s)
2459     if cname is None and ctx.namespace is not None:
2460         cname = ctx.namespace + "::" + name
2461     attributes = None
2462     if s.sy == ':':
2463         s.next()
2464         s.expect('NEWLINE')
2465         s.expect_indent()
2466         attributes = []
2467         body_ctx = Ctx()
2468         while s.sy != 'DEDENT':
2469             if s.sy != 'pass':
2470                 attributes.append(
2471                     p_c_func_or_var_declaration(s, s.position(), body_ctx))
2472             else:
2473                 s.next()
2474                 s.expect_newline("Expected a newline")
2475         s.expect_dedent()
2476     else:
2477         s.expect_newline("Syntax error in struct or union definition")
2478     return Nodes.CStructOrUnionDefNode(pos, 
2479         name = name, cname = cname, kind = kind, attributes = attributes,
2480         typedef_flag = ctx.typedef_flag, visibility = ctx.visibility,
2481         in_pxd = ctx.level == 'module_pxd', packed = packed)
2482
2483 def p_visibility(s, prev_visibility):
2484     pos = s.position()
2485     visibility = prev_visibility
2486     if s.sy == 'IDENT' and s.systring in ('extern', 'public', 'readonly'):
2487         visibility = s.systring
2488         if prev_visibility != 'private' and visibility != prev_visibility:
2489             s.error("Conflicting visibility options '%s' and '%s'"
2490                 % (prev_visibility, visibility))
2491         s.next()
2492     return visibility
2493     
2494 def p_c_modifiers(s):
2495     if s.sy == 'IDENT' and s.systring in ('inline',):
2496         modifier = s.systring
2497         s.next()
2498         return [modifier] + p_c_modifiers(s)
2499     return []
2500
2501 def p_c_func_or_var_declaration(s, pos, ctx):
2502     cmethod_flag = ctx.level in ('c_class', 'c_class_pxd')
2503     modifiers = p_c_modifiers(s)
2504     base_type = p_c_base_type(s, nonempty = 1, templates = ctx.templates)
2505     declarator = p_c_declarator(s, ctx, cmethod_flag = cmethod_flag,
2506                                 assignable = 1, nonempty = 1)
2507     declarator.overridable = ctx.overridable
2508     if s.sy == ':':
2509         if ctx.level not in ('module', 'c_class', 'module_pxd', 'c_class_pxd') and not ctx.templates:
2510             s.error("C function definition not allowed here")
2511         doc, suite = p_suite(s, Ctx(level = 'function'), with_doc = 1)
2512         result = Nodes.CFuncDefNode(pos,
2513             visibility = ctx.visibility,
2514             base_type = base_type,
2515             declarator = declarator, 
2516             body = suite,
2517             doc = doc,
2518             modifiers = modifiers,
2519             api = ctx.api,
2520             overridable = ctx.overridable)
2521     else:
2522         #if api:
2523         #    s.error("'api' not allowed with variable declaration")
2524         declarators = [declarator]
2525         while s.sy == ',':
2526             s.next()
2527             if s.sy == 'NEWLINE':
2528                 break
2529             declarator = p_c_declarator(s, ctx, cmethod_flag = cmethod_flag,
2530                                         assignable = 1, nonempty = 1)
2531             declarators.append(declarator)
2532         s.expect_newline("Syntax error in C variable declaration")
2533         result = Nodes.CVarDefNode(pos, 
2534             visibility = ctx.visibility,
2535             base_type = base_type,
2536             declarators = declarators,
2537             in_pxd = ctx.level == 'module_pxd',
2538             api = ctx.api,
2539             overridable = ctx.overridable)
2540     return result
2541
2542 def p_ctypedef_statement(s, ctx):
2543     # s.sy == 'ctypedef'
2544     pos = s.position()
2545     s.next()
2546     visibility = p_visibility(s, ctx.visibility)
2547     api = p_api(s)
2548     ctx = ctx(typedef_flag = 1, visibility = visibility)
2549     if api:
2550         ctx.api = 1
2551     if s.sy == 'class':
2552         return p_c_class_definition(s, pos, ctx)
2553     elif s.sy == 'IDENT' and s.systring in ('packed', 'struct', 'union', 'enum'):
2554         if s.systring == 'enum':
2555             return p_c_enum_definition(s, pos, ctx)
2556         else:
2557             return p_c_struct_or_union_definition(s, pos, ctx)
2558     else:
2559         base_type = p_c_base_type(s, nonempty = 1)
2560         if base_type.name is None:
2561             s.error("Syntax error in ctypedef statement")
2562         declarator = p_c_declarator(s, ctx, is_type = 1, nonempty = 1)
2563         s.expect_newline("Syntax error in ctypedef statement")
2564         return Nodes.CTypeDefNode(
2565             pos, base_type = base_type,
2566             declarator = declarator, visibility = visibility,
2567             in_pxd = ctx.level == 'module_pxd')
2568
2569 def p_decorators(s):
2570     decorators = []
2571     while s.sy == 'DECORATOR':
2572         pos = s.position()
2573         s.next()
2574         decstring = p_dotted_name(s, as_allowed=0)[2]
2575         names = decstring.split('.')
2576         decorator = ExprNodes.NameNode(pos, name=EncodedString(names[0]))
2577         for name in names[1:]:
2578             decorator = ExprNodes.AttributeNode(pos,
2579                                            attribute=EncodedString(name),
2580                                            obj=decorator)
2581         if s.sy == '(':
2582             decorator = p_call(s, decorator)
2583         decorators.append(Nodes.DecoratorNode(pos, decorator=decorator))
2584         s.expect_newline("Expected a newline after decorator")
2585     return decorators
2586
2587 def p_def_statement(s, decorators=None):
2588     # s.sy == 'def'
2589     pos = s.position()
2590     s.next()
2591     name = EncodedString( p_ident(s) )
2592     s.expect('(');
2593     args, star_arg, starstar_arg = p_varargslist(s, terminator=')')
2594     s.expect(')')
2595     if p_nogil(s):
2596         error(pos, "Python function cannot be declared nogil")
2597     return_type_annotation = None
2598     if s.sy == '->':
2599         s.next()
2600         return_type_annotation = p_test(s)
2601     doc, body = p_suite(s, Ctx(level = 'function'), with_doc = 1)
2602     return Nodes.DefNode(pos, name = name, args = args, 
2603         star_arg = star_arg, starstar_arg = starstar_arg,
2604         doc = doc, body = body, decorators = decorators,
2605         return_type_annotation = return_type_annotation)
2606
2607 def p_varargslist(s, terminator=')', annotated=1):
2608     args = p_c_arg_list(s, in_pyfunc = 1, nonempty_declarators = 1,
2609                         annotated = annotated)
2610     star_arg = None
2611     starstar_arg = None
2612     if s.sy == '*':
2613         s.next()
2614         if s.sy == 'IDENT':
2615             star_arg = p_py_arg_decl(s, annotated=annotated)
2616         if s.sy == ',':
2617             s.next()
2618             args.extend(p_c_arg_list(s, in_pyfunc = 1,
2619                 nonempty_declarators = 1, kw_only = 1, annotated = annotated))
2620         elif s.sy != terminator:
2621             s.error("Syntax error in Python function argument list")
2622     if s.sy == '**':
2623         s.next()
2624         starstar_arg = p_py_arg_decl(s, annotated=annotated)
2625     return (args, star_arg, starstar_arg)
2626
2627 def p_py_arg_decl(s, annotated = 1):
2628     pos = s.position()
2629     name = p_ident(s)
2630     annotation = None
2631     if annotated and s.sy == ':':
2632         s.next()
2633         annotation = p_test(s)
2634     return Nodes.PyArgDeclNode(pos, name = name, annotation = annotation)
2635
2636 def p_class_statement(s, decorators):
2637     # s.sy == 'class'
2638     pos = s.position()
2639     s.next()
2640     class_name = EncodedString( p_ident(s) )
2641     class_name.encoding = s.source_encoding
2642     arg_tuple = None
2643     keyword_dict = None
2644     starstar_arg = None
2645     if s.sy == '(':
2646         positional_args, keyword_args, star_arg, starstar_arg = \
2647                             p_call_parse_args(s, allow_genexp = False)
2648         arg_tuple, keyword_dict = p_call_build_packed_args(
2649             pos, positional_args, keyword_args, star_arg)
2650     if arg_tuple is None:
2651         # XXX: empty arg_tuple
2652         arg_tuple = ExprNodes.TupleNode(pos, args = [])
2653     doc, body = p_suite(s, Ctx(level = 'class'), with_doc = 1)
2654     return Nodes.PyClassDefNode(pos,
2655         name = class_name,
2656         bases = arg_tuple,
2657         keyword_args = keyword_dict,
2658         starstar_arg = starstar_arg,
2659         doc = doc, body = body, decorators = decorators)
2660
2661 def p_c_class_definition(s, pos,  ctx):
2662     # s.sy == 'class'
2663     s.next()
2664     module_path = []
2665     class_name = p_ident(s)
2666     while s.sy == '.':
2667         s.next()
2668         module_path.append(class_name)
2669         class_name = p_ident(s)
2670     if module_path and ctx.visibility != 'extern':
2671         error(pos, "Qualified class name only allowed for 'extern' C class")
2672     if module_path and s.sy == 'IDENT' and s.systring == 'as':
2673         s.next()
2674         as_name = p_ident(s)
2675     else:
2676         as_name = class_name
2677     objstruct_name = None
2678     typeobj_name = None
2679     base_class_module = None
2680     base_class_name = None
2681     if s.sy == '(':
2682         s.next()
2683         base_class_path = [p_ident(s)]
2684         while s.sy == '.':
2685             s.next()
2686             base_class_path.append(p_ident(s))
2687         if s.sy == ',':
2688             s.error("C class may only have one base class")
2689         s.expect(')')
2690         base_class_module = ".".join(base_class_path[:-1])
2691         base_class_name = base_class_path[-1]
2692     if s.sy == '[':
2693         if ctx.visibility not in ('public', 'extern'):
2694             error(s.position(), "Name options only allowed for 'public' or 'extern' C class")
2695         objstruct_name, typeobj_name = p_c_class_options(s)
2696     if s.sy == ':':
2697         if ctx.level == 'module_pxd':
2698             body_level = 'c_class_pxd'
2699         else:
2700             body_level = 'c_class'
2701         doc, body = p_suite(s, Ctx(level = body_level), with_doc = 1)
2702     else:
2703         s.expect_newline("Syntax error in C class definition")
2704         doc = None
2705         body = None
2706     if ctx.visibility == 'extern':
2707         if not module_path:
2708             error(pos, "Module name required for 'extern' C class")
2709         if typeobj_name:
2710             error(pos, "Type object name specification not allowed for 'extern' C class")
2711     elif ctx.visibility == 'public':
2712         if not objstruct_name:
2713             error(pos, "Object struct name specification required for 'public' C class")
2714         if not typeobj_name:
2715             error(pos, "Type object name specification required for 'public' C class")
2716     elif ctx.visibility == 'private':
2717         if ctx.api:
2718             error(pos, "Only 'public' C class can be declared 'api'")
2719     else:
2720         error(pos, "Invalid class visibility '%s'" % ctx.visibility)
2721     return Nodes.CClassDefNode(pos,
2722         visibility = ctx.visibility,
2723         typedef_flag = ctx.typedef_flag,
2724         api = ctx.api,
2725         module_name = ".".join(module_path),
2726         class_name = class_name,
2727         as_name = as_name,
2728         base_class_module = base_class_module,
2729         base_class_name = base_class_name,
2730         objstruct_name = objstruct_name,
2731         typeobj_name = typeobj_name,
2732         in_pxd = ctx.level == 'module_pxd',
2733         doc = doc,
2734         body = body)
2735
2736 def p_c_class_options(s):
2737     objstruct_name = None
2738     typeobj_name = None
2739     s.expect('[')
2740     while 1:
2741         if s.sy != 'IDENT':
2742             break
2743         if s.systring == 'object':
2744             s.next()
2745             objstruct_name = p_ident(s)
2746         elif s.systring == 'type':
2747             s.next()
2748             typeobj_name = p_ident(s)
2749         if s.sy != ',':
2750             break
2751         s.next()
2752     s.expect(']', "Expected 'object' or 'type'")
2753     return objstruct_name, typeobj_name
2754
2755 def p_property_decl(s):
2756     pos = s.position()
2757     s.next() # 'property'
2758     name = p_ident(s)
2759     doc, body = p_suite(s, Ctx(level = 'property'), with_doc = 1)
2760     return Nodes.PropertyNode(pos, name = name, doc = doc, body = body)
2761
2762 def p_doc_string(s):
2763     if s.sy == 'BEGIN_STRING':
2764         pos = s.position()
2765         kind, bytes_result, unicode_result = p_cat_string_literal(s)
2766         if s.sy != 'EOF':
2767             s.expect_newline("Syntax error in doc string")
2768         if kind in ('u', ''):
2769             return unicode_result
2770         warning(pos, "Python 3 requires docstrings to be unicode strings")
2771         return bytes_result
2772     else:
2773         return None
2774
2775 def p_code(s, level=None):
2776     body = p_statement_list(s, Ctx(level = level), first_statement = 1)
2777     if s.sy != 'EOF':
2778         s.error("Syntax error in statement [%s,%s]" % (
2779             repr(s.sy), repr(s.systring)))
2780     return body
2781
2782 COMPILER_DIRECTIVE_COMMENT_RE = re.compile(r"^#\s*cython:\s*((\w|[.])+\s*=.*)$")
2783
2784 def p_compiler_directive_comments(s):
2785     result = {}
2786     while s.sy == 'commentline':
2787         m = COMPILER_DIRECTIVE_COMMENT_RE.match(s.systring)
2788         if m:
2789             directives = m.group(1).strip()
2790             try:
2791                 result.update( Options.parse_directive_list(
2792                     directives, ignore_unknown=True) )
2793             except ValueError, e:
2794                 s.error(e.args[0], fatal=False)
2795         s.next()
2796     return result
2797
2798 def p_module(s, pxd, full_module_name):
2799     pos = s.position()
2800
2801     directive_comments = p_compiler_directive_comments(s)
2802     s.parse_comments = False
2803
2804     if 'language_level' in directive_comments:
2805         s.context.set_language_level(directive_comments['language_level'])
2806
2807     doc = p_doc_string(s)
2808     if pxd:
2809         level = 'module_pxd'
2810     else:
2811         level = 'module'
2812
2813     body = p_statement_list(s, Ctx(level = level), first_statement = 1)
2814     if s.sy != 'EOF':
2815         s.error("Syntax error in statement [%s,%s]" % (
2816             repr(s.sy), repr(s.systring)))
2817     return ModuleNode(pos, doc = doc, body = body,
2818                       full_module_name = full_module_name,
2819                       directive_comments = directive_comments)
2820
2821 def p_cpp_class_definition(s, pos,  ctx):
2822     # s.sy == 'cppclass'
2823     s.next()
2824     module_path = []
2825     class_name = p_ident(s)
2826     cname = p_opt_cname(s)
2827     if cname is None and ctx.namespace is not None:
2828         cname = ctx.namespace + "::" + class_name
2829     if s.sy == '.':
2830         error(pos, "Qualified class name not allowed C++ class")
2831     if s.sy == '[':
2832         s.next()
2833         templates = [p_ident(s)]
2834         while s.sy == ',':
2835             s.next()
2836             templates.append(p_ident(s))
2837         s.expect(']')
2838     else:
2839         templates = None
2840     if s.sy == '(':
2841         s.next()
2842         base_classes = [p_dotted_name(s, False)[2]]
2843         while s.sy == ',':
2844             s.next()
2845             base_classes.append(p_dotted_name(s, False)[2])
2846         s.expect(')')
2847     else:
2848         base_classes = []
2849     if s.sy == '[':
2850         error(s.position(), "Name options not allowed for C++ class")
2851     if s.sy == ':':
2852         s.next()
2853         s.expect('NEWLINE')
2854         s.expect_indent()
2855         attributes = []
2856         body_ctx = Ctx(visibility = ctx.visibility)
2857         body_ctx.templates = templates
2858         while s.sy != 'DEDENT':
2859             if s.systring == 'cppclass':
2860                 attributes.append(
2861                     p_cpp_class_definition(s, s.position(), body_ctx))
2862             elif s.sy != 'pass':
2863                 attributes.append(
2864                     p_c_func_or_var_declaration(s, s.position(), body_ctx))
2865             else:
2866                 s.next()
2867                 s.expect_newline("Expected a newline")
2868         s.expect_dedent()
2869     else:
2870         attributes = None
2871         s.expect_newline("Syntax error in C++ class definition")
2872     return Nodes.CppClassNode(pos,
2873         name = class_name,
2874         cname = cname,
2875         base_classes = base_classes,
2876         visibility = ctx.visibility,
2877         in_pxd = ctx.level == 'module_pxd',
2878         attributes = attributes,
2879         templates = templates)
2880
2881
2882
2883 #----------------------------------------------
2884 #
2885 #   Debugging
2886 #
2887 #----------------------------------------------
2888
2889 def print_parse_tree(f, node, level, key = None):
2890     from types import ListType, TupleType
2891     from Nodes import Node
2892     ind = "  " * level
2893     if node:
2894         f.write(ind)
2895         if key:
2896             f.write("%s: " % key)
2897         t = type(node)
2898         if t is tuple:
2899             f.write("(%s @ %s\n" % (node[0], node[1]))
2900             for i in xrange(2, len(node)):
2901                 print_parse_tree(f, node[i], level+1)
2902             f.write("%s)\n" % ind)
2903             return
2904         elif isinstance(node, Node):
2905             try:
2906                 tag = node.tag
2907             except AttributeError:
2908                 tag = node.__class__.__name__
2909             f.write("%s @ %s\n" % (tag, node.pos))
2910             for name, value in node.__dict__.items():
2911                 if name != 'tag' and name != 'pos':
2912                     print_parse_tree(f, value, level+1, name)
2913             return
2914         elif t is list:
2915             f.write("[\n")
2916             for i in xrange(len(node)):
2917                 print_parse_tree(f, node[i], level+1)
2918             f.write("%s]\n" % ind)
2919             return
2920     f.write("%s%s\n" % (ind, node))
2921