1
0

check_undef.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import re
  2. def check_define_undef_pairs(code):
  3. # 使用正则表达式匹配#define和#undef指令
  4. define_pattern = re.compile(r'#define\s+(\w+)')
  5. undef_pattern = re.compile(r'#undef\s+(\w+)')
  6. # 查找所有的#define和#undef
  7. defines = define_pattern.findall(code)
  8. undefs = undef_pattern.findall(code)
  9. # 使用集合计算差集,找出不匹配的部分
  10. define_set = set(defines)
  11. undef_set = set(undefs)
  12. unmatched_defines = define_set - undef_set
  13. unmatched_undefs = undef_set - define_set
  14. if unmatched_defines or unmatched_undefs:
  15. if unmatched_defines:
  16. print("mismatched #define")
  17. for define in unmatched_defines:
  18. print(f"- {define}")
  19. if unmatched_undefs:
  20. print("mismatched #undef")
  21. for undef in unmatched_undefs:
  22. print(f"- {undef}")
  23. # iterate over all the files in `path` directory
  24. import os
  25. import sys
  26. def check_undef_in_dir(path):
  27. for root, dirs, files in os.walk(path):
  28. for file in files:
  29. if file.endswith(".c") or file.endswith(".h"):
  30. with open(os.path.join(root, file), "r", encoding='utf-8') as f:
  31. print(f"==> {os.path.join(root, file)}")
  32. check_define_undef_pairs(f.read())
  33. if __name__ == "__main__":
  34. if len(sys.argv) < 2:
  35. print("Usage: python scripts/check_undef.py <path>")
  36. sys.exit(1)
  37. check_undef_in_dir(sys.argv[1])