File size: 6,203 Bytes
5e4510c |
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 |
"""
Utilities for code parsing, diffing, and manipulation
"""
import re
from typing import Dict, List, Optional, Tuple, Union
def parse_evolve_blocks(code: str) -> List[Tuple[int, int, str]]:
"""
Parse evolve blocks from code
Args:
code: Source code with evolve blocks
Returns:
List of tuples (start_line, end_line, block_content)
"""
lines = code.split("\n")
blocks = []
in_block = False
start_line = -1
block_content = []
for i, line in enumerate(lines):
if "# EVOLVE-BLOCK-START" in line:
in_block = True
start_line = i
block_content = []
elif "# EVOLVE-BLOCK-END" in line and in_block:
in_block = False
blocks.append((start_line, i, "\n".join(block_content)))
elif in_block:
block_content.append(line)
return blocks
def apply_diff(
original_code: str,
diff_text: str,
diff_pattern: str = r"<<<<<<< SEARCH\n(.*?)=======\n(.*?)>>>>>>> REPLACE",
) -> str:
"""
Apply a diff to the original code
Args:
original_code: Original source code
diff_text: Diff in the SEARCH/REPLACE format
diff_pattern: Regex pattern for the SEARCH/REPLACE format
Returns:
Modified code
"""
# Split into lines for easier processing
original_lines = original_code.split("\n")
result_lines = original_lines.copy()
# Extract diff blocks
diff_blocks = extract_diffs(diff_text, diff_pattern)
# Apply each diff block
for search_text, replace_text in diff_blocks:
search_lines = search_text.split("\n")
replace_lines = replace_text.split("\n")
# Find where the search pattern starts in the original code
for i in range(len(result_lines) - len(search_lines) + 1):
if result_lines[i : i + len(search_lines)] == search_lines:
# Replace the matched section
result_lines[i : i + len(search_lines)] = replace_lines
break
return "\n".join(result_lines)
def extract_diffs(
diff_text: str, diff_pattern: str = r"<<<<<<< SEARCH\n(.*?)=======\n(.*?)>>>>>>> REPLACE"
) -> List[Tuple[str, str]]:
"""
Extract diff blocks from the diff text
Args:
diff_text: Diff in the SEARCH/REPLACE format
diff_pattern: Regex pattern for the SEARCH/REPLACE format
Returns:
List of tuples (search_text, replace_text)
"""
diff_blocks = re.findall(diff_pattern, diff_text, re.DOTALL)
return [(match[0].rstrip(), match[1].rstrip()) for match in diff_blocks]
def parse_full_rewrite(llm_response: str, language: str = "python") -> Optional[str]:
"""
Extract a full rewrite from an LLM response
Args:
llm_response: Response from the LLM
language: Programming language
Returns:
Extracted code or None if not found
"""
code_block_pattern = r"```" + language + r"\n(.*?)```"
matches = re.findall(code_block_pattern, llm_response, re.DOTALL)
if matches:
return matches[0].strip()
# Fallback to any code block
code_block_pattern = r"```(.*?)```"
matches = re.findall(code_block_pattern, llm_response, re.DOTALL)
if matches:
return matches[0].strip()
# Fallback to plain text
return llm_response
def format_diff_summary(diff_blocks: List[Tuple[str, str]]) -> str:
"""
Create a human-readable summary of the diff
Args:
diff_blocks: List of (search_text, replace_text) tuples
Returns:
Summary string
"""
summary = []
for i, (search_text, replace_text) in enumerate(diff_blocks):
search_lines = search_text.strip().split("\n")
replace_lines = replace_text.strip().split("\n")
# Create a short summary
if len(search_lines) == 1 and len(replace_lines) == 1:
summary.append(f"Change {i+1}: '{search_lines[0]}' to '{replace_lines[0]}'")
else:
search_summary = (
f"{len(search_lines)} lines" if len(search_lines) > 1 else search_lines[0]
)
replace_summary = (
f"{len(replace_lines)} lines" if len(replace_lines) > 1 else replace_lines[0]
)
summary.append(f"Change {i+1}: Replace {search_summary} with {replace_summary}")
return "\n".join(summary)
def calculate_edit_distance(code1: str, code2: str) -> int:
"""
Calculate the Levenshtein edit distance between two code snippets
Args:
code1: First code snippet
code2: Second code snippet
Returns:
Edit distance (number of operations needed to transform code1 into code2)
"""
if code1 == code2:
return 0
# Simple implementation of Levenshtein distance
m, n = len(code1), len(code2)
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
cost = 0 if code1[i - 1] == code2[j - 1] else 1
dp[i][j] = min(
dp[i - 1][j] + 1, # deletion
dp[i][j - 1] + 1, # insertion
dp[i - 1][j - 1] + cost, # substitution
)
return dp[m][n]
def extract_code_language(code: str) -> str:
"""
Try to determine the language of a code snippet
Args:
code: Code snippet
Returns:
Detected language or "unknown"
"""
# Look for common language signatures
if re.search(r"^(import|from|def|class)\s", code, re.MULTILINE):
return "python"
elif re.search(r"^(package|import java|public class)", code, re.MULTILINE):
return "java"
elif re.search(r"^(#include|int main|void main)", code, re.MULTILINE):
return "cpp"
elif re.search(r"^(function|var|let|const|console\.log)", code, re.MULTILINE):
return "javascript"
elif re.search(r"^(module|fn|let mut|impl)", code, re.MULTILINE):
return "rust"
elif re.search(r"^(SELECT|CREATE TABLE|INSERT INTO)", code, re.MULTILINE):
return "sql"
return "unknown"
|