check_binding_retval.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. #!/usr/bin/env python3
  2. """
  3. Static analysis tool to check Python binding functions for missing py_retval() assignments.
  4. This tool checks whether Python binding functions properly set return values before returning true.
  5. According to pocketpy conventions, when a binding function returns true, it MUST either:
  6. 1. Assign a value to py_retval() using py_new* functions, py_assign, etc.
  7. 2. Set the return value to None using py_newnone(py_retval())
  8. 3. Call a function that sets py_retval() internally (like py_import, py_call, py_iter, etc.)
  9. Usage:
  10. python scripts/check_binding_retval.py [--verbose]
  11. Exit codes:
  12. 0: No issues found
  13. 1: Issues found
  14. 2: Script error
  15. """
  16. import os
  17. import re
  18. import sys
  19. import argparse
  20. from typing import List, Dict, Tuple, Set
  21. # Functions that set py_retval() internally
  22. RETVAL_SETTING_FUNCTIONS = {
  23. 'py_import', # Sets py_retval() on success
  24. 'py_call', # Sets py_retval() with result
  25. 'py_iter', # Sets py_retval() with iterator
  26. 'py_str', # Sets py_retval() with string representation
  27. 'py_repr', # Sets py_retval() with repr string
  28. 'py_getattr', # Sets py_retval() with attribute value
  29. 'py_next', # Sets py_retval() with next value
  30. 'py_getitem', # Sets py_retval() with item
  31. 'py_vectorcall', # Sets py_retval() with call result
  32. }
  33. # Patterns that indicate py_retval() is being set
  34. RETVAL_PATTERNS = [
  35. r'py_retval\(\)', # Direct py_retval() usage
  36. r'py_new\w+\s*\(\s*py_retval\(\)', # py_newint(py_retval(), ...)
  37. r'py_assign\s*\(\s*py_retval\(\)', # py_assign(py_retval(), ...)
  38. r'\*py_retval\(\)\s*=', # *py_retval() = ...
  39. ]
  40. class BindingChecker:
  41. """Checker for Python binding functions."""
  42. def __init__(self, verbose: bool = False):
  43. self.verbose = verbose
  44. self.issues: List[Dict] = []
  45. def log(self, message: str):
  46. """Log message if verbose mode is enabled."""
  47. if self.verbose:
  48. print(f"[DEBUG] {message}")
  49. def find_c_files(self, *directories: str) -> List[str]:
  50. """Find all .c files in the given directories."""
  51. c_files = []
  52. for directory in directories:
  53. if not os.path.exists(directory):
  54. self.log(f"Directory not found: {directory}")
  55. continue
  56. for root, _, files in os.walk(directory):
  57. for file in files:
  58. if file.endswith('.c'):
  59. c_files.append(os.path.join(root, file))
  60. return c_files
  61. def extract_functions(self, content: str) -> Dict[str, Dict]:
  62. """Extract all bool-returning functions from C code."""
  63. # Pattern to match bool-returning functions
  64. pattern = r'(?:static\s+)?bool\s+(\w+)\s*\(([^)]*)\)\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}'
  65. functions = {}
  66. for match in re.finditer(pattern, content, re.MULTILINE | re.DOTALL):
  67. func_name = match.group(1)
  68. func_params = match.group(2)
  69. func_body = match.group(3)
  70. full_func = match.group(0)
  71. functions[func_name] = {
  72. 'params': func_params,
  73. 'body': func_body,
  74. 'full': full_func,
  75. 'start_pos': match.start(),
  76. }
  77. return functions
  78. def get_bound_functions(self, content: str) -> Set[str]:
  79. """Find functions that are bound as Python callables."""
  80. bound_funcs = set()
  81. # Binding patterns used in pocketpy
  82. patterns = [
  83. r'py_bindfunc\s*\([^,]+,\s*"[^"]+",\s*(\w+)\)',
  84. r'py_bind\s*\([^,]+,\s*"[^"]*",\s*(\w+)\)',
  85. r'py_bindmagic\s*\([^,]+,\s*\w+,\s*(\w+)\)',
  86. r'py_bindmethod\s*\([^,]+,\s*"[^"]+",\s*(\w+)\)',
  87. r'py_bindproperty\s*\([^,]+,\s*"[^"]+",\s*(\w+)',
  88. ]
  89. for pattern in patterns:
  90. for match in re.finditer(pattern, content):
  91. func_name = match.group(1)
  92. bound_funcs.add(func_name)
  93. self.log(f"Found bound function: {func_name}")
  94. return bound_funcs
  95. def remove_comments(self, code: str) -> str:
  96. """Remove C-style comments from code."""
  97. # Remove single-line comments
  98. code = re.sub(r'//.*?$', '', code, flags=re.MULTILINE)
  99. # Remove multi-line comments
  100. code = re.sub(r'/\*.*?\*/', '', code, flags=re.DOTALL)
  101. return code
  102. def has_retval_usage(self, func_body: str) -> bool:
  103. """Check if function body uses py_retval() in any form."""
  104. # Remove comments to avoid false positives
  105. code_without_comments = self.remove_comments(func_body)
  106. # Check for direct patterns
  107. for pattern in RETVAL_PATTERNS:
  108. if re.search(pattern, code_without_comments):
  109. return True
  110. # Check for functions that set py_retval internally
  111. for func in RETVAL_SETTING_FUNCTIONS:
  112. if func + '(' in code_without_comments:
  113. return True
  114. return False
  115. def analyze_return_statements(self, func_body: str, func_name: str) -> List[Dict]:
  116. """Analyze return true statements in the function."""
  117. lines = func_body.split('\n')
  118. suspicious_returns = []
  119. for i, line in enumerate(lines):
  120. # Look for "return true" statements
  121. if re.search(r'\breturn\s+true\b', line):
  122. # Get context (10 lines before the return)
  123. start = max(0, i - 10)
  124. context_lines = lines[start:i+1]
  125. context = '\n'.join(context_lines)
  126. suspicious_returns.append({
  127. 'line_num': i + 1,
  128. 'line': line.strip(),
  129. 'context': context,
  130. })
  131. return suspicious_returns
  132. def check_function(self, func_name: str, func_info: Dict, filepath: str) -> bool:
  133. """
  134. Check if a bound function properly sets py_retval() before returning true.
  135. Returns True if there's an issue, False otherwise.
  136. """
  137. func_body = func_info['body']
  138. # Skip if function doesn't return true
  139. if 'return true' not in func_body:
  140. self.log(f"Function {func_name} doesn't return true, skipping")
  141. return False
  142. # Check if function has any py_retval usage
  143. if self.has_retval_usage(func_body):
  144. self.log(f"Function {func_name} uses py_retval(), OK")
  145. return False
  146. # Found a potential issue
  147. self.log(f"Function {func_name} returns true without py_retval()!")
  148. suspicious_returns = self.analyze_return_statements(func_body, func_name)
  149. issue = {
  150. 'file': filepath,
  151. 'function': func_name,
  152. 'full_code': func_info['full'],
  153. 'suspicious_returns': suspicious_returns,
  154. }
  155. self.issues.append(issue)
  156. return True
  157. def check_file(self, filepath: str) -> int:
  158. """Check all bound functions in a file."""
  159. self.log(f"Checking file: {filepath}")
  160. try:
  161. with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
  162. content = f.read()
  163. except Exception as e:
  164. print(f"Error reading {filepath}: {e}", file=sys.stderr)
  165. return 0
  166. # Extract functions and find bound ones
  167. functions = self.extract_functions(content)
  168. bound_funcs = self.get_bound_functions(content)
  169. if not bound_funcs:
  170. self.log(f"No bound functions found in {filepath}")
  171. return 0
  172. issues_count = 0
  173. for func_name in bound_funcs:
  174. if func_name not in functions:
  175. self.log(f"Bound function {func_name} not found in extracted functions")
  176. continue
  177. if self.check_function(func_name, functions[func_name], filepath):
  178. issues_count += 1
  179. return issues_count
  180. def check_directories(self, *directories: str) -> int:
  181. """Check all C files in the given directories."""
  182. c_files = self.find_c_files(*directories)
  183. if not c_files:
  184. print("No C files found to check", file=sys.stderr)
  185. return 0
  186. self.log(f"Found {len(c_files)} C files to check")
  187. total_issues = 0
  188. for filepath in c_files:
  189. issues = self.check_file(filepath)
  190. total_issues += issues
  191. return total_issues
  192. def print_report(self):
  193. """Print a detailed report of all issues found."""
  194. if not self.issues:
  195. print("✓ No issues found! All Python binding functions properly set py_retval().")
  196. return
  197. print(f"\n{'='*80}")
  198. print(f"Found {len(self.issues)} function(s) with potential issues:")
  199. print(f"{'='*80}\n")
  200. for i, issue in enumerate(self.issues, 1):
  201. print(f"Issue #{i}:")
  202. print(f" File: {issue['file']}")
  203. print(f" Function: {issue['function']}")
  204. print(f" Problem: Function returns true but doesn't set py_retval()")
  205. print(f"\n Function code:")
  206. print(" " + "-" * 76)
  207. for line in issue['full_code'].split('\n'):
  208. print(f" {line}")
  209. print(" " + "-" * 76)
  210. if issue['suspicious_returns']:
  211. print(f"\n Found {len(issue['suspicious_returns'])} 'return true' statement(s):")
  212. for ret in issue['suspicious_returns']:
  213. print(f" Line {ret['line_num']}: {ret['line']}")
  214. print(f"\n{'='*80}\n")
  215. def main():
  216. parser = argparse.ArgumentParser(
  217. description='Check Python binding functions for missing py_retval() assignments',
  218. formatter_class=argparse.RawDescriptionHelpFormatter,
  219. epilog=__doc__
  220. )
  221. parser.add_argument(
  222. '--verbose', '-v',
  223. action='store_true',
  224. help='Enable verbose output for debugging'
  225. )
  226. parser.add_argument(
  227. '--dirs',
  228. nargs='+',
  229. default=['src/bindings', 'src/modules'],
  230. help='Directories to check (default: src/bindings src/modules)'
  231. )
  232. args = parser.parse_args()
  233. # Create checker and run analysis
  234. checker = BindingChecker(verbose=args.verbose)
  235. print("Checking Python binding functions for missing py_retval() assignments...")
  236. print(f"Target directories: {', '.join(args.dirs)}")
  237. print()
  238. try:
  239. total_issues = checker.check_directories(*args.dirs)
  240. checker.print_report()
  241. # Exit with appropriate code
  242. sys.exit(1 if total_issues > 0 else 0)
  243. except Exception as e:
  244. print(f"\nError during analysis: {e}", file=sys.stderr)
  245. if args.verbose:
  246. import traceback
  247. traceback.print_exc()
  248. sys.exit(2)
  249. if __name__ == '__main__':
  250. main()