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