Skip to content

Commit 2764aff

Browse files
committed
todo cleanup
1 parent 9d69a58 commit 2764aff

11 files changed

+373
-545
lines changed

codeflash/code_utils/code_extractor.py

Lines changed: 139 additions & 426 deletions
Large diffs are not rendered by default.

codeflash/code_utils/config_consts.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,6 @@
3434
N_CANDIDATES_LP_EFFECTIVE = min(N_CANDIDATES_LP_LSP if _IS_LSP_ENABLED else N_CANDIDATES_LP, MAX_N_CANDIDATES_LP)
3535
N_TESTS_TO_GENERATE_EFFECTIVE = N_TESTS_TO_GENERATE_LSP if _IS_LSP_ENABLED else N_TESTS_TO_GENERATE
3636
TOTAL_LOOPING_TIME_EFFECTIVE = TOTAL_LOOPING_TIME_LSP if _IS_LSP_ENABLED else TOTAL_LOOPING_TIME
37+
38+
MAX_CONTEXT_LEN_IMPACT = 1000
39+
TIME_LIMIT_FOR_OPT_IMPACT = 5 # in sec

codeflash/optimization/function_optimizer.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,6 @@ def generate_and_instrument_tests(
377377

378378
# note: this isn't called by the lsp, only called by cli
379379
def optimize_function(self) -> Result[BestOptimization, str]:
380-
get_opt_impact_metrics(self.function_to_optimize.file_path,self.function_to_optimize.qualified_name, self.project_root, self.test_cfg.tests_root)
381380
initialization_result = self.can_be_optimized()
382381
if not is_successful(initialization_result):
383382
return Failure(initialization_result.failure())
@@ -1470,7 +1469,11 @@ def process_review(
14701469
logger.debug(f"optimization impact response failed, investigate {e}")
14711470
data["optimization_impact"] = opt_impact_response
14721471
data["impact_metrics"] = get_opt_impact_metrics(
1473-
self.project_root, self.test_cfg.tests_root
1472+
self.function_to_optimize_source_code,
1473+
self.function_to_optimize.file_path,
1474+
self.function_to_optimize.qualified_name,
1475+
self.project_root,
1476+
self.test_cfg.tests_root,
14741477
) # need module root, tests root only
14751478
if raise_pr and not staging_review:
14761479
data["git_remote"] = self.args.git_remote

example_usage.py

Lines changed: 122 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,131 @@
11
#!/usr/bin/env python3
2-
"""Example of using the ripgrep search script programmatically."""
2+
"""Example usage of the function reference finder."""
33

4-
import json
4+
from find_function_references import find_function_references
5+
from find_function_references_detailed import find_function_references_detailed
56

6-
from ripgrep_search import search_with_ripgrep
77

8-
# Search for any pattern you want
9-
pattern = "sorter" # Change this to any pattern you need
10-
results = search_with_ripgrep(pattern)
8+
def example_basic_usage():
9+
"""Example of basic usage - just get list of files."""
10+
# Example: Find references to a function
11+
filepath = "path/to/your/file.py"
12+
function_name = "your_function_name"
1113

12-
# Access the results as a dictionary
13-
print(f"Found matches in {len(results)} files")
14+
# Find references (will auto-detect project root)
15+
reference_files = find_function_references(filepath, function_name)
1416

15-
# Iterate through the results
16-
for filepath, occurrences in results.items():
17-
print(f"\n{filepath}: {len(occurrences)} matches")
18-
for line_no, content in occurrences[:3]: # Show first 3 matches per file
19-
print(f" Line {line_no}: {content[:80]}...")
17+
print(f"Files containing references to {function_name}:")
18+
for file in reference_files:
19+
print(f" - {file}")
2020

21-
# Save results to a JSON file if needed
22-
with open("search_results.json", "w") as f:
23-
json.dump(results, f, indent=2)
21+
return reference_files
2422

25-
# Or filter results for specific files
26-
python_files_only = {path: matches for path, matches in results.items() if path.endswith(".py")}
2723

28-
print(f"\nPython files with matches: {len(python_files_only)}")
24+
def example_detailed_usage():
25+
"""Example of detailed usage - get line numbers and context."""
26+
# Example: Find references with detailed information
27+
filepath = "path/to/your/file.py"
28+
function_name = "your_function_name"
29+
project_root = "/path/to/project/root" # Optional
30+
31+
# Find detailed references
32+
references = find_function_references_detailed(filepath, function_name, project_root)
33+
34+
print(f"\nDetailed references to {function_name}:")
35+
for file, refs in references.items():
36+
print(f"\nFile: {file}")
37+
for ref in refs:
38+
print(f" Line {ref['line']}: {ref['context']}")
39+
40+
return references
41+
42+
43+
def example_programmatic_usage():
44+
"""Example of using in your own Python code."""
45+
import jedi
46+
47+
# Direct Jedi usage for more control
48+
source_code = """
49+
def my_function(x, y):
50+
return x + y
51+
52+
result = my_function(1, 2)
53+
"""
54+
55+
# Create a script object
56+
script = jedi.Script(code=source_code)
57+
58+
# Find the function definition (line 2, column 4 for 'my_function')
59+
references = script.get_references(line=2, column=4)
60+
61+
print("Direct Jedi references:")
62+
for ref in references:
63+
print(f" Line {ref.line}, Column {ref.column}: {ref.description}")
64+
65+
# You can also search for names
66+
names = script.get_names()
67+
for name in names:
68+
if name.type == "function":
69+
print(f"Found function: {name.name} at line {name.line}")
70+
71+
72+
def example_find_all_functions_and_their_references():
73+
"""Example of finding all functions in a file and their references."""
74+
import os
75+
76+
import jedi
77+
78+
def find_all_functions_with_references(filepath: str):
79+
"""Find all functions in a file and their references."""
80+
with open(filepath) as f:
81+
source_code = f.read()
82+
83+
script = jedi.Script(code=source_code, path=filepath)
84+
85+
# Get all defined names
86+
names = script.get_names()
87+
88+
functions_and_refs = {}
89+
90+
for name in names:
91+
if name.type == "function":
92+
# Get references for this function
93+
refs = script.get_references(line=name.line, column=name.column)
94+
95+
ref_locations = []
96+
for ref in refs:
97+
if ref.module_path and str(ref.module_path) != filepath:
98+
ref_locations.append({"file": str(ref.module_path), "line": ref.line, "column": ref.column})
99+
100+
functions_and_refs[name.name] = {"definition_line": name.line, "references": ref_locations}
101+
102+
return functions_and_refs
103+
104+
# Example usage
105+
filepath = "your_module.py"
106+
if os.path.exists(filepath):
107+
all_refs = find_all_functions_with_references(filepath)
108+
109+
for func_name, info in all_refs.items():
110+
print(f"\nFunction: {func_name} (defined at line {info['definition_line']})")
111+
if info["references"]:
112+
print(" Referenced in:")
113+
for ref in info["references"]:
114+
print(f" - {ref['file']}:{ref['line']}")
115+
else:
116+
print(" No external references found")
117+
118+
119+
if __name__ == "__main__":
120+
print("=" * 60)
121+
print("Function Reference Finder - Usage Examples")
122+
print("=" * 60)
123+
124+
print("\nNote: Update the file paths and function names in the examples")
125+
print("before running them with your actual code.\n")
126+
127+
# Uncomment to run examples:
128+
# example_basic_usage()
129+
# example_detailed_usage()
130+
# example_programmatic_usage()
131+
# example_find_all_functions_and_their_references()

find_sorter_references.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,25 @@
11
#!/usr/bin/env python3
2-
"""
3-
Script to find all references to the sorter function from code_to_optimize/bubble_sort.py
2+
"""Script to find all references to the sorter function from code_to_optimize/bubble_sort.py
43
using Jedi's static analysis capabilities.
54
"""
65

7-
import jedi
8-
import os
96
from pathlib import Path
107

8+
import jedi
9+
1110

1211
def find_function_references(file_path, line, column, project_root):
13-
"""
14-
Find all references to a function using Jedi.
12+
"""Find all references to a function using Jedi.
1513
1614
Args:
1715
file_path: Path to the file containing the function
1816
line: Line number where the function is defined (1-indexed)
1917
column: Column number where the function name starts (0-indexed)
2018
project_root: Root directory of the project to search
19+
2120
"""
2221
# Read the source code
23-
with open(file_path, 'r') as f:
22+
with open(file_path) as f:
2423
source = f.read()
2524

2625
# Create a Jedi Script object with project configuration
@@ -45,7 +44,7 @@ def find_function_references(file_path, line, column, project_root):
4544
references = []
4645
try:
4746
# Use usages() method to get all references
48-
references = script.get_references(line, column, scope='project', include_builtins=False)
47+
references = script.get_references(line, column, scope="project", include_builtins=False)
4948
except AttributeError:
5049
# Alternative approach using search
5150
print("Using alternative search method...")
@@ -91,7 +90,7 @@ def main():
9190
for ref in sorted(file_refs, key=lambda r: (r.line, r.column)):
9291
# Get the line content for context
9392
try:
94-
with open(file_path, 'r') as f:
93+
with open(file_path) as f:
9594
lines = f.readlines()
9695
if ref.line <= len(lines):
9796
line_content = lines[ref.line - 1].strip()
@@ -108,4 +107,4 @@ def main():
108107

109108

110109
if __name__ == "__main__":
111-
main()
110+
main()

function_call_finder.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -143,8 +143,8 @@ def leave_FunctionDef(self, node: cst.FunctionDef) -> None:
143143

144144
# For methods, add proper indentation (4 spaces)
145145
if self.current_class_stack:
146-
lines = func_source.split('\n')
147-
func_source = '\n'.join(' ' + line if line else line for line in lines)
146+
lines = func_source.split("\n")
147+
func_source = "\n".join(" " + line if line else line for line in lines)
148148

149149
self.function_definitions[full_name] = FunctionDefinitionInfo(
150150
name=full_name,
@@ -153,7 +153,7 @@ def leave_FunctionDef(self, node: cst.FunctionDef) -> None:
153153
start_line=position.start.line if position else -1,
154154
end_line=position.end.line if position else -1,
155155
is_method=bool(self.current_class_stack),
156-
class_name=self.current_class_stack[-1] if self.current_class_stack else None
156+
class_name=self.current_class_stack[-1] if self.current_class_stack else None,
157157
)
158158

159159
# Handle nested functions - mark parent as containing nested calls
@@ -167,11 +167,15 @@ def leave_FunctionDef(self, node: cst.FunctionDef) -> None:
167167
parent_source = cst.Module(body=[parent_func_node]).code
168168

169169
# Get parent class context (go up one level in stack since we're inside the nested function)
170-
parent_class_stack = self.current_class_stack[:-1] if len(self.current_function_stack) == 1 and self.current_class_stack else []
170+
parent_class_stack = (
171+
self.current_class_stack[:-1]
172+
if len(self.current_function_stack) == 1 and self.current_class_stack
173+
else []
174+
)
171175

172176
if parent_class_stack:
173-
lines = parent_source.split('\n')
174-
parent_source = '\n'.join(' ' + line if line else line for line in lines)
177+
lines = parent_source.split("\n")
178+
parent_source = "\n".join(" " + line if line else line for line in lines)
175179

176180
self.function_definitions[parent_name] = FunctionDefinitionInfo(
177181
name=parent_name,
@@ -180,7 +184,7 @@ def leave_FunctionDef(self, node: cst.FunctionDef) -> None:
180184
start_line=parent_position.start.line if parent_position else -1,
181185
end_line=parent_position.end.line if parent_position else -1,
182186
is_method=bool(parent_class_stack),
183-
class_name=parent_class_stack[-1] if parent_class_stack else None
187+
class_name=parent_class_stack[-1] if parent_class_stack else None,
184188
)
185189

186190
# Reset the flag for parent function if we're in nested functions
@@ -290,10 +294,7 @@ def get_results(self) -> Dict[str, str]:
290294
Only includes functions that call the target function (directly or through nested functions).
291295
292296
"""
293-
return {
294-
info.name: info.source_code
295-
for info in self.function_definitions.values()
296-
}
297+
return {info.name: info.source_code for info in self.function_definitions.values()}
297298

298299

299300
def find_function_calls(source_code: str, target_function_name: str, target_filepath: str) -> Dict[str, str]:
@@ -367,11 +368,12 @@ def inner():
367368

368369
# Simple usage - results is just a dict of {function_name: source_code}
369370
import json
371+
370372
print("JSON representation of results:")
371373
print(json.dumps(list(results.keys()), indent=2))
372374

373375
print("\nFormatted output:")
374376
for func_name, source_code in results.items():
375377
print(f"\n=== {func_name} ===")
376378
print(source_code)
377-
print()
379+
print()

0 commit comments

Comments
 (0)