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