| 1 | from collections import defaultdict, namedtuple |
| 2 | from collections.abc import MutableMapping |
| 3 | |
| 4 | from app.search import search_utils |
| 5 | from app.search.search_utils import SearchResult |
| 6 | |
| 7 | LineRange = namedtuple("LineRange", ["start", "end"]) |
| 8 | |
| 9 | ClassIndexType = MutableMapping[str, list[tuple[str, LineRange]]] |
| 10 | ClassFuncIndexType = MutableMapping[ |
| 11 | str, MutableMapping[str, list[tuple[str, LineRange]]] |
| 12 | ] |
| 13 | FuncIndexType = MutableMapping[str, list[tuple[str, LineRange]]] |
| 14 | |
| 15 | RESULT_SHOW_LIMIT = 3 |
| 16 | |
| 17 | |
| 18 | class SearchManager: |
| 19 | def __init__(self, project_path: str): |
| 20 | self.project_path = project_path |
| 21 | # list of all files ending with .py, which are likely not test files |
| 22 | # These are all ABSOLUTE paths. |
| 23 | self.parsed_files: list[str] = [] |
| 24 | |
| 25 | # for file name in the indexes, assume they are absolute path |
| 26 | # class name -> [(file_name, line_range)] |
| 27 | self.class_index: ClassIndexType = {} |
| 28 | |
| 29 | # {class_name -> {func_name -> [(file_name, line_range)]}} |
| 30 | # inner dict is a list, since we can have (1) overloading func names, |
| 31 | # and (2) multiple classes with the same name, having the same method |
| 32 | self.class_func_index: ClassFuncIndexType = {} |
| 33 | |
| 34 | # function name -> [(file_name, line_range)] |
| 35 | self.function_index: FuncIndexType = {} |
| 36 | self._build_index() |
| 37 | |
| 38 | def _build_index(self): |
| 39 | """ |
| 40 | With all source code of the project, build two indexes: |
| 41 | 1. From class name to (source file, start line, end line) |
| 42 | 2. From function name to (source file, start line, end line) |
| 43 | Since there can be two classes/functions with the same name, the mapping |
| 44 | value is a list of tuples. |
| 45 | This is for fast lookup whenever we receive a query. |
| 46 | """ |
| 47 | self._update_indices(*self._build_python_index()) |
| 48 | |
| 49 | def _update_indices( |
| 50 | self, |
| 51 | class_index: ClassIndexType, |
| 52 | class_func_index: ClassFuncIndexType, |
| 53 | function_index: FuncIndexType, |
| 54 | parsed_files: list[str], |
| 55 | ) -> None: |
| 56 | self.class_index.update(class_index) |
| 57 | self.class_func_index.update(class_func_index) |
| 58 | self.function_index.update(function_index) |
| 59 | self.parsed_files.extend(parsed_files) |
| 60 | |
| 61 | def _build_python_index( |
| 62 | self, |
| 63 | ) -> tuple[ClassIndexType, ClassFuncIndexType, FuncIndexType, list[str]]: |
| 64 | class_index: ClassIndexType = defaultdict(list) |
| 65 | class_func_index: ClassFuncIndexType = defaultdict(lambda: defaultdict(list)) |
| 66 | function_index: FuncIndexType = defaultdict(list) |
| 67 | |
| 68 | py_files = search_utils.find_python_files(self.project_path) |
| 69 | # holds the parsable subset of all py files |
| 70 | parsed_py_files = [] |
| 71 | for py_file in py_files: |
| 72 | file_info = search_utils.parse_python_file(py_file) |
| 73 | if file_info is None: |
| 74 | # parsing of this file failed |
| 75 | continue |
| 76 | parsed_py_files.append(py_file) |
| 77 | # extract from file info, and form search index |
| 78 | classes, class_to_funcs, top_level_funcs = file_info |
| 79 | |
| 80 | # (1) build class index |
| 81 | for c, start, end in classes: |
| 82 | class_index[c].append((py_file, LineRange(start, end))) |
| 83 | |
| 84 | # (2) build class-function index |
| 85 | for c, class_funcs in class_to_funcs.items(): |
| 86 | for f, start, end in class_funcs: |
| 87 | class_func_index[c][f].append((py_file, LineRange(start, end))) |
| 88 | |
| 89 | # (3) build (top-level) function index |
| 90 | for f, start, end in top_level_funcs: |
| 91 | function_index[f].append((py_file, LineRange(start, end))) |
| 92 | |
| 93 | return class_index, class_func_index, function_index, parsed_py_files |
| 94 | |
| 95 | def file_line_to_class_and_func( |
| 96 | self, file_path: str, line_no: int |
| 97 | ) -> tuple[str | None, str | None]: |
| 98 | """ |
| 99 | Given a file path and a line number, return the class and function name. |
| 100 | If the line is not inside a class or function, return None. |
| 101 | """ |
| 102 | # check whether this line is inside a class |
| 103 | for class_name in self.class_func_index: |
| 104 | func_dict = self.class_func_index[class_name] |
| 105 | for func_name, func_info in func_dict.items(): |
| 106 | for file_name, (start, end) in func_info: |
| 107 | if file_name == file_path and start <= line_no <= end: |
| 108 | return class_name, func_name |
| 109 | |
| 110 | # not in any class; check whether this line is inside a top-level function |
| 111 | for func_name in self.function_index: |
| 112 | for file_name, (start, end) in self.function_index[func_name]: |
| 113 | if file_name == file_path and start <= line_no <= end: |
| 114 | return None, func_name |
| 115 | |
| 116 | # this file-line is not recorded in any of the indexes |
| 117 | return None, None |
| 118 | |
| 119 | def _search_func_in_class( |
| 120 | self, function_name: str, class_name: str |
| 121 | ) -> list[SearchResult]: |
| 122 | """ |
| 123 | Search for the function name in the class. |
| 124 | Args: |
| 125 | function_name (str): Name of the function. |
| 126 | class_name (str): Name of the class. |
| 127 | Returns: |
| 128 | The list of code snippets searched. |
| 129 | """ |
| 130 | result: list[SearchResult] = [] |
| 131 | if class_name not in self.class_func_index: |
| 132 | return result |
| 133 | if function_name not in self.class_func_index[class_name]: |
| 134 | return result |
| 135 | for fname, (start, end) in self.class_func_index[class_name][function_name]: |
| 136 | func_code = search_utils.get_code_snippets(fname, start, end) |
| 137 | res = SearchResult(fname, class_name, function_name, func_code) |
| 138 | result.append(res) |
| 139 | return result |
| 140 | |
| 141 | def _search_func_in_all_classes(self, function_name: str) -> list[SearchResult]: |
| 142 | """ |
| 143 | Search for the function name in all classes. |
| 144 | Args: |
| 145 | function_name (str): Name of the function. |
| 146 | Returns: |
| 147 | The list of code snippets searched. |
| 148 | """ |
| 149 | result: list[SearchResult] = [] |
| 150 | for class_name in self.class_index: |
| 151 | res = self._search_func_in_class(function_name, class_name) |
| 152 | result.extend(res) |
| 153 | return result |
| 154 | |
| 155 | def _search_top_level_func(self, function_name: str) -> list[SearchResult]: |
| 156 | """ |
| 157 | Search for top-level function name in the entire project. |
| 158 | Args: |
| 159 | function_name (str): Name of the function. |
| 160 | Returns: |
| 161 | The list of code snippets searched. |
| 162 | """ |
| 163 | result: list[SearchResult] = [] |
| 164 | if function_name not in self.function_index: |
| 165 | return result |
| 166 | |
| 167 | for fname, (start, end) in self.function_index[function_name]: |
| 168 | func_code = search_utils.get_code_snippets(fname, start, end) |
| 169 | res = SearchResult(fname, None, function_name, func_code) |
| 170 | result.append(res) |
| 171 | return result |
| 172 | |
| 173 | def _search_func_in_code_base(self, function_name: str) -> list[SearchResult]: |
| 174 | """ |
| 175 | Search for this function, from both top-level and all class definitions. |
| 176 | """ |
| 177 | result: list[SearchResult] = [] # list of (file_name, func_code) |
| 178 | # (1) search in top level |
| 179 | top_level_res = self._search_top_level_func(function_name) |
| 180 | class_res = self._search_func_in_all_classes(function_name) |
| 181 | result.extend(top_level_res) |
| 182 | result.extend(class_res) |
| 183 | return result |
| 184 | |
| 185 | ############################### |
| 186 | ### Interfaces ################ |
| 187 | ############################### |
| 188 | |
| 189 | # not search API - for writing patch |
| 190 | # if we are searching for only a class when writing patch, likely we do not have enough info |
| 191 | # the result can be too long, so we just show the first two |
| 192 | def get_class_full_snippet(self, class_name: str) -> tuple[str, str, bool]: |
| 193 | summary = f"Class {class_name} did not appear in the codebase." |
| 194 | tool_result = f"Could not find class {class_name} in the codebase." |
| 195 | |
| 196 | if class_name not in self.class_index: |
| 197 | return tool_result, summary, False |
| 198 | # class name -> [(file_name, start_line, end_line)] |
| 199 | search_res: list[SearchResult] = [] |
| 200 | for fname, (start, end) in self.class_index[class_name]: |
| 201 | code = search_utils.get_code_snippets(fname, start, end) |
| 202 | res = SearchResult(fname, class_name, None, code) |
| 203 | search_res.append(res) |
| 204 | |
| 205 | if not search_res: |
| 206 | return tool_result, summary, False |
| 207 | |
| 208 | # the good path |
| 209 | # for all the searched result, append them and form the final result |
| 210 | tool_result = f"Found {len(search_res)} classes with name {class_name} in the codebase:\n\n" |
| 211 | summary = tool_result |
| 212 | if len(search_res) > 2: |
| 213 | tool_result += "Too many results, showing full code for 2 of them:\n" |
| 214 | for idx, res in enumerate(search_res[:2]): |
| 215 | res_str = res.to_tagged_str(self.project_path) |
| 216 | tool_result += f"- Search result {idx + 1}:\n```\n{res_str}\n```" |
| 217 | return tool_result, summary, True |
| 218 | |
| 219 | def search_class(self, class_name: str) -> tuple[str, str, bool]: |
| 220 | # initialize them to error case |
| 221 | summary = f"Class {class_name} did not appear in the codebase." |
| 222 | tool_result = f"Could not find class {class_name} in the codebase." |
| 223 | |
| 224 | if class_name not in self.class_index: |
| 225 | return tool_result, summary, False |
| 226 | |
| 227 | search_res: list[SearchResult] = [] |
| 228 | for fname, _ in self.class_index[class_name]: |
| 229 | # there are some classes; we return their signatures |
| 230 | code = search_utils.get_class_signature(fname, class_name) |
| 231 | res = SearchResult(fname, class_name, None, code) |
| 232 | search_res.append(res) |
| 233 | |
| 234 | if not search_res: |
| 235 | # this should not happen, but just in case |
| 236 | return tool_result, summary, False |
| 237 | |
| 238 | # the good path |
| 239 | # for all the searched result, append them and form the final result |
| 240 | tool_result = f"Found {len(search_res)} classes with name {class_name} in the codebase:\n\n" |
| 241 | if len(search_res) > RESULT_SHOW_LIMIT: |
| 242 | tool_result += "They appeared in the following files:\n" |
| 243 | tool_result += SearchResult.collapse_to_file_level( |
| 244 | search_res, self.project_path |
| 245 | ) |
| 246 | else: |
| 247 | for idx, res in enumerate(search_res): |
| 248 | res_str = res.to_tagged_str(self.project_path) |
| 249 | tool_result += f"- Search result {idx + 1}:\n```\n{res_str}\n```\n" |
| 250 | summary = f"The tool returned information about class `{class_name}`." |
| 251 | return tool_result, summary, True |
| 252 | |
| 253 | def search_class_in_file(self, class_name, file_name: str) -> tuple[str, str, bool]: |
| 254 | # (1) check whether we can get the file |
| 255 | candidate_py_abs_paths = [f for f in self.parsed_files if f.endswith(file_name)] |
| 256 | if not candidate_py_abs_paths: |
| 257 | tool_output = f"Could not find file {file_name} in the codebase." |
| 258 | summary = tool_output |
| 259 | return tool_output, summary, False |
| 260 | |
| 261 | # (2) search for this class in the entire code base (we do filtering later) |
| 262 | if class_name not in self.class_index: |
| 263 | tool_output = f"Could not find class {class_name} in the codebase." |
| 264 | summary = tool_output |
| 265 | return tool_output, summary, False |
| 266 | |
| 267 | # (3) class is there, check whether it exists in the file specified. |
| 268 | search_res: list[SearchResult] = [] |
| 269 | for fname, (start_line, end_line) in self.class_index[class_name]: |
| 270 | if fname in candidate_py_abs_paths: |
| 271 | class_code = search_utils.get_code_snippets(fname, start_line, end_line) |
| 272 | res = SearchResult(fname, class_name, None, class_code) |
| 273 | search_res.append(res) |
| 274 | |
| 275 | if not search_res: |
| 276 | tool_output = f"Could not find class {class_name} in file {file_name}." |
| 277 | summary = tool_output |
| 278 | return tool_output, summary, False |
| 279 | |
| 280 | # good path; we have result, now just form a response |
| 281 | tool_output = f"Found {len(search_res)} classes with name {class_name} in file {file_name}:\n\n" |
| 282 | summary = tool_output |
| 283 | for idx, res in enumerate(search_res): |
| 284 | res_str = res.to_tagged_str(self.project_path) |
| 285 | tool_output += f"- Search result {idx + 1}:\n```\n{res_str}\n```\n" |
| 286 | return tool_output, summary, True |
| 287 | |
| 288 | def search_method_in_file( |
| 289 | self, method_name: str, file_name: str |
| 290 | ) -> tuple[str, str, bool]: |
| 291 | # (1) check whether we can get the file |
| 292 | # supports both when file_name is relative to project root, and when |
| 293 | # it is just a short name |
| 294 | candidate_py_abs_paths = [f for f in self.parsed_files if f.endswith(file_name)] |
| 295 | # print(candidate_py_files) |
| 296 | if not candidate_py_abs_paths: |
| 297 | tool_output = f"Could not find file {file_name} in the codebase." |
| 298 | summary = tool_output |
| 299 | return tool_output, summary, False |
| 300 | |
| 301 | # (2) search for this method in the entire code base (we do filtering later) |
| 302 | search_res: list[SearchResult] = self._search_func_in_code_base(method_name) |
| 303 | if not search_res: |
| 304 | tool_output = f"The method {method_name} does not appear in the codebase." |
| 305 | summary = tool_output |
| 306 | return tool_output, summary, False |
| 307 | |
| 308 | # (3) filter the search result => they need to be in one of the files! |
| 309 | filtered_res: list[SearchResult] = [ |
| 310 | res for res in search_res if res.file_path in candidate_py_abs_paths |
| 311 | ] |
| 312 | |
| 313 | # (4) done with search, now prepare result |
| 314 | if not filtered_res: |
| 315 | tool_output = ( |
| 316 | f"There is no method with name `{method_name}` in file {file_name}." |
| 317 | ) |
| 318 | summary = tool_output |
| 319 | return tool_output, summary, False |
| 320 | |
| 321 | tool_output = f"Found {len(filtered_res)} methods with name `{method_name}` in file {file_name}:\n\n" |
| 322 | summary = tool_output |
| 323 | |
| 324 | # when searching for a method in one file, it's rare that there are |
| 325 | # many candidates, so we do not trim the result |
| 326 | for idx, res in enumerate(filtered_res): |
| 327 | res_str = res.to_tagged_str(self.project_path) |
| 328 | tool_output += f"- Search result {idx + 1}:\n```\n{res_str}\n```\n" |
| 329 | return tool_output, summary, True |
| 330 | |
| 331 | def search_method_in_class( |
| 332 | self, method_name: str, class_name: str |
| 333 | ) -> tuple[str, str, bool]: |
| 334 | if class_name not in self.class_index: |
| 335 | tool_output = f"Could not find class {class_name} in the codebase." |
| 336 | summary = tool_output |
| 337 | return tool_output, summary, False |
| 338 | |
| 339 | # has this class, check its methods |
| 340 | search_res: list[SearchResult] = self._search_func_in_class( |
| 341 | method_name, class_name |
| 342 | ) |
| 343 | if not search_res: |
| 344 | tool_output = f"Could not find method {method_name} in class {class_name}`." |
| 345 | summary = tool_output |
| 346 | return tool_output, summary, False |
| 347 | |
| 348 | # found some methods, prepare the result |
| 349 | tool_output = f"Found {len(search_res)} methods with name {method_name} in class {class_name}:\n\n" |
| 350 | summary = tool_output |
| 351 | |
| 352 | # There can be multiple classes defined in multiple files, which contain the same method |
| 353 | # still trim the result, just in case |
| 354 | if len(search_res) > RESULT_SHOW_LIMIT: |
| 355 | tool_output += f"Too many results, showing full code for {RESULT_SHOW_LIMIT} of them, and the rest just file names:\n" |
| 356 | first_five = search_res[:RESULT_SHOW_LIMIT] |
| 357 | for idx, res in enumerate(first_five): |
| 358 | res_str = res.to_tagged_str(self.project_path) |
| 359 | tool_output += f"- Search result {idx + 1}:\n```\n{res_str}\n```\n" |
| 360 | # for the rest, collect the file names into a set |
| 361 | if rest := search_res[RESULT_SHOW_LIMIT:]: |
| 362 | tool_output += "Other results are in these files:\n" |
| 363 | tool_output += SearchResult.collapse_to_file_level(rest, self.project_path) |
| 364 | return tool_output, summary, True |
| 365 | |
| 366 | def search_method(self, method_name: str) -> tuple[str, str, bool]: |
| 367 | """ |
| 368 | Search for a method in the entire codebase. |
| 369 | """ |
| 370 | search_res: list[SearchResult] = self._search_func_in_code_base(method_name) |
| 371 | if not search_res: |
| 372 | tool_output = f"Could not find method {method_name} in the codebase." |
| 373 | summary = tool_output |
| 374 | return tool_output, summary, False |
| 375 | |
| 376 | tool_output = f"Found {len(search_res)} methods with name {method_name} in the codebase:\n\n" |
| 377 | summary = tool_output |
| 378 | |
| 379 | if len(search_res) > RESULT_SHOW_LIMIT: |
| 380 | tool_output += "They appeared in the following files:\n" |
| 381 | tool_output += SearchResult.collapse_to_file_level( |
| 382 | search_res, self.project_path |
| 383 | ) |
| 384 | else: |
| 385 | for idx, res in enumerate(search_res): |
| 386 | res_str = res.to_tagged_str(self.project_path) |
| 387 | tool_output += f"- Search result {idx + 1}:\n```\n{res_str}\n```\n" |
| 388 | |
| 389 | return tool_output, summary, True |
| 390 | |
| 391 | def search_code(self, code_str: str) -> tuple[str, str, bool]: |
| 392 | # attempt to search for this code string in all py files |
| 393 | all_search_results: list[SearchResult] = [] |
| 394 | for file_path in self.parsed_files: |
| 395 | searched_line_and_code: list[tuple[int, str]] = ( |
| 396 | search_utils.get_code_region_containing_code(file_path, code_str) |
| 397 | ) |
| 398 | if not searched_line_and_code: |
| 399 | continue |
| 400 | for searched in searched_line_and_code: |
| 401 | line_no, code_region = searched |
| 402 | # from line_no, check which function and class we are in |
| 403 | class_name, func_name = self.file_line_to_class_and_func( |
| 404 | file_path, line_no |
| 405 | ) |
| 406 | res = SearchResult(file_path, class_name, func_name, code_region) |
| 407 | all_search_results.append(res) |
| 408 | |
| 409 | if not all_search_results: |
| 410 | tool_output = f"Could not find code {code_str} in the codebase." |
| 411 | summary = tool_output |
| 412 | return tool_output, summary, False |
| 413 | |
| 414 | # good path |
| 415 | tool_output = f"Found {len(all_search_results)} snippets containing `{code_str}` in the codebase:\n\n" |
| 416 | summary = tool_output |
| 417 | |
| 418 | if len(all_search_results) > RESULT_SHOW_LIMIT: |
| 419 | tool_output += "They appeared in the following files:\n" |
| 420 | tool_output += SearchResult.collapse_to_file_level( |
| 421 | all_search_results, self.project_path |
| 422 | ) |
| 423 | else: |
| 424 | for idx, res in enumerate(all_search_results): |
| 425 | res_str = res.to_tagged_str(self.project_path) |
| 426 | tool_output += f"- Search result {idx + 1}:\n```\n{res_str}\n```\n" |
| 427 | return tool_output, summary, True |
| 428 | |
| 429 | def search_code_in_file( |
| 430 | self, code_str: str, file_name: str |
| 431 | ) -> tuple[str, str, bool]: |
| 432 | code_str = code_str.removesuffix(")") |
| 433 | |
| 434 | candidate_py_files = [f for f in self.parsed_files if f.endswith(file_name)] |
| 435 | if not candidate_py_files: |
| 436 | tool_output = f"Could not find file {file_name} in the codebase." |
| 437 | summary = tool_output |
| 438 | return tool_output, summary, False |
| 439 | |
| 440 | # start searching for code in the filtered files |
| 441 | all_search_results: list[SearchResult] = [] |
| 442 | for file_path in candidate_py_files: |
| 443 | searched_line_and_code: list[tuple[int, str]] = ( |
| 444 | search_utils.get_code_region_containing_code(file_path, code_str) |
| 445 | ) |
| 446 | if not searched_line_and_code: |
| 447 | continue |
| 448 | for searched in searched_line_and_code: |
| 449 | line_no, code_region = searched |
| 450 | # from line_no, check which function and class we are in |
| 451 | class_name, func_name = self.file_line_to_class_and_func( |
| 452 | file_path, line_no |
| 453 | ) |
| 454 | res = SearchResult(file_path, class_name, func_name, code_region) |
| 455 | all_search_results.append(res) |
| 456 | |
| 457 | if not all_search_results: |
| 458 | tool_output = f"Could not find code {code_str} in file {file_name}." |
| 459 | summary = tool_output |
| 460 | return tool_output, summary, False |
| 461 | |
| 462 | # good path |
| 463 | # There can be a lot of results, from multiple files. |
| 464 | tool_output = f"Found {len(all_search_results)} snippets with code {code_str} in file {file_name}:\n\n" |
| 465 | summary = tool_output |
| 466 | if len(all_search_results) > RESULT_SHOW_LIMIT: |
| 467 | tool_output += "They appeared in the following methods:\n" |
| 468 | tool_output += SearchResult.collapse_to_method_level( |
| 469 | all_search_results, self.project_path |
| 470 | ) |
| 471 | else: |
| 472 | for idx, res in enumerate(all_search_results): |
| 473 | res_str = res.to_tagged_str(self.project_path) |
| 474 | tool_output += f"- Search result {idx + 1}:\n```\n{res_str}\n```\n" |
| 475 | return tool_output, summary, True |
| 476 | |
| 477 | def retrieve_code_snippet( |
| 478 | self, file_path: str, start_line: int, end_line: int |
| 479 | ) -> str: |
| 480 | return search_utils.get_code_snippets(file_path, start_line, end_line) |