GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Psearch/context_repair.py at main · iSEngLab/Psearch Expand file tree/ Copy pathcontext_repair.pyMore file actions 441 lines (375 loc) · 19.4 KB / Copy pathcontext_repair.pyFile metadata and controls441 lines (375 loc) · 19.4 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 import os import re import json import framework from framework import get_bug_details, Bug from gpt import generate, generate_patches from neo4j_client import * from utils import run_bash client = Neo4jClient() def get_full_qualified_name_from_path(path: str): path_split = path.split(os.path.sep) if "org" in path_split: idx = path_split.index("org") qualified_name_split = path_split[idx:] qualified_name_split[-1] = qualified_name_split[-1].replace(".java", "") return ".".join(qualified_name_split) return None def get_simple_name_from_path(path: str): path_split = path.split(os.path.sep) if path_split[-1].endswith(".java"): return path_split[-1].replace(".java", "") return None def get_method_name_from_code(code: str): # Define the regular expression pattern = r'\w+\s+(\w+)\(' # Use a regular expression to match the function name match = re.search(pattern, code) if match: return match.group(1) # Return the function name captured by the regex group else: raise ValueError("Function definition not found!") def is_util_class(name: str): keywords = ['util', 'tool', 'helper', 'manager', 'factory', 'builder', 'converter'] for keyword in keywords: if keyword in name.lower(): return True return False def get_field_info(field_node): return {"comment": field_node['comment'], "content": field_node['content']} def remove_java_comments(code: str) -> str: """ Remove comments from Java code, including single-line, multi-line, and documentation comments. :param code: Input Java source code string :return: Code string after removing comments """ # Regular expression for matching multi-line comments (/* ... */) multiline_pattern = r'/\*.*?\*/' # Regular expression for matching single-line comments (// ...) singleline_pattern = r'(?<![:\'"/])//.*?$' # Regular expression for matching documentation comments (/** ... */ or content in /* ... */) doc_comment_pattern = r'/\*\*.*?\*/' # Remove multi-line and documentation comments code = re.sub(multiline_pattern, '', code, flags=re.DOTALL) code = re.sub(doc_comment_pattern, '', code, flags=re.DOTALL) # Remove single-line comments code = re.sub(singleline_pattern, '', code, flags=re.MULTILINE) # Remove extra blank lines code = '\n'.join(line.rstrip() for line in code.splitlines() if line.strip()) return code def format_context(context_dict, include_external=False): context_str = "" # For intra-class context, only keep class fields and method lists internal_context = context_dict['internal_context'] context_str += "Fields of the buggy class:\n" for i, field_info in enumerate(internal_context['field']): context_str += f"Field{i + 1}\n - Definition: {remove_java_comments(field_info['content'])}\n - Comment: {field_info['comment']}\n" context_str += "==================================\n" context_str += "Methods of the buggy class:\n" for i, method_info in enumerate(internal_context['method']): context_str += f"Method{i + 1}\n - Signature: {method_info['signature']}\n - Summary: {method_info['summary']}\n" context_str += "==================================\n" external_context = context_dict['external_context'] # Inter-class context if include_external: context_str += "Classes relevant to the buggy method:\n" for i, relevant_class in enumerate(external_context['relevant_class']): context_str += f"Class{i + 1}: {relevant_class['name']}" context_str += f"Class{i + 1} has following methods:\n" for j, method_info in enumerate(relevant_class['method']): context_str += f"Method{j + 1}\n - Signature: {method_info['signature']}\n - Summary: {method_info['summary']}\n" context_str += "==================================\n" context_str += "Utility Classes which may contain useful methods:\n" for i, relevant_class in enumerate(external_context['util_class']): context_str += f"Class{i + 1}: {relevant_class['name']}" context_str += f"Class{i + 1} has following methods:\n" for j, method_info in enumerate(relevant_class['method']): context_str += f"Method{j + 1}\n - Signature: {method_info['signature']}\n - Summary: {method_info['summary']}\n" context_str += "==================================\n" context_str += "The buggy method also has external function calls, listed as follows:\n" for i, external_method in enumerate(external_context['external_invoke_method']): context_str += "\n" context_str += external_method context_str += "\n" context_str += "==================================\n" return context_str method_summary_prompt = ("Generate a concise and professional summary for the given function. The summary should " "include the following details:\n" "Purpose: A brief description of what the function does.\n" "Parameters: List and explain the inputs (if any) the function accepts, including their types " "and roles.\n" "Return Value: Describe the output of the function, including its type and significance.\n" "Key Logic: Highlight the main operations or logic implemented within the function.") method_brief_summary_prompt = ("Generate a one-sentence summary (less than 20 words) for the given function, " "describing its purpose.") def construct_initial_message(bug: Bug, mode: str, context: str): cot_prompt = ("Before you give the final answer, let's think step by step. You need to explain where bug happens " "and how your answer can avoid it.") context_str = f"Here are contexts which may help you fix the bug.\n{context}" if mode == "SL": prompt_header = f"""The following code contains a buggy line that has been removed.\n```java\n{bug.masked_code}\n``` This was the original buggy line which was removed by the infill location: ```java\n{bug.buggy_lines}\n```\nTest cases look like:```java\n{bug.extract_test_code}```\nThe code fails with the following test error:\n```\n{bug.failing_tests}\n```""" prompt_footer = f"Please provide the correct line at the infill location, only single line is allowed. Your answer should begin with ```java" elif mode == "SH": prompt_header = f"""The following code contains a buggy hunk that has been removed.\n```java\n{bug.masked_code}\n``` This was the original buggy hunk which was removed by the infill location: ```java\n{bug.buggy_lines}\n```\nTest cases look like:```java\n{bug.extract_test_code}```\nThe code fails with the following test error:\n```\n{bug.failing_tests}\n```""" prompt_footer = f"Please provide the correct hunk at the infill location, only single hunk is allowed. Your answer should begin with ```java" elif mode == "SF": prompt_header = f"The following code contains a bug\n```java\n{bug.code}\n```\nTest cases look like:```java\n{bug.extract_test_code}```\nThe code fails with the following test error:\n```\n{bug.failing_tests}\n```" prompt_footer = f"Please provide the correct function, starting with ```java" initial_prompt_message = f"""{prompt_header} {cot_prompt}\n {context_str}\n {prompt_footer}""" return initial_prompt_message def get_method_brief_info(method_node): """ A brief summary including the method signature and a short method description (fewer than 20 words) :param method_node: :return: """ method_content = method_node['content'] prompt = [{ 'role': 'user', 'content': method_brief_summary_prompt + f"\nThe method is:\n```java\n{method_content}\n```" }] method_brief_summary = generate(prompt) print(method_brief_summary) return { "signature": method_node['signature'], "summary": method_brief_summary } def extract_patch_from_response(response, mode=None): splitter_count = len(response.split("```java")) - 1 if splitter_count > 2: patch = response[response.rfind("```java") + len("```java") + 1:] patch = patch[:patch.find("\n```")] elif splitter_count > 0: patch = response[response.find("```java") + len("```java") + 1:] patch = patch[:patch.find("\n```")] else: patch = response if mode == "SL": while len(patch) > 0 and patch.startswith("\n"): patch = patch[1:] while len(patch) > 0 and patch.endswith("\n"): patch = patch[:-1] if "\n" in patch: patch = patch[:patch.find("\n")] return patch def construct_context_and_save(proj="Chart", bid=5, output_dir="./context"): if not os.path.exists(output_dir): os.makedirs(output_dir) bug = get_bug_details(proj, bid) path = run_bash("get_source_code_file_path", proj, bid).stdout # Defect file path bug_start_line = int(run_bash("get_first_change_line_count_number", proj, bid).stdout.split(",")[0]) # Defect start line bug_end_line = int(run_bash("get_last_change_line_count_number", proj, bid).stdout.split(",")[0]) # Defect end line class_full_qualified_name = get_full_qualified_name_from_path(path) # simple_name = get_simple_name_from_path(path) method_name = get_method_name_from_code(bug.code) method_full_qualified_name = class_full_qualified_name + "." + method_name # 1. Find the method node script = METHOD_QUERY(method_full_qualified_name, method_name) results = client.execute_query(script) buggy_method_node = None if len(results) == 0: # No function node found raise Exception("buggy method not found in KG") elif len(results) == 1: buggy_method_node = results[0]['n'] else: # Functions with the same name are matched by line number for result in results: if result['n']["start_line"] < bug_start_line and result['n']["end_line"] > bug_end_line: buggy_method_node = result['n'] break raise Exception("buggy method not found in KG") internal_context = {} # 2. Intra-class context: class fields and method list class_query = ClAZZ_QUERY(class_full_qualified_name) class_node = client.execute_query(class_query)[0]['n'] print("Defect class") print(class_node) field_list_query = FIELD_LIST_QUERY(class_full_qualified_name) field_nodes = [x['n'] for x in client.execute_query(field_list_query)] print("Class fields") field_info = [get_field_info(x) for x in field_nodes] internal_context['field'] = field_info print(field_info) method_list_query = METHOD_LIST_QUERY(class_full_qualified_name) method_nodes = [x['n'] for x in client.execute_query(method_list_query)] print("Method list") method_info = [get_method_brief_info(x) for x in method_nodes] internal_context['method'] = method_info print(method_info) # 3. Cross-class context external_context = { 'relevant_class': [], 'util_class': [], 'external_invoke_method': [] } # 3.1 Classes corresponding to local variables and parameters of the method params_type = buggy_method_node['params'] param_multiclass_query = ClAZZ_QUERY(params_type) param_class_nodes = [x['n'] for x in client.execute_query(param_multiclass_query)] local_variable_query = LOCAL_VARIABLE_QUERY(buggy_method_node['signature']) local_variable_nodes = [x['n'] for x in client.execute_query(local_variable_query)] local_variable_classes = [x['data_type'] for x in local_variable_nodes] local_variable_multiclass_query = ClAZZ_QUERY(local_variable_classes) local_variable_class_nodes = [x['n'] for x in client.execute_query(local_variable_multiclass_query)] class_nodes = param_class_nodes + local_variable_class_nodes # Step 1: Filter out the current class class_nodes = [x for x in class_nodes if x['full_qualified_name'] != class_node['full_qualified_name']] # Step 2: Deduplicate by `full_qualified_name` seen = set() class_nodes = [x for x in class_nodes if x['full_qualified_name'] not in seen and not seen.add(x['full_qualified_name'])] for class_node in class_nodes: data = {} class_node_name = class_node["full_qualified_name"] data['name'] = class_node_name method_list_query = METHOD_LIST_QUERY(class_node_name) method_nodes = [x['n'] for x in client.execute_query(method_list_query)] method_info = [get_method_brief_info(x) for x in method_nodes] data['method'] = method_info external_context['relevant_class'] = external_context['relevant_class'] + [data] # 3.2 Cross-class function calls method_invoke_query = METHOD2METHOD_INVOKE_QUERY(buggy_method_node['signature']) invoke_method_nodes = [x['n'] for x in client.execute_query(method_invoke_query)] invoke_method_nodes = [x for x in invoke_method_nodes if "test" not in x['name']] # Filter test methods # Separate intra-class and cross-class calls internal_invoke_method_nodes = [x for x in invoke_method_nodes if x['full_qualified_name'].startswith(class_node['full_qualified_name'])] external_invoke_method_nodes = [x for x in invoke_method_nodes if not x['full_qualified_name'].startswith(class_node['full_qualified_name'])] print("Intra-class calls") print(internal_invoke_method_nodes) # Intra-class calls print("Cross-class calls") print(external_invoke_method_nodes) # Cross-class calls Extract method bodies for cross-class calls external_invoke_seen = set() external_invoke_methods = [] for external_invoke_method_node in external_invoke_method_nodes: method_query = UNIQUE_METHOD_QUERY(external_invoke_method_node['full_qualified_name'], external_invoke_method_node['signature']) unique_method_node = client.execute_query(method_query)[0]['n'] # Skip constructors if unique_method_node['type'].lower() == "constructor": continue if ( unique_method_node['full_qualified_name'], external_invoke_method_node['signature']) in external_invoke_seen: continue external_invoke_seen.add((unique_method_node['full_qualified_name'], external_invoke_method_node['signature'])) external_invoke_methods.append(unique_method_node['content']) external_context['external_invoke_method'] = external_invoke_methods # 3.3 Parent class parent_class_query = PARENT_CLASS_QUERY(class_full_qualified_name) result = client.execute_query(parent_class_query) if len(result) == 0: # No parent class parent_class_node = None else: parent_class_node = result[0]['n'] print("Parent class") print(parent_class_node) # 3.4 Imported utility classes import_query = IMPORT_QUERY(class_full_qualified_name) import_class_nodes = [x['n'] for x in client.execute_query(import_query)] print("Imported classes") print([x['name'] for x in import_class_nodes]) # Filter utility classes import_util_class_nodes = [x for x in import_class_nodes if is_util_class(x['name'])] print("Imported utility classes") relevant_class_names = [x['name'] for x in external_context['relevant_class']] for import_util_class_node in import_util_class_nodes: # If already in related classes, no second lookup is needed if import_util_class_node['full_qualified_name'] in relevant_class_names: continue data = {} import_util_class_name = import_util_class_node["full_qualified_name"] data['name'] = import_util_class_name method_list_query = METHOD_LIST_QUERY(import_util_class_name) method_nodes = [x['n'] for x in client.execute_query(method_list_query)] method_info = [get_method_brief_info(x) for x in method_nodes] data['method'] = method_info external_context['util_class'] = external_context['util_class'] + [data] # Merge internal and external context into one dictionary context = { "project": proj, "bugid": bid, "internal_context": internal_context, "external_context": external_context } # Write the JSON file output_file = f"{output_dir}/context_{proj}_{bid}.json" # Output file name with open(output_file, "w", encoding="utf-8") as f: json.dump(context, f, ensure_ascii=False, indent=4) print(f"Context has been written to {output_file}") def repair(proj="Chart", bid=5, context_dir="./context", model="gpt-4o-mini", result_file="./context_repair_result" ".jsonl", num_patches=10): context_file = f"{context_dir}/context_{proj}_{bid}.json" # Output file name if not os.path.exists(context_file): construct_context_and_save(proj, bid, context_dir) context_dict = dict(json.load(open(context_file, 'r'))) context_str = format_context(context_dict, True) bug = get_bug_details(proj, bid) modes = list(bug.bug_type.split()) mode = modes[0] prompt = construct_initial_message(bug, mode, context_str) prompt = [{ "role": "user", "content": prompt }] print(prompt) responses = generate_patches(prompt, model, num_samples=num_patches) patches = [extract_patch_from_response(response, mode) for response in responses] for i, patch in enumerate(patches): test_result, result_reason, patch_diff = framework.validate_patch(bug=bug, proposed_patch=patch, mode=mode) if test_result == "PASS": print(f"Proposed patch of {bug.project}-{bug.bug_id} ({mode}) patch passed all tests") with open(result_file, "a") as f: record = { "project": bug.project, "bug_id": bug.bug_id, "eval": "PASS", "attempt": i + 1, "mode": mode, "patch": patch, "diff": patch_diff, } f.write(json.dumps(record) + "\n") return elif result_reason == bug.test_error_message: record = { "project": bug.project, "bug_id": bug.bug_id, "eval": result_reason, "attempt": i + 1, "mode": mode, "patch": patch, "diff": "", } with open(result_file, "a") as f: f.write(json.dumps(record) + "\n") print( f"Proposed patch of {bug.project}-{bug.bug_id} ({mode}) failed with same error message as original bug") else: record = { "project": bug.project, "bug_id": bug.bug_id, "eval": result_reason, "attempt": i + 1, "mode": mode, "patch": patch, "diff": "", } with open(result_file, "a") as f: f.write(json.dumps(record) + "\n") print( f"Proposed patch of {bug.project}-{bug.bug_id} ({mode}) failed with a different error message than original bug") with open(result_file, "a") as f: f.write(json.dumps(record) + "\n") if __name__ == '__main__': repair() |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |