__init__.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #-----------------------------------------------------------------
  2. # pycparser: __init__.py
  3. #
  4. # This package file exports some convenience functions for
  5. # interacting with pycparser
  6. #
  7. # Eli Bendersky [https://eli.thegreenplace.net/]
  8. # License: BSD
  9. #-----------------------------------------------------------------
  10. __all__ = ['c_lexer', 'c_parser', 'c_ast']
  11. __version__ = '2.21'
  12. import io
  13. from subprocess import check_output
  14. from .c_parser import CParser
  15. def preprocess_file(filename, cpp_path='cpp', cpp_args=''):
  16. """ Preprocess a file using cpp.
  17. filename:
  18. Name of the file you want to preprocess.
  19. cpp_path:
  20. cpp_args:
  21. Refer to the documentation of parse_file for the meaning of these
  22. arguments.
  23. When successful, returns the preprocessed file's contents.
  24. Errors from cpp will be printed out.
  25. """
  26. path_list = [cpp_path]
  27. if isinstance(cpp_args, list):
  28. path_list += cpp_args
  29. elif cpp_args != '':
  30. path_list += [cpp_args]
  31. path_list += [filename]
  32. try:
  33. # Note the use of universal_newlines to treat all newlines
  34. # as \n for Python's purpose
  35. text = check_output(path_list, universal_newlines=True)
  36. except OSError as e:
  37. raise RuntimeError("Unable to invoke 'cpp'. " +
  38. 'Make sure its path was passed correctly\n' +
  39. ('Original error: %s' % e))
  40. return text
  41. def parse_file(filename, use_cpp=False, cpp_path='cpp', cpp_args='',
  42. parser=None):
  43. """ Parse a C file using pycparser.
  44. filename:
  45. Name of the file you want to parse.
  46. use_cpp:
  47. Set to True if you want to execute the C pre-processor
  48. on the file prior to parsing it.
  49. cpp_path:
  50. If use_cpp is True, this is the path to 'cpp' on your
  51. system. If no path is provided, it attempts to just
  52. execute 'cpp', so it must be in your PATH.
  53. cpp_args:
  54. If use_cpp is True, set this to the command line arguments strings
  55. to cpp. Be careful with quotes - it's best to pass a raw string
  56. (r'') here. For example:
  57. r'-I../utils/fake_libc_include'
  58. If several arguments are required, pass a list of strings.
  59. parser:
  60. Optional parser object to be used instead of the default CParser
  61. When successful, an AST is returned. ParseError can be
  62. thrown if the file doesn't parse successfully.
  63. Errors from cpp will be printed out.
  64. """
  65. if use_cpp:
  66. text = preprocess_file(filename, cpp_path, cpp_args)
  67. else:
  68. with io.open(filename) as f:
  69. text = f.read()
  70. if parser is None:
  71. parser = CParser()
  72. return parser.parse(text, filename)