cpp_lint.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/usr/bin/python
  2. #
  3. # Checks C++ files to make sure they conform to LLVM standards, as specified in
  4. # http://llvm.org/docs/CodingStandards.html .
  5. #
  6. # TODO: add unittests for the verifier functions:
  7. # http://docs.python.org/library/unittest.html .
  8. import common_lint
  9. import re
  10. import sys
  11. def VerifyIncludes(filename, lines):
  12. """Makes sure the #includes are in proper order and no disallows files are
  13. #included.
  14. Args:
  15. filename: the file under consideration as string
  16. lines: contents of the file as string array
  17. """
  18. include_gtest_re = re.compile(r'^#include "gtest/(.*)"')
  19. include_llvm_re = re.compile(r'^#include "llvm/(.*)"')
  20. include_support_re = re.compile(r'^#include "(Support/.*)"')
  21. include_config_re = re.compile(r'^#include "(Config/.*)"')
  22. include_system_re = re.compile(r'^#include <(.*)>')
  23. DISALLOWED_SYSTEM_HEADERS = ['iostream']
  24. line_num = 1
  25. prev_config_header = None
  26. prev_system_header = None
  27. for line in lines:
  28. # TODO: implement private headers
  29. # TODO: implement gtest headers
  30. # TODO: implement top-level llvm/* headers
  31. # TODO: implement llvm/Support/* headers
  32. # Process Config/* headers
  33. config_header = include_config_re.match(line)
  34. if config_header:
  35. curr_config_header = config_header.group(1)
  36. if prev_config_header:
  37. if prev_config_header > curr_config_header:
  38. print '%s:%d:Config headers not in order: "%s" before "%s" ' % (
  39. filename, line_num, prev_config_header, curr_config_header)
  40. # Process system headers
  41. system_header = include_system_re.match(line)
  42. if system_header:
  43. curr_system_header = system_header.group(1)
  44. # Is it blacklisted?
  45. if curr_system_header in DISALLOWED_SYSTEM_HEADERS:
  46. print '%s:%d:Disallowed system header: <%s>' % (
  47. filename, line_num, curr_system_header)
  48. elif prev_system_header:
  49. # Make sure system headers are alphabetized amongst themselves
  50. if prev_system_header > curr_system_header:
  51. print '%s:%d:System headers not in order: <%s> before <%s>' % (
  52. filename, line_num, prev_system_header, curr_system_header)
  53. prev_system_header = curr_system_header
  54. line_num += 1
  55. class CppLint(common_lint.BaseLint):
  56. MAX_LINE_LENGTH = 80
  57. def RunOnFile(self, filename, lines):
  58. VerifyIncludes(filename, lines)
  59. common_lint.VerifyLineLength(filename, lines, CppLint.MAX_LINE_LENGTH)
  60. common_lint.VerifyTrailingWhitespace(filename, lines)
  61. def CppLintMain(filenames):
  62. common_lint.RunLintOverAllFiles(CppLint(), filenames)
  63. return 0
  64. if __name__ == '__main__':
  65. sys.exit(CppLintMain(sys.argv[1:]))