Advertisement
johnmudd

Python/pyparser code to extract typedefs from C code

Apr 27th, 2013
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. from pyparsing  import *
  2.  
  3.  
  4. # Only the top level typedef element will be used to search for typedef stmts.
  5. # But this is also used to parse declare stmts nested inside typedefs.
  6. declare_list = Forward()  # Will be defined later, after being referenced.
  7. ident = Word(alphas+'_', alphanums+'_')
  8. int_number = Word(nums+' ()+-*/')
  9.  
  10. # "|" = MatchFirst
  11. simple_base = Group(
  12.         ( Optional(Keyword('unsigned'))('unsigned') + oneOf('char int long short')('name') ) |
  13.         oneOf('unsigned double float void')('name') |
  14.         ident('name')
  15.     )('simple')
  16.  
  17. struct_base = Group( Keyword('struct') + Optional(ident('struct_name')) + '{' + declare_list + '}' )('struct')
  18.  
  19. union_base = Group( Keyword('union') + '{' + declare_list + '}' )('union')  # "+" = And
  20.  
  21. enum_base = Group( Keyword('enum') + Optional(ident('enum_name')) + '{'
  22.         + delimitedList(ident) + Optional(',') +
  23.         '}' )('enum')
  24.  
  25. any_base = (struct_base | union_base | enum_base | simple_base)('type')
  26.  
  27. array = Group( '[' + ( int_number | ident )('extent') + ']' )
  28.  
  29. bit_size = Group( ':' + int_number('extent') )
  30.  
  31. declare = Group(
  32.             any_base + ident('instance') +
  33.             Optional( OneOrMore(array)('array') | bit_size('bit') ) + ';'
  34.         )('declare')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement