|
3 | 3 | import ast |
4 | 4 | from collections import defaultdict |
5 | 5 | from functools import lru_cache |
6 | | -from typing import TYPE_CHECKING, Optional, TypeVar |
| 6 | +from typing import TYPE_CHECKING, Optional, TypeVar, Union |
7 | 7 |
|
8 | 8 | import isort |
9 | 9 | import libcst as cst |
|
16 | 16 | from codeflash.models.models import FunctionParent |
17 | 17 |
|
18 | 18 | if TYPE_CHECKING: |
| 19 | + from _ast import AST |
19 | 20 | from pathlib import Path |
20 | 21 |
|
21 | 22 | from codeflash.discovery.functions_to_optimize import FunctionToOptimize |
|
24 | 25 | ASTNodeT = TypeVar("ASTNodeT", bound=ast.AST) |
25 | 26 |
|
26 | 27 |
|
| 28 | +class BenchmarkFunctionRemover(ast.NodeTransformer): |
| 29 | + """AST transformer that removes functions using pytest-benchmark fixture.""" |
| 30 | + |
| 31 | + def _uses_benchmark_fixture(self, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> bool: |
| 32 | + """Check if a function uses the benchmark fixture.""" |
| 33 | + # Check function arguments for 'benchmark' parameter |
| 34 | + for arg in node.args.args: |
| 35 | + if arg.arg == "benchmark": |
| 36 | + return True |
| 37 | + |
| 38 | + # Check for pytest markers that might indicate benchmarking |
| 39 | + for decorator in node.decorator_list: |
| 40 | + if self._is_benchmark_marker(decorator): |
| 41 | + return True |
| 42 | + |
| 43 | + # Check function body for benchmark usage |
| 44 | + return any(isinstance(stmt, ast.Call) and self._is_benchmark_call(stmt) for stmt in ast.walk(node)) |
| 45 | + |
| 46 | + def _is_benchmark_marker(self, decorator: ast.expr) -> bool: |
| 47 | + """Check if decorator is a benchmark-related pytest marker.""" |
| 48 | + if isinstance(decorator, ast.Call): |
| 49 | + if isinstance(decorator.func, ast.Attribute): |
| 50 | + # Check for @pytest.mark.benchmark |
| 51 | + if ( |
| 52 | + isinstance(decorator.func.value, ast.Attribute) |
| 53 | + and isinstance(decorator.func.value.value, ast.Name) |
| 54 | + and decorator.func.value.value.id == "pytest" |
| 55 | + and decorator.func.value.attr == "mark" |
| 56 | + and decorator.func.attr == "benchmark" |
| 57 | + ): |
| 58 | + return True |
| 59 | + elif isinstance(decorator.func, ast.Name) and decorator.func.id == "benchmark": |
| 60 | + return True |
| 61 | + elif isinstance(decorator, ast.Attribute): |
| 62 | + # Check for @pytest.mark.benchmark (without call) |
| 63 | + if ( |
| 64 | + isinstance(decorator.value, ast.Attribute) |
| 65 | + and isinstance(decorator.value.value, ast.Name) |
| 66 | + and decorator.value.value.id == "pytest" |
| 67 | + and decorator.value.attr == "mark" |
| 68 | + and decorator.attr == "benchmark" |
| 69 | + ): |
| 70 | + return True |
| 71 | + elif isinstance(decorator, ast.Name) and decorator.id == "benchmark": |
| 72 | + return True |
| 73 | + |
| 74 | + return False |
| 75 | + |
| 76 | + @staticmethod |
| 77 | + def _is_benchmark_call(call: ast.Call) -> bool: |
| 78 | + """Check if a call is using the benchmark fixture.""" |
| 79 | + if isinstance(call.func, ast.Name) and call.func.id == "benchmark": |
| 80 | + return True |
| 81 | + return bool( |
| 82 | + isinstance(call.func, ast.Attribute) |
| 83 | + and call.func.attr in ["benchmark", "__call__"] |
| 84 | + and isinstance(call.func.value, ast.Name) |
| 85 | + and call.func.value.id == "benchmark" |
| 86 | + ) |
| 87 | + |
| 88 | + def visit_FunctionDef(self, node: ast.FunctionDef) -> Optional[AST]: |
| 89 | + """Visit function definitions and remove if they use benchmark fixture.""" |
| 90 | + if self._uses_benchmark_fixture(node): |
| 91 | + return None # Remove the function |
| 92 | + return self.generic_visit(node) |
| 93 | + |
| 94 | + def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> Optional[AST]: |
| 95 | + """Visit async function definitions and remove if they use benchmark fixture.""" |
| 96 | + if self._uses_benchmark_fixture(node): |
| 97 | + return None # Remove the function |
| 98 | + return self.generic_visit(node) |
| 99 | + |
| 100 | + def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef: |
| 101 | + """Visit class definitions and remove benchmark methods.""" |
| 102 | + original_body = node.body[:] |
| 103 | + new_body = [] |
| 104 | + |
| 105 | + for item in original_body: |
| 106 | + if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)): |
| 107 | + if not self._uses_benchmark_fixture(item): |
| 108 | + new_body.append(self.visit(item)) |
| 109 | + |
| 110 | + else: |
| 111 | + new_body.append(self.visit(item)) |
| 112 | + |
| 113 | + node.body = new_body |
| 114 | + return node |
| 115 | + |
| 116 | + |
| 117 | +def remove_benchmark_functions(tree: AST) -> AST: |
| 118 | + """Remove benchmark functions from Python source code. |
| 119 | +
|
| 120 | + Args: |
| 121 | + tree: Python source code as ast module |
| 122 | +
|
| 123 | + Returns: |
| 124 | + Tuple of (modified_source_code, set_of_removed_function_names) |
| 125 | +
|
| 126 | + """ |
| 127 | + try: |
| 128 | + # Create and apply the transformer |
| 129 | + remover = BenchmarkFunctionRemover() |
| 130 | + return remover.visit(tree) |
| 131 | + |
| 132 | + except Exception as e: |
| 133 | + print(f"Error processing code: {e}") |
| 134 | + return tree |
| 135 | + |
| 136 | + |
27 | 137 | def normalize_node(node: ASTNodeT) -> ASTNodeT: |
28 | 138 | if isinstance(node, (ast.Module, ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and ast.get_docstring(node): |
29 | 139 | node.body = node.body[1:] |
|
0 commit comments