Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Python/pyparser code to extract typedefs from C code

By: johnmudd on Apr 27th, 2013  |  syntax: Python  |  size: 1.24 KB  |  views: 59  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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')