1
0

check_undef.py 1.7 KB

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