check_binding_retval.py 12 KB

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