Debian Codegraph @

tools/wraptypes/cparser.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 '''Parse a C source file.
4
5 To use, subclass CParser and override its handle_* methods. Then instantiate
6 the class with a string to parse.
7
8 Derived from ANSI C grammar:
9 * Lexicon: http://www.lysator.liu.se/c/ANSI-C-grammar-l.html
10 * Grammar: http://www.lysator.liu.se/c/ANSI-C-grammar-y.html
11
12 Reference is C99:
13 * http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1124.pdf
14
15 '''
16 import cPickle
17 import operator
18 import os.path
19 import re
20 import sys
21 import time
22 import warnings
23
24 import preprocessor
25 import yacc
26
27 tokens = (
28
29 'PP_IF', 'PP_IFDEF', 'PP_IFNDEF', 'PP_ELIF', 'PP_ELSE',
30 'PP_ENDIF', 'PP_INCLUDE', 'PP_DEFINE', 'PP_DEFINE_CONSTANT', 'PP_UNDEF',
31 'PP_LINE', 'PP_ERROR', 'PP_PRAGMA',
32
33 'IDENTIFIER', 'CONSTANT', 'CHARACTER_CONSTANT', 'STRING_LITERAL', 'SIZEOF',
34 'PTR_OP', 'INC_OP', 'DEC_OP', 'LEFT_OP', 'RIGHT_OP', 'LE_OP', 'GE_OP',
35 'EQ_OP', 'NE_OP', 'AND_OP', 'OR_OP', 'MUL_ASSIGN', 'DIV_ASSIGN',
36 'MOD_ASSIGN', 'ADD_ASSIGN', 'SUB_ASSIGN', 'LEFT_ASSIGN', 'RIGHT_ASSIGN',
37 'AND_ASSIGN', 'XOR_ASSIGN', 'OR_ASSIGN', 'HASH_HASH', 'PERIOD',
38 'TYPE_NAME',
39
40 'TYPEDEF', 'EXTERN', 'STATIC', 'AUTO', 'REGISTER',
41 'CHAR', 'SHORT', 'INT', 'LONG', 'SIGNED', 'UNSIGNED', 'FLOAT', 'DOUBLE',
42 'CONST', 'VOLATILE', 'VOID',
43 'STRUCT', 'UNION', 'ENUM', 'ELLIPSIS',
44
45 'CASE', 'DEFAULT', 'IF', 'ELSE', 'SWITCH', 'WHILE', 'DO', 'FOR', 'GOTO',
46 'CONTINUE', 'BREAK', 'RETURN', '__ASM__'
47 )
48
49 keywords = [
50 'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do',
51 'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if', 'int',
52 'long', 'register', 'return', 'short', 'signed', 'sizeof', 'static',
53 'struct', 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile',
54 'while', '__asm__'
55 ]
56
57
58 # --------------------------------------------------------------------------
59 # C Object Model
60 # --------------------------------------------------------------------------
61
62 class Declaration(object):
63 def __init__(self):
64 self.declarator = None
65 self.type = Type()
66 self.storage = None
67
68 def __repr__(self):
69 d = {
70 'declarator': self.declarator,
71 'type': self.type,
72 }
73 if self.storage:
74 d['storage'] = self.storage
75 l = ['%s=%r' % (k, v) for k, v in d.items()]
76 return 'Declaration(%s)' % ', '.join(l)
77
78 class Declarator(object):
79 pointer = None
80 def __init__(self):
81 self.identifier = None
82 self.initializer = None
83 self.array = None
84 self.parameters = None
85
86 # make pointer read-only to catch mistakes early
87 pointer = property(lambda self: None)
88
89 def __repr__(self):
90 s = self.identifier or ''
91 if self.array:
92 s += repr(self.array)
93 if self.initializer:
94 s += ' = %r' % self.initializer
95 if self.parameters is not None:
96 s += '(' + ', '.join([repr(p) for p in self.parameters]) + ')'
97 return s
98
99 class Pointer(Declarator):
100 pointer = None
101 def __init__(self):
102 super().__init__()
103 self.qualifiers = []
104
105 def __repr__(self):
106 q = ''
107 if self.qualifiers:
108 q = '<%s>' % ' '.join(self.qualifiers)
109 return 'POINTER%s(%r)' % (q, self.pointer) + super().__repr__()
110
111 class Array(object):
112 def __init__(self):
113 self.size = None
114 self.array = None
115
116 def __repr__(self):
117 if self.size:
118 a = '[%r]' % self.size
119 else:
120 a = '[]'
121 if self.array:
122 return repr(self.array) + a
123 else:
124 return a
125
126 class Parameter(object):
127 def __init__(self):
128 self.type = Type()
129 self.storage = None
130 self.declarator = None
131
132 def __repr__(self):
133 d = {
134 'type': self.type,
135 }
136 if self.declarator:
137 d['declarator'] = self.declarator
138 if self.storage:
139 d['storage'] = self.storage
140 l = ['%s=%r' % (k, v) for k, v in d.items()]
141 return 'Parameter(%s)' % ', '.join(l)
142
143
144 class Type(object):
145 def __init__(self):
146 self.qualifiers = []
147 self.specifiers = []
148
149 def __repr__(self):
150 return ' '.join(self.qualifiers + [str(s) for s in self.specifiers])
151
152 # These are used only internally.
153
154 class StorageClassSpecifier(str):
155 pass
156
157 class TypeSpecifier(str):
158 pass
159
160 class StructTypeSpecifier(object):
161 def __init__(self, is_union, tag, declarations):
162 self.is_union = is_union
163 self.tag = tag
164 self.declarations = declarations
165
166 def __repr__(self):
167 if self.is_union:
168 s = 'union'
169 else:
170 s = 'struct'
171 if self.tag:
172 s += ' %s' % self.tag
173 if self.declarations:
174 s += ' {%s}' % '; '.join([repr(d) for d in self.declarations])
175 return s
176
177 class EnumSpecifier(object):
178 def __init__(self, tag, enumerators):
179 self.tag = tag
180 self.enumerators = enumerators
181
182 def __repr__(self):
183 s = 'enum'
184 if self.tag:
185 s += ' %s' % self.tag
186 if self.enumerators:
187 s += ' {%s}' % ', '.join([repr(e) for e in self.enumerators])
188 return s
189
190 class Enumerator(object):
191 def __init__(self, name, expression):
192 self.name = name
193 self.expression = expression
194
195 def __repr__(self):
196 s = self.name
197 if self.expression:
198 s += ' = %r' % self.expression
199 return s
200
201 class TypeQualifier(str):
202 pass
203
204 def apply_specifiers(specifiers, declaration):
205 '''Apply specifiers to the declaration (declaration may be
206 a Parameter instead).'''
207 for s in specifiers:
208 if type(s) == StorageClassSpecifier:
209 if declaration.storage:
210 p.parser.cparser.handle_error(
211 'Declaration has more than one storage class',
212 '???', p.lineno(1))
213 return
214 declaration.storage = s
215 elif type(s) in (TypeSpecifier, StructTypeSpecifier, EnumSpecifier):
216 declaration.type.specifiers.append(s)
217 elif type(s) == TypeQualifier:
218 declaration.type.qualifiers.append(s)
219
220
221 # --------------------------------------------------------------------------
222 # Expression Object Model
223 # --------------------------------------------------------------------------
224
225 class EvaluationContext(object):
226 '''Interface for evaluating expression nodes.
227 '''
228 def evaluate_identifier(self, name):
229 warnings.warn('Attempt to evaluate identifier "%s" failed' % name)
230 return 0
231
232 def evaluate_sizeof(self, type):
233 warnings.warn('Attempt to evaluate sizeof "%s" failed' % str(type))
234 return 0
235
236 class ExpressionNode(object):
237 def evaluate(self, context):
238 return 0
239
240 def __str__(self):
241 return ''
242
243 class ConstantExpressionNode(ExpressionNode):
244 def __init__(self, value):
245 self.value = value
246
247 def evaluate(self, context):
248 return self.value
249
250 def __str__(self):
251 return str(self.value)
252
253 class IdentifierExpressionNode(ExpressionNode):
254 def __init__(self, name):
255 self.name = name
256
257 def evaluate(self, context):
258 return context.evaluate_identifier(self.name)
259
260 def __str__(self):
261 return str(self.value)
262
263 class UnaryExpressionNode(ExpressionNode):
264 def __init__(self, op, op_str, child):
265 self.op = op
266 self.op_str = op_str
267 self.child = child
268
269 def evaluate(self, context):
270 return self.op(self.child.evaluate(context))
271
272 def __str__(self):
273 return '(%s %s)' % (self.op_str, self.child)
274
275 class SizeOfExpressionNode(ExpressionNode):
276 def __init__(self, type):
277 self.type = type
278
279 def evaluate(self, context):
280 return context.evaluate_sizeof(self.type)
281
282 def __str__(self):
283 return 'sizeof(%s)' % str(self.type)
284
285 class BinaryExpressionNode(ExpressionNode):
286 def __init__(self, op, op_str, left, right):
287 self.op = op
288 self.op_str = op_str
289 self.left = left
290 self.right = right
291
292 def evaluate(self, context):
293 return self.op(self.left.evaluate(context),
294 self.right.evaluate(context))
295
296 def __str__(self):
297 return '(%s %s %s)' % (self.left, self.op_str, self.right)
298
299 class LogicalAndExpressionNode(ExpressionNode):
300 def __init__(self, left, right):
301 self.left = left
302 self.right = right
303
304 def evaluate(self, context):
305 return self.left.evaluate(context) and self.right.evaluate(context)
306
307 def __str__(self):
308 return '(%s && %s)' % (self.left, self.right)
309
310 class LogicalOrExpressionNode(ExpressionNode):
311 def __init__(self, left, right):
312 self.left = left
313 self.right = right
314
315 def evaluate(self, context):
316 return self.left.evaluate(context) or self.right.evaluate(context)
317
318 def __str__(self):
319 return '(%s || %s)' % (self.left, self.right)
320
321 class ConditionalExpressionNode(ExpressionNode):
322 def __init__(self, condition, left, right):
323 self.condition = condition
324 self.left = left
325 self.right = right
326
327 def evaluate(self, context):
328 if self.condition.evaluate(context):
329 return self.left.evaluate(context)
330 else:
331 return self.right.evaluate(context)
332
333 def __str__(self):
334 return '(%s ? %s : %s)' % (self.condition, self.left, self.right)
335
336
337 # --------------------------------------------------------------------------
338 # Grammar
339 # --------------------------------------------------------------------------
340
341 def p_translation_unit(p):
342 '''translation_unit :
343 | translation_unit external_declaration
344 '''
345 # Starting production.
346 # Allow empty production so that files with no declarations are still
347 # valid.
348 # Intentionally empty
349
350 def p_identifier(p):
351 '''identifier : IDENTIFIER'''
352 p[0] = IdentifierExpressionNode(p[1])
353
354 def p_constant(p):
355 '''constant : CONSTANT
356 | CHARACTER_CONSTANT
357 '''
358 def _to_int(s):
359 s = s.rstrip('lLuU')
360 if s.startswith('0x'):
361 return int(s, base=16)
362 elif s.startswith('0'):
363 return int(s, base=8)
364 else:
365 return int(s)
366
367 value = p[1]
368 try:
369 value = _to_int(value)
370 except ValueError:
371 pass
372 p[0] = ConstantExpressionNode(value)
373
374 def p_string_literal(p):
375 '''string_literal : STRING_LITERAL'''
376 p[0] = ConstantExpressionNode(p[1])
377
378 def p_primary_expression(p):
379 '''primary_expression : identifier
380 | constant
381 | string_literal
382 | '(' expression ')'
383 '''
384 if p[1] == '(':
385 p[0] = p[2]
386 else:
387 p[0] = p[1]
388
389 def p_postfix_expression(p):
390 '''postfix_expression : primary_expression
391 | postfix_expression '[' expression ']'
392 | postfix_expression '(' ')'
393 | postfix_expression '(' argument_expression_list ')'
394 | postfix_expression PERIOD IDENTIFIER
395 | postfix_expression PTR_OP IDENTIFIER
396 | postfix_expression INC_OP
397 | postfix_expression DEC_OP
398 '''
399 # XXX Largely unsupported
400 p[0] = p[1]
401
402 def p_argument_expression_list(p):
403 '''argument_expression_list : assignment_expression
404 | argument_expression_list ',' assignment_expression
405 '''
406
407 def p_asm_expression(p):
408 '''asm_expression : __ASM__ volatile_opt '(' string_literal ')'
409 | __ASM__ volatile_opt '(' string_literal ':' str_opt_expr_pair_list ')'
410 | __ASM__ volatile_opt '(' string_literal ':' str_opt_expr_pair_list ':' str_opt_expr_pair_list ')'
411 | __ASM__ volatile_opt '(' string_literal ':' str_opt_expr_pair_list ':' str_opt_expr_pair_list ':' str_opt_expr_pair_list ')'
412 '''
413
414 # Definitely not ISO C, adapted from example ANTLR GCC parser at
415 # http://www.antlr.org/grammar/cgram//grammars/GnuCParser.g
416 # but more lenient (expressions permitted in optional final part, when
417 # they shouldn't be -- avoids shift/reduce conflict with
418 # str_opt_expr_pair_list).
419
420 # XXX node not supported
421 p[0] = ExpressionNode()
422
423 def p_str_opt_expr_pair_list(p):
424 '''str_opt_expr_pair_list :
425 | str_opt_expr_pair
426 | str_opt_expr_pair_list ',' str_opt_expr_pair
427 '''
428
429 def p_str_opt_expr_pair(p):
430 '''str_opt_expr_pair : string_literal
431 | string_literal '(' expression ')'
432 '''
433
434 def p_volatile_opt(p):
435 '''volatile_opt :
436 | VOLATILE
437 '''
438
439 def p_unary_expression(p):
440 '''unary_expression : postfix_expression
441 | INC_OP unary_expression
442 | DEC_OP unary_expression
443 | unary_operator cast_expression
444 | SIZEOF unary_expression
445 | SIZEOF '(' type_name ')'
446 | asm_expression
447 '''
448 if len(p) == 2:
449 p[0] = p[1]
450 elif p[1] == 'sizeof':
451 if p[2] == '(':
452 p[0] = SizeOfExpressionNode(p[3])
453 else:
454 p[0] = SizeOfExpressionNode(p[2])
455 elif type(p[1]) == tuple:
456 # unary_operator reduces to (op, op_str)
457 p[0] = UnaryExpressionNode(p[1][0], p[1][1], p[2])
458 else:
459 # XXX INC_OP and DEC_OP expression nodes not supported
460 p[0] = p[2]
461
462 def p_unary_operator(p):
463 '''unary_operator : '&'
464 | '*'
465 | '+'
466 | '-'
467 | '~'
468 | '!'
469 '''
470 # reduces to (op, op_str)
471 p[0] = ({
472 '+': operator.pos,
473 '-': operator.neg,
474 '~': operator.inv,
475 '!': operator.not_,
476 '&': 'AddressOfUnaryOperator',
477 '*': 'DereferenceUnaryOperator'}[p[1]], p[1])
478
479 def p_cast_expression(p):
480 '''cast_expression : unary_expression
481 | '(' type_name ')' cast_expression
482 '''
483 if len(p) == 2:
484 p[0] = p[1]
485 else:
486 # XXX cast node not supported
487 p[0] = p[4]
488
489 def p_multiplicative_expression(p):
490 '''multiplicative_expression : cast_expression
491 | multiplicative_expression '*' cast_expression
492 | multiplicative_expression '/' cast_expression
493 | multiplicative_expression '%' cast_expression
494 '''
495 if len(p) == 2:
496 p[0] = p[1]
497 else:
498 p[0] = BinaryExpressionNode({
499 '*': operator.mul,
500 '/': operator.div,
501 '%': operator.mod}[p[2]], p[2], p[1], p[3])
502
503 def p_additive_expression(p):
504 '''additive_expression : multiplicative_expression
505 | additive_expression '+' multiplicative_expression
506 | additive_expression '-' multiplicative_expression
507 '''
508 if len(p) == 2:
509 p[0] = p[1]
510 else:
511 p[0] = BinaryExpressionNode({
512 '+': operator.add,
513 '-': operator.sub}[p[2]], p[2], p[1], p[3])
514
515 def p_shift_expression(p):
516 '''shift_expression : additive_expression
517 | shift_expression LEFT_OP additive_expression
518 | shift_expression RIGHT_OP additive_expression
519 '''
520 if len(p) == 2:
521 p[0] = p[1]
522 else:
523 p[0] = BinaryExpressionNode({
524 '<<': operator.lshift,
525 '>>': operator.rshift}[p[2]], p[2], p[1], p[3])
526
527 def p_relational_expression(p):
528 '''relational_expression : shift_expression
529 | relational_expression '<' shift_expression
530 | relational_expression '>' shift_expression
531 | relational_expression LE_OP shift_expression
532 | relational_expression GE_OP shift_expression
533 '''
534 if len(p) == 2:
535 p[0] = p[1]
536 else:
537 p[0] = BinaryExpressionNode({
538 '>': operator.gt,
539 '<': operator.lt,
540 '<=': operator.le,
541 '>=': operator.ge}[p[2]], p[2], p[1], p[3])
542
543 def p_equality_expression(p):
544 '''equality_expression : relational_expression
545 | equality_expression EQ_OP relational_expression
546 | equality_expression NE_OP relational_expression
547 '''
548 if len(p) == 2:
549 p[0] = p[1]
550 else:
551 p[0] = BinaryExpressionNode({
552 '==': operator.eq,
553 '!=': operator.ne}[p[2]], p[2], p[1], p[3])
554
555 def p_and_expression(p):
556 '''and_expression : equality_expression
557 | and_expression '&' equality_expression
558 '''
559 if len(p) == 2:
560 p[0] = p[1]
561 else:
562 p[0] = BinaryExpressionNode(operator.and_, '&', p[1], p[3])
563
564 def p_exclusive_or_expression(p):
565 '''exclusive_or_expression : and_expression
566 | exclusive_or_expression '^' and_expression
567 '''
568 if len(p) == 2:
569 p[0] = p[1]
570 else:
571 p[0] = BinaryExpressionNode(operator.xor, '^', p[1], p[3])
572
573 def p_inclusive_or_expression(p):
574 '''inclusive_or_expression : exclusive_or_expression
575 | inclusive_or_expression '|' exclusive_or_expression
576 '''
577 if len(p) == 2:
578 p[0] = p[1]
579 else:
580 p[0] = BinaryExpressionNode(operator.or_, '|', p[1], p[3])
581
582 def p_logical_and_expression(p):
583 '''logical_and_expression : inclusive_or_expression
584 | logical_and_expression AND_OP inclusive_or_expression
585 '''
586 if len(p) == 2:
587 p[0] = p[1]
588 else:
589 p[0] = LogicalAndExpressionNode(p[1], p[3])
590
591 def p_logical_or_expression(p):
592 '''logical_or_expression : logical_and_expression
593 | logical_or_expression OR_OP logical_and_expression
594 '''
595 if len(p) == 2:
596 p[0] = p[1]
597 else:
598 p[0] = LogicalOrExpressionNode(p[1], p[3])
599
600
601 def p_conditional_expression(p):
602 '''conditional_expression : logical_or_expression
603 | logical_or_expression '?' expression ':' conditional_expression
604 '''
605 if len(p) == 2:
606 p[0] = p[1]
607 else:
608 p[0] = ConditionalExpressionNode(p[1], p[3], p[5])
609
610 def p_assignment_expression(p):
611 '''assignment_expression : conditional_expression
612 | unary_expression assignment_operator assignment_expression
613 '''
614 if len(p) == 2:
615 p[0] = p[1]
616 else:
617 # XXX assignment expression node not supported
618 p[0] = p[3]
619
620 def p_assignment_operator(p):
621 '''assignment_operator : '='
622 | MUL_ASSIGN
623 | DIV_ASSIGN
624 | MOD_ASSIGN
625 | ADD_ASSIGN
626 | SUB_ASSIGN
627 | LEFT_ASSIGN
628 | RIGHT_ASSIGN
629 | AND_ASSIGN
630 | XOR_ASSIGN
631 | OR_ASSIGN
632 '''
633
634 def p_expression(p):
635 '''expression : assignment_expression
636 | expression ',' assignment_expression
637 '''
638 p[0] = p[1]
639 # XXX sequence expression node not supported
640
641 def p_constant_expression(p):
642 '''constant_expression : conditional_expression
643 '''
644 p[0] = p[1]
645
646 def p_declaration(p):
647 '''declaration : declaration_impl ';'
648 '''
649 # The ';' must be here, not in 'declaration', as declaration needs to
650 # be executed before the ';' is shifted (otherwise the next lookahead will
651 # be read, which may be affected by this declaration if its a typedef.
652
653 def p_declaration_impl(p):
654 '''declaration_impl : declaration_specifiers
655 | declaration_specifiers init_declarator_list
656 '''
657 declaration = Declaration()
658 apply_specifiers(p[1], declaration)
659
660 if len(p) == 2:
661 filename = p.slice[1].filename
662 lineno = p.slice[1].lineno
663 p.parser.cparser.impl_handle_declaration(declaration, filename, lineno)
664 return
665
666 filename = p.slice[2].filename
667 lineno = p.slice[2].lineno
668 for declarator in p[2]:
669 declaration.declarator = declarator
670 p.parser.cparser.impl_handle_declaration(declaration, filename, lineno)
671
672 """ # shift/reduce conflict with p_statement_error.
673 def p_declaration_error(p):
674 '''declaration : error ';'
675 '''
676 # Error resynchronisation catch-all
677 """
678
679 def p_declaration_specifiers(p):
680 '''declaration_specifiers : storage_class_specifier
681 | storage_class_specifier declaration_specifiers
682 | type_specifier
683 | type_specifier declaration_specifiers
684 | type_qualifier
685 | type_qualifier declaration_specifiers
686 '''
687 if len(p) > 2:
688 p[0] = (p[1],) + p[2]
689 else:
690 p[0] = (p[1],)
691
692 def p_init_declarator_list(p):
693 '''init_declarator_list : init_declarator
694 | init_declarator_list ',' init_declarator
695 '''
696 if len(p) > 2:
697 p[0] = p[1] + (p[3],)
698 else:
699 p[0] = (p[1],)
700
701 def p_init_declarator(p):
702 '''init_declarator : declarator
703 | declarator '=' initializer
704 '''
705 p[0] = p[1]
706 if len(p) > 2:
707 p[0].initializer = p[2]
708
709 def p_storage_class_specifier(p):
710 '''storage_class_specifier : TYPEDEF
711 | EXTERN
712 | STATIC
713 | AUTO
714 | REGISTER
715 '''
716 p[0] = StorageClassSpecifier(p[1])
717
718 def p_type_specifier(p):
719 '''type_specifier : VOID
720 | CHAR
721 | SHORT
722 | INT
723 | LONG
724 | FLOAT
725 | DOUBLE
726 | SIGNED
727 | UNSIGNED
728 | struct_or_union_specifier
729 | enum_specifier
730 | TYPE_NAME
731 '''
732 if type(p[1]) in (StructTypeSpecifier, EnumSpecifier):
733 p[0] = p[1]
734 else:
735 p[0] = TypeSpecifier(p[1])
736 # TODO enum
737
738 def p_struct_or_union_specifier(p):
739 '''struct_or_union_specifier : struct_or_union IDENTIFIER '{' struct_declaration_list '}'
740 | struct_or_union TYPE_NAME '{' struct_declaration_list '}'
741 | struct_or_union '{' struct_declaration_list '}'
742 | struct_or_union IDENTIFIER
743 | struct_or_union TYPE_NAME
744 '''
745 # The TYPE_NAME ones are dodgy, needed for Apple headers
746 # CoreServices.framework/Frameworks/CarbonCore.framework/Headers/Files.h.
747 # CoreServices.framework/Frameworks/OSServices.framework/Headers/Power.h
748 if len(p) == 3:
749 p[0] = StructTypeSpecifier(p[1], p[2], None)
750 elif p[2] == '{':
751 p[0] = StructTypeSpecifier(p[1], '', p[3])
752 else:
753 p[0] = StructTypeSpecifier(p[1], p[2], p[4])
754
755 def p_struct_or_union(p):
756 '''struct_or_union : STRUCT
757 | UNION
758 '''
759 p[0] = p[1] == 'union'
760
761 def p_struct_declaration_list(p):
762 '''struct_declaration_list : struct_declaration
763 | struct_declaration_list struct_declaration
764 '''
765 if len(p) == 2:
766 p[0] = p[1]
767 else:
768 p[0] = p[1] + p[2]
769
770 def p_struct_declaration(p):
771 '''struct_declaration : specifier_qualifier_list struct_declarator_list ';'
772 '''
773 # p[0] returned is a tuple, to handle multiple declarators in one
774 # declaration.
775 r = ()
776 for declarator in p[2]:
777 declaration = Declaration()
778 apply_specifiers(p[1], declaration)
779 declaration.declarator = declarator
780 r += (declaration,)
781 p[0] = r
782
783 def p_specifier_qualifier_list(p):
784 '''specifier_qualifier_list : type_specifier specifier_qualifier_list
785 | type_specifier
786 | type_qualifier specifier_qualifier_list
787 | type_qualifier
788 '''
789 # XXX Interesting.. why is this one right-recursion?
790 if len(p) == 3:
791 p[0] = (p[1],) + p[2]
792 else:
793 p[0] = (p[1],)
794
795 def p_struct_declarator_list(p):
796 '''struct_declarator_list : struct_declarator
797 | struct_declarator_list ',' struct_declarator
798 '''
799 if len(p) == 2:
800 p[0] = (p[1],)
801 else:
802 p[0] = p[1] + (p[3],)
803
804 def p_struct_declarator(p):
805 '''struct_declarator : declarator
806 | ':' constant_expression
807 | declarator ':' constant_expression
808 '''
809 # XXX ignoring bitfields.
810 if p[1] == ':':
811 p[0] = Declarator()
812 else:
813 p[0] = p[1]
814
815 def p_enum_specifier(p):
816 '''enum_specifier : ENUM '{' enumerator_list '}'
817 | ENUM IDENTIFIER '{' enumerator_list '}'
818 | ENUM IDENTIFIER
819 '''
820 if len(p) == 5:
821 p[0] = EnumSpecifier(None, p[3])
822 elif len(p) == 6:
823 p[0] = EnumSpecifier(p[2], p[4])
824 else:
825 p[0] = EnumSpecifier(p[2], ())
826
827 def p_enumerator_list(p):
828 '''enumerator_list : enumerator_list_iso
829 | enumerator_list_iso ','
830 '''
831 # Apple headers sometimes have trailing ',' after enumerants, which is
832 # not ISO C.
833 p[0] = p[1]
834
835 def p_enumerator_list_iso(p):
836 '''enumerator_list_iso : enumerator
837 | enumerator_list_iso ',' enumerator
838 '''
839 if len(p) == 2:
840 p[0] = (p[1],)
841 else:
842 p[0] = p[1] + (p[3],)
843
844 def p_enumerator(p):
845 '''enumerator : IDENTIFIER
846 | IDENTIFIER '=' constant_expression
847 '''
848 if len(p) == 2:
849 p[0] = Enumerator(p[1], None)
850 else:
851 p[0] = Enumerator(p[1], p[3])
852
853 def p_type_qualifier(p):
854 '''type_qualifier : CONST
855 | VOLATILE
856 '''
857 p[0] = TypeQualifier(p[1])
858
859 def p_declarator(p):
860 '''declarator : pointer direct_declarator
861 | direct_declarator
862 '''
863 if len(p) > 2:
864 p[0] = p[1]
865 ptr = p[1]
866 while ptr.pointer:
867 ptr = ptr.pointer
868 ptr.pointer = p[2]
869 else:
870 p[0] = p[1]
871
872 def p_direct_declarator(p):
873 '''direct_declarator : IDENTIFIER
874 | TYPE_NAME
875 | '(' declarator ')'
876 | direct_declarator '[' constant_expression ']'
877 | direct_declarator '[' ']'
878 | direct_declarator '(' parameter_type_list ')'
879 | direct_declarator '(' identifier_list ')'
880 | direct_declarator '(' ')'
881 '''
882 # TYPE_NAME path is because some types are predefined in wrapper scripts;
883 # it is not valid C.
884
885 if isinstance(p[1], Declarator):
886 p[0] = p[1]
887 if p[2] == '[':
888 a = Array()
889 a.array = p[0].array
890 p[0].array = a
891 if p[3] != ']':
892 a.size = p[3]
893 else:
894 if p[3] == ')':
895 p[0].parameters = ()
896 else:
897 p[0].parameters = p[3]
898 elif p[1] == '(':
899 p[0] = p[2]
900 else:
901 p[0] = Declarator()
902 p[0].identifier = p[1]
903
904 # Check parameters for (void) and simplify to empty tuple.
905 if p[0].parameters and len(p[0].parameters) == 1:
906 param = p[0].parameters[0]
907 if param.type.specifiers == ['void'] and not param.declarator:
908 p[0].parameters = ()
909
910
911 def p_pointer(p):
912 '''pointer : '*'
913 | '*' type_qualifier_list
914 | '*' pointer
915 | '*' type_qualifier_list pointer
916 '''
917 if len(p) == 2:
918 p[0] = Pointer()
919 elif len(p) == 3:
920 if type(p[2]) == Pointer:
921 p[0] = Pointer()
922 p[0].pointer = p[2]
923 else:
924 p[0] = Pointer()
925 p[0].qualifiers = p[2]
926 else:
927 p[0] = Pointer()
928 p[0].qualifiers = p[2]
929 p[0].pointer = p[3]
930
931 def p_type_qualifier_list(p):
932 '''type_qualifier_list : type_qualifier
933 | type_qualifier_list type_qualifier
934 '''
935 if len(p) > 2:
936 p[0] = p[1] + (p[2],)
937 else:
938 p[0] = (p[1],)
939
940 def p_parameter_type_list(p):
941 '''parameter_type_list : parameter_list
942 | parameter_list ',' ELLIPSIS
943 '''
944 if len(p) > 2:
945 p[0] = p[1] + (p[3],)
946 else:
947 p[0] = p[1]
948
949
950 def p_parameter_list(p):
951 '''parameter_list : parameter_declaration
952 | parameter_list ',' parameter_declaration
953 '''
954 if len(p) > 2:
955 p[0] = p[1] + (p[3],)
956 else:
957 p[0] = (p[1],)
958
959 def p_parameter_declaration(p):
960 '''parameter_declaration : declaration_specifiers declarator
961 | declaration_specifiers abstract_declarator
962 | declaration_specifiers
963 '''
964 p[0] = Parameter()
965 apply_specifiers(p[1], p[0])
966 if len(p) > 2:
967 p[0].declarator = p[2]
968
969 def p_identifier_list(p):
970 '''identifier_list : IDENTIFIER
971 | identifier_list ',' IDENTIFIER
972 '''
973 param = Parameter()
974 param.declarator = Declarator()
975 if len(p) > 2:
976 param.declarator.identifier = p[3]
977 p[0] = p[1] + (param,)
978 else:
979 param.declarator.identifier = p[1]
980 p[0] = (param,)
981
982 def p_type_name(p):
983 '''type_name : specifier_qualifier_list
984 | specifier_qualifier_list abstract_declarator
985 '''
986
987 def p_abstract_declarator(p):
988 '''abstract_declarator : pointer
989 | direct_abstract_declarator
990 | pointer direct_abstract_declarator
991 '''
992 if len(p) == 2:
993 p[0] = p[1]
994 if type(p[0]) == Pointer:
995 ptr = p[0]
996 while ptr.pointer:
997 ptr = ptr.pointer
998 # Only if doesn't already terminate in a declarator
999 if type(ptr) == Pointer:
1000 ptr.pointer = Declarator()
1001 else:
1002 p[0] = p[1]
1003 ptr = p[0]
1004 while ptr.pointer:
1005 ptr = ptr.pointer
1006 ptr.pointer = p[2]
1007
1008 def p_direct_abstract_declarator(p):
1009 '''direct_abstract_declarator : '(' abstract_declarator ')'
1010 | '[' ']'
1011 | '[' constant_expression ']'
1012 | direct_abstract_declarator '[' ']'
1013 | direct_abstract_declarator '[' constant_expression ']'
1014 | '(' ')'
1015 | '(' parameter_type_list ')'
1016 | direct_abstract_declarator '(' ')'
1017 | direct_abstract_declarator '(' parameter_type_list ')'
1018 '''
1019 if p[1] == '(' and isinstance(p[2], Declarator):
1020 p[0] = p[2]
1021 else:
1022 if isinstance(p[1], Declarator):
1023 p[0] = p[1]
1024 if p[2] == '[':
1025 a = Array()
1026 a.array = p[0].array
1027 p[0].array = a
1028 if p[3] != ']':
1029 p[0].array.size = p[3]
1030 elif p[2] == '(':
1031 if p[3] == ')':
1032 p[0].parameters = ()
1033 else:
1034 p[0].parameters = p[3]
1035 else:
1036 p[0] = Declarator()
1037 if p[1] == '[':
1038 p[0].array = Array()
1039 if p[2] != ']':
1040 p[0].array.size = p[2]
1041 elif p[1] == '(':
1042 if p[2] == ')':
1043 p[0].parameters = ()
1044 else:
1045 p[0].parameters = p[2]
1046
1047 def p_initializer(p):
1048 '''initializer : assignment_expression
1049 | '{' initializer_list '}'
1050 | '{' initializer_list ',' '}'
1051 '''
1052
1053 def p_initializer_list(p):
1054 '''initializer_list : initializer
1055 | initializer_list ',' initializer
1056 '''
1057
1058 def p_statement(p):
1059 '''statement : labeled_statement
1060 | compound_statement
1061 | expression_statement
1062 | selection_statement
1063 | iteration_statement
1064 | jump_statement
1065 '''
1066
1067 def p_labeled_statement(p):
1068 '''labeled_statement : IDENTIFIER ':' statement
1069 | CASE constant_expression ':' statement
1070 | DEFAULT ':' statement
1071 '''
1072
1073 def p_compound_statement(p):
1074 '''compound_statement : '{' '}'
1075 | '{' statement_list '}'
1076 | '{' declaration_list '}'
1077 | '{' declaration_list statement_list '}'
1078 '''
1079
1080 def p_compound_statement_error(p):
1081 '''compound_statement : '{' error '}'
1082 '''
1083 # Error resynchronisation catch-all
1084
1085 def p_declaration_list(p):
1086 '''declaration_list : declaration
1087 | declaration_list declaration
1088 '''
1089
1090 def p_statement_list(p):
1091 '''statement_list : statement
1092 | statement_list statement
1093 '''
1094
1095 def p_expression_statement(p):
1096 '''expression_statement : ';'
1097 | expression ';'
1098 '''
1099 def p_expression_statement_error(p):
1100 '''expression_statement : error ';'
1101 '''
1102 # Error resynchronisation catch-all
1103
1104 def p_selection_statement(p):
1105 '''selection_statement : IF '(' expression ')' statement
1106 | IF '(' expression ')' statement ELSE statement
1107 | SWITCH '(' expression ')' statement
1108 '''
1109
1110 def p_iteration_statement(p):
1111 '''iteration_statement : WHILE '(' expression ')' statement
1112 | DO statement WHILE '(' expression ')' ';'
1113 | FOR '(' expression_statement expression_statement ')' statement
1114 | FOR '(' expression_statement expression_statement expression ')' statement
1115 '''
1116
1117 def p_jump_statement(p):
1118 '''jump_statement : GOTO IDENTIFIER ';'
1119 | CONTINUE ';'
1120 | BREAK ';'
1121 | RETURN ';'
1122 | RETURN expression ';'
1123 '''
1124
1125 def p_external_declaration(p):
1126 '''external_declaration : declaration
1127 | function_definition
1128 '''
1129
1130 # Intentionally empty
1131
1132 def p_function_definition(p):
1133 '''function_definition : declaration_specifiers declarator declaration_list compound_statement
1134 | declaration_specifiers declarator compound_statement
1135 | declarator declaration_list compound_statement
1136 | declarator compound_statement
1137 '''
1138
1139 def p_error(t):
1140 if not t:
1141 # Crap, no way to get to CParser instance. FIXME TODO
1142 print('Syntax error at end of file.', file=sys.stderr)
1143 else:
1144 t.lexer.cparser.handle_error('Syntax error at %r' % t.value,
1145 t.filename, t.lineno)
1146 # Don't alter lexer: default behaviour is to pass error production
1147 # up until it hits the catch-all at declaration, at which point
1148 # parsing continues (synchronisation).
1149
1150 # --------------------------------------------------------------------------
1151 # Lexer
1152 # --------------------------------------------------------------------------
1153
1154 class CLexer(object):
1155 def __init__(self, cparser):
1156 self.cparser = cparser
1157 self.type_names = set()
1158
1159 def input(self, tokens):
1160 self.tokens = tokens
1161 self.pos = 0
1162
1163 def token(self):
1164 while self.pos < len(self.tokens):
1165 t = self.tokens[self.pos]
1166 self.pos += 1
1167
1168 if not t:
1169 break
1170
1171 # PP events
1172 if t.type == 'PP_DEFINE':
1173 name, value = t.value
1174 self.cparser.handle_define(
1175 name, value, t.filename, t.lineno)
1176 continue
1177 elif t.type == 'PP_DEFINE_CONSTANT':
1178 name, value = t.value
1179 self.cparser.handle_define_constant(
1180 name, value, t.filename, t.lineno)
1181 continue
1182 elif t.type == 'PP_IFNDEF':
1183 self.cparser.handle_ifndef(t.value, t.filename, t.lineno)
1184 continue
1185 # TODO: other PP tokens
1186
1187 # Transform PP tokens into C tokens
1188 if t.type == 'LPAREN':
1189 t.type = '('
1190 elif t.type == 'PP_NUMBER':
1191 t.type = 'CONSTANT'
1192 elif t.type == 'IDENTIFIER' and t.value in keywords:
1193 t.type = t.value.upper()
1194 elif t.type == 'IDENTIFIER' and t.value in self.type_names:
1195 t.type = 'TYPE_NAME'
1196 t.lexer = self
1197 return t
1198 return None
1199
1200 # --------------------------------------------------------------------------
1201 # Parser
1202 # --------------------------------------------------------------------------
1203
1204 class CPreprocessorParser(preprocessor.PreprocessorParser):
1205 def __init__(self, cparser, **kwargs):
1206 self.cparser = cparser
1207 preprocessor.PreprocessorParser.__init__(self, **kwargs)
1208
1209 def push_file(self, filename, data=None):
1210 if not self.cparser.handle_include(filename):
1211 return
1212
1213 tokens = self.cparser.get_cached_tokens(filename)
1214 if tokens is not None:
1215 self.output += tokens
1216 return
1217
1218 if not data:
1219 data = open(filename).read()
1220 self.lexer.push_input(data, filename)
1221
1222 class CParser(object):
1223 '''Parse a C source file.
1224
1225 Subclass and override the handle_* methods. Call `parse` with a string
1226 to parse.
1227 '''
1228 def __init__(self, stddef_types=True, gnu_types=True, cache_headers=True):
1229 self.preprocessor_parser = CPreprocessorParser(self)
1230 self.parser = yacc.Parser()
1231 yacc.yacc(method='LALR').init_parser(self.parser)
1232 self.parser.cparser = self
1233
1234 self.lexer = CLexer(self)
1235 if stddef_types:
1236 self.lexer.type_names.add('wchar_t')
1237 self.lexer.type_names.add('ptrdiff_t')
1238 self.lexer.type_names.add('size_t')
1239 if gnu_types:
1240 self.lexer.type_names.add('__builtin_va_list')
1241 if sys.platform == 'win32':
1242 self.lexer.type_names.add('__int64')
1243
1244 self.header_cache = {}
1245 self.cache_headers = cache_headers
1246 self.load_header_cache()
1247
1248 def parse(self, filename, data=None, debug=False):
1249 '''Parse a file. Give filename or filename + data.
1250
1251 If `debug` is True, parsing state is dumped to stdout.
1252 '''
1253 if not data:
1254 data = open(filename, 'r').read()
1255
1256 self.handle_status('Preprocessing %s' % filename)
1257 self.preprocessor_parser.parse(filename, data, debug=debug)
1258 self.lexer.input(self.preprocessor_parser.output)
1259 self.handle_status('Parsing %s' % filename)
1260 self.parser.parse(lexer=self.lexer, debug=debug)
1261
1262 def load_header_cache(self, filename=None):
1263 if not filename:
1264 filename = '.header.cache'
1265 try:
1266 self.header_cache = cPickle.load(open(filename, 'rb'))
1267 self.handle_status('Loaded header cache "%s". Found:' % filename)
1268 for header in self.header_cache.keys():
1269 self.handle_status(' %s' % header)
1270 except:
1271 self.handle_status('Failed to load header cache "%s"' % filename)
1272
1273 def save_header_cache(self, filename=None):
1274 if not filename:
1275 filename = '.header.cache'
1276 try:
1277 cPickle.dump(self.header_cache, open(filename, 'wb'))
1278 self.handle_status('Updated header cache "%s"' % filename)
1279 except:
1280 self.handle_status('Failed to update header cache "%s"' % filename)
1281
1282 def get_cached_tokens(self, header):
1283 '''Return a list of tokens for `header`.
1284
1285 If there is no cached copy, return None.
1286 '''
1287 try:
1288 now = os.stat(header).st_mtime
1289 except OSError:
1290 now = time.time()
1291 current_memento = self.preprocessor_parser.get_memento()
1292 if header in self.header_cache:
1293 timestamp, memento, tokens, namespace = self.header_cache[header]
1294 if self.preprocessor_parser.system_headers:
1295 self.handle_status('Not using cached header "%s" because ' \
1296 'of overridden system_headers.' % header)
1297 elif now < timestamp:
1298 self.handle_status('Not using cached header "%s" because ' \
1299 'cached copy is stale.' % header)
1300 elif memento != current_memento:
1301 self.handle_status('Not using cached header "%s" because ' \
1302 'memento differs.' % header)
1303 else:
1304 self.handle_status('Using cached header "%s"' % header)
1305 self.preprocessor_parser.namespace = namespace
1306 return tokens
1307
1308 if self.cache_headers and not self.preprocessor_parser.system_headers:
1309 self.handle_status('Caching header "%s"' % header)
1310 self.cache_headers = False
1311 ppp = preprocessor.PreprocessorParser()
1312 ppp.include_path = self.preprocessor_parser.include_path
1313 ppp.parse(filename=header,
1314 namespace=self.preprocessor_parser.namespace)
1315 self.header_cache[header] = (now, current_memento,
1316 ppp.output, ppp.namespace.copy())
1317 self.save_header_cache()
1318 self.cache_headers = True
1319 return ppp.output
1320
1321 return None
1322
1323 # ----------------------------------------------------------------------
1324 # Parser interface. Override these methods in your subclass.
1325 # ----------------------------------------------------------------------
1326
1327 def handle_error(self, message, filename, lineno):
1328 '''A parse error occurred.
1329
1330 The default implementation prints `lineno` and `message` to stderr.
1331 The parser will try to recover from errors by synchronising at the
1332 next semicolon.
1333 '''
1334 print('%s:%s %s' % (filename, lineno, message), file=sys.stderr)
1335
1336 def handle_status(self, message):
1337 '''Progress information.
1338
1339 The default implementationg prints message to stderr.
1340 '''
1341 print(message, file=sys.stderr)
1342
1343 def handle_include(self, header):
1344 '''#include `header`
1345
1346 Return True to proceed with including the header, otherwise return
1347 False to skip it. The default implementation returns True.
1348 '''
1349 return True
1350
1351 def handle_define(self, name, value, filename, lineno):
1352 '''#define `name` `value`
1353
1354 both are strings, value could not be parsed as an expression
1355 '''
1356
1357 def handle_define_constant(self, name, value, filename, lineno):
1358 '''#define `name` `value`
1359
1360 value is an int or float
1361 '''
1362
1363 def handle_undef(self, name):
1364 '''#undef `name`'''
1365
1366 def handle_if(self, expr):
1367 '''#if `expr`'''
1368
1369 def handle_ifdef(self, name):
1370 '''#ifdef `name`'''
1371
1372 def handle_ifndef(self, name, filename, lineno):
1373 '''#ifndef `name`'''
1374
1375 def handle_elif(self, expr):
1376 '''#elif `expr`'''
1377
1378 def handle_else(self):
1379 '''#else'''
1380
1381 def handle_endif(self):
1382 '''#endif'''
1383
1384 def impl_handle_declaration(self, declaration, filename, lineno):
1385 '''Internal method that calls `handle_declaration`. This method
1386 also adds any new type definitions to the lexer's list of valid type
1387 names, which affects the parsing of subsequent declarations.
1388 '''
1389 if declaration.storage == 'typedef':
1390 declarator = declaration.declarator
1391 if not declarator:
1392 # XXX TEMPORARY while struct etc not filled
1393 return
1394 while declarator.pointer:
1395 declarator = declarator.pointer
1396 self.lexer.type_names.add(declarator.identifier)
1397 self.handle_declaration(declaration, filename, lineno)
1398
1399 def handle_declaration(self, declaration, filename, lineno):
1400 '''A declaration was encountered.
1401
1402 `declaration` is an instance of Declaration. Where a declaration has
1403 multiple initialisers, each is returned as a separate declaration.
1404 '''
1405 pass
1406
1407 class DebugCParser(CParser):
1408 '''A convenience class that prints each invocation of a handle_* method to
1409 stdout.
1410 '''
1411 def handle_include(self, header):
1412 print('#include header=%r' % header)
1413 return True
1414
1415 def handle_define(self, name, value, filename, lineno):
1416 print('#define name=%r, value=%r' % (name, value))
1417
1418 def handle_define_constant(self, name, value, filename, lineno):
1419 print('#define constant name=%r, value=%r' % (name, value))
1420
1421 def handle_undef(self, name):
1422 print('#undef name=%r' % name)
1423
1424 def handle_if(self, expr):
1425 print('#if expr=%s' % expr)
1426
1427 def handle_ifdef(self, name):
1428 print('#ifdef name=%r' % name)
1429
1430 def handle_ifndef(self, name, filename, lineno):
1431 print('#ifndef name=%r' % name)
1432
1433 def handle_elif(self, expr):
1434 print('#elif expr=%s' % expr)
1435
1436 def handle_else(self):
1437 print('#else')
1438
1439 def handle_endif(self):
1440 print('#endif')
1441
1442 def handle_declaration(self, declaration, filename, lineno):
1443 print(declaration)
1444
1445 if __name__ == '__main__':
1446 DebugCParser().parse(sys.argv[1], debug=True)