| 1 |
"""utils.py |
| 2 |
|
| 3 |
A few useful objects which do not naturally fit anywhere else. |
| 4 |
""" |
| 5 |
|
| 6 |
import ast |
| 7 |
import difflib |
| 8 |
import types |
| 9 |
import uuid |
| 10 |
from typing import Any, Dict, Iterable, List, Tuple |
| 11 |
|
| 12 |
import pure_eval |
| 13 |
|
| 14 |
from .tb_data import TracebackData |
| 15 |
|
| 16 |
|
| 17 |
def unique_variable_name() -> str: |
| 18 |
"""Creates a unique variable name. Useful when attempting to introduce |
| 19 |
a new token to see if it can fix specific cases of SyntaxError.""" |
| 20 |
name = uuid.uuid4() |
| 21 |
return f"_{name.hex}" |
| 22 |
|
| 23 |
|
| 24 |
def eval_expr(expr: str, frame: types.FrameType) -> Any: |
| 25 |
"""Attempts to evaluate the expression 'expr' in a frame. |
| 26 |
Note that 'expr' might be a string containing leading spaces which need |
| 27 |
to be removed prior to being evaluated. |
| 28 |
|
| 29 |
This can raise some exceptions which are meant to be caught by the |
| 30 |
calling function. |
| 31 |
""" |
| 32 |
node = ast.parse(expr.strip()).body[0].value |
| 33 |
evaluator = pure_eval.Evaluator.from_frame(frame) |
| 34 |
return evaluator[node] |
| 35 |
|
| 36 |
|
| 37 |
def get_similar_words(word_with_typo: str, words: Iterable[str]) -> List[str]: |
| 38 |
"""Returns a list of similar words. |
| 39 |
|
| 40 |
The parameters we chose are based on experimenting with |
| 41 |
different values of the cutoff parameter for the difflib function |
| 42 |
get_close_matches. |
| 43 |
|
| 44 |
Suppose we have the following words: |
| 45 |
['cos', 'cosh', 'acos', 'acosh'] |
| 46 |
If we use a cutoff of 0.66, and ask for a maximum of 4 matches, |
| 47 |
all will be a match for 'cost'. However, if we increase the cutoff |
| 48 |
to 0.67, 'acosh' will be dropped from the list, which seems sensible. |
| 49 |
|
| 50 |
However, this cutoff is "too generous" when dealing with long words. |
| 51 |
Using a cutoff up to 0.75 will result in both 'ascii_lowercase' |
| 52 |
and 'ascii_uppercase' matching 'ascii_lowecase'. Increasing the cutoff |
| 53 |
to 0.76 will drop ascii_uppercase as a match which also seems sensible. |
| 54 |
|
| 55 |
We thus use a heuristic cutoff based on length which ends up |
| 56 |
matching our expectation as to what a close match should be. |
| 57 |
|
| 58 |
We also do not return any matches for single character variables, |
| 59 |
nor do we consider single character variable potential matches. |
| 60 |
""" |
| 61 |
if len(word_with_typo) == 1: |
| 62 |
return [] |
| 63 |
words = set(words) |
| 64 |
words = sorted(list(words)) |
| 65 |
|
| 66 |
if 2 <= len(word_with_typo) <= 4: |
| 67 |
words = [word for word in words if 2 <= len(word) <= 5] |
| 68 |
max_dist = 1 |
| 69 |
elif 5 <= len(word_with_typo) <= 8: |
| 70 |
words = [word for word in words if 4 <= len(word) <= 10] |
| 71 |
max_dist = 2 |
| 72 |
else: |
| 73 |
words = [word for word in words if len(word) >= 7] |
| 74 |
max_dist = 3 |
| 75 |
|
| 76 |
similar_words: Dict[int, List[str]] = {} |
| 77 |
for word in words: |
| 78 |
distance = _leven(word_with_typo, word, max_dist + 1) |
| 79 |
if distance <= max_dist: |
| 80 |
if distance in similar_words: |
| 81 |
similar_words[distance].append(word) |
| 82 |
else: |
| 83 |
similar_words[distance] = [word] |
| 84 |
|
| 85 |
similar = [] |
| 86 |
for distance in range(1, max_dist + 1): |
| 87 |
if distance in similar_words and similar_words[distance]: |
| 88 |
similar.extend(similar_words[distance]) |
| 89 |
if not similar: |
| 90 |
if word_with_typo.lower() in words: |
| 91 |
similar.append(word_with_typo.lower()) |
| 92 |
elif word_with_typo.upper() in words: |
| 93 |
similar.append(word_with_typo.upper()) |
| 94 |
return similar |
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
def _leven(s1: str, s2: str, max_distance: int) -> int: |
| 102 |
|
| 103 |
s1, s2 = (s1, s2) if len(s1) <= len(s2) else (s2, s1) |
| 104 |
|
| 105 |
l1, l2 = len(s1), len(s2) |
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
prev_row: List[int] = [] |
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
cur_row = [x for x in range(l1 + 1)] |
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
for row_num in range(1, l2 + 1): |
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
transposition_row, prev_row, cur_row = prev_row, cur_row, [row_num] + [0] * l1 |
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
if transposition_row and all( |
| 153 |
cell_value > max_distance for cell_value in transposition_row |
| 154 |
): |
| 155 |
return max_distance |
| 156 |
|
| 157 |
for col_num in range(1, l1 + 1): |
| 158 |
insertion_cost = cur_row[col_num - 1] + 1 |
| 159 |
deletion_cost = prev_row[col_num] + 1 |
| 160 |
change_cost = prev_row[col_num - 1] + ( |
| 161 |
0 if s1[col_num - 1] == s2[row_num - 1] else 1 |
| 162 |
) |
| 163 |
|
| 164 |
|
| 165 |
cur_row[col_num] = min(insertion_cost, deletion_cost, change_cost) |
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
if 1 < row_num <= col_num: |
| 170 |
|
| 171 |
if ( |
| 172 |
s1[col_num - 1] == s2[col_num - 2] |
| 173 |
and s2[col_num - 1] == s1[col_num - 2] |
| 174 |
): |
| 175 |
cur_row[col_num] = min( |
| 176 |
cur_row[col_num], transposition_row[col_num - 2] + 1 |
| 177 |
) |
| 178 |
|
| 179 |
|
| 180 |
return cur_row[-1] |
| 181 |
|
| 182 |
|
| 183 |
def list_to_string(list_: Iterable[str], sep: str = ", ") -> str: |
| 184 |
"""Transforms a list of names, like ['a', 'b', 'c'], into a single |
| 185 |
string of names, like "a, b, c".""" |
| 186 |
result = ["{c}".format(c=c.replace("'", "")) for c in list_] |
| 187 |
return sep.join(result) |
| 188 |
|
| 189 |
|
| 190 |
def expected_in_result(expected: str, result: str) -> Tuple[bool, str]: |
| 191 |
"""Used in tests. Intended to help more quickly identify |
| 192 |
differences between what was expected and what was found.""" |
| 193 |
if expected in result: |
| 194 |
return True, "Test is satisfied: 'expected' is found in 'result'." |
| 195 |
result = result.strip(" ") |
| 196 |
lines = result.splitlines() |
| 197 |
best_ratio = 0.0 |
| 198 |
best_line = "" |
| 199 |
for line in lines: |
| 200 |
line = line.strip(" ") |
| 201 |
ratio = difflib.SequenceMatcher(None, expected, line).ratio() |
| 202 |
if ratio > best_ratio: |
| 203 |
best_ratio = ratio |
| 204 |
best_line = line |
| 205 |
|
| 206 |
if result == best_line: |
| 207 |
return False, "Only differences are different white spaces at the ends." |
| 208 |
|
| 209 |
return False, "\n" + "\n".join(difflib.ndiff([expected], [best_line])) |
| 210 |
|
| 211 |
|
| 212 |
def get_bad_statement(tb_data: TracebackData) -> str: |
| 213 |
"""This function attempts to recover a complete statement |
| 214 |
even if it spans multiple lines.""" |
| 215 |
try: |
| 216 |
ex = tb_data.records[-1].executing |
| 217 |
[statement] = ex.statements |
| 218 |
return ex.source.asttokens().get_text(statement) |
| 219 |
except Exception: |
| 220 |
if hasattr(tb_data, "original_bad_line"): |
| 221 |
return tb_data.original_bad_line |
| 222 |
elif hasattr(tb_data, "bad_line"): |
| 223 |
return tb_data.bad_line |
| 224 |
return "" |
| 225 |
|
| 226 |
|
| 227 |
def to_code_block(code: str) -> str: |
| 228 |
"""Takes some code and indent it with an added empty line at the top |
| 229 |
and bottom so that it is usable as a Markdown code block without |
| 230 |
showing the triple backquotes. |
| 231 |
""" |
| 232 |
indent = " " * 4 |
| 233 |
new_lines = ["\n"] |
| 234 |
lines = code.split("\n") |
| 235 |
new_lines.extend(f"{indent}{line}" for line in lines) |
| 236 |
new_lines.append("\n") |
| 237 |
return "\n".join(new_lines) |
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
def get_highlighting_ranges(lines: List[str]) -> Dict[int, List[Tuple[int, int]]]: |
| 244 |
"""Given a block of code highlighted primarily with carets (^), |
| 245 |
this function will identify the lines containing carets and break up |
| 246 |
that line into sub-ranges, showing at which indices the carets |
| 247 |
begin and end. |
| 248 |
|
| 249 |
It returns a dict whose index is the line number where the carets |
| 250 |
were found, and the content is a list of sub-ranges. |
| 251 |
""" |
| 252 |
caret_set = set("^->") |
| 253 |
|
| 254 |
error_lines = {} |
| 255 |
for index, line in enumerate(lines): |
| 256 |
if set(line.strip().replace(" ", "")).issubset(caret_set) and "^" in line: |
| 257 |
|
| 258 |
line = line.replace("-", " ").replace(">", " ").rstrip("\n") |
| 259 |
|
| 260 |
|
| 261 |
line = line + " " * (len(lines[index - 1].rstrip("\n")) - len(line)) |
| 262 |
error_lines[index] = get_single_line_highlighting_ranges(line) |
| 263 |
|
| 264 |
return error_lines |
| 265 |
|
| 266 |
|
| 267 |
def get_single_line_highlighting_ranges(line: str) -> List[Tuple[int, int]]: |
| 268 |
"""Given a single line containing alternating sequences of consecutive |
| 269 |
spaces and carets (^), this function will compute the position of the |
| 270 |
beginning and end of each sequence of consecutive characters, |
| 271 |
recording them as tuples |
| 272 |
|
| 273 |
It returns a list corresponding containing these tuples alternating between |
| 274 |
regions where carets are not found and where carets are found. |
| 275 |
""" |
| 276 |
caret_line = [] |
| 277 |
scanning_carets = False |
| 278 |
char_index = begin = 0 |
| 279 |
for char_index, char in enumerate(line): |
| 280 |
if not scanning_carets and char == "^": |
| 281 |
caret_line.append((begin, char_index)) |
| 282 |
begin = char_index |
| 283 |
scanning_carets = True |
| 284 |
if scanning_carets and char == " ": |
| 285 |
caret_line.append((begin, char_index)) |
| 286 |
begin = char_index |
| 287 |
scanning_carets = False |
| 288 |
|
| 289 |
caret_line.append((begin, char_index + 1)) |
| 290 |
return caret_line |
| 291 |
|
| 292 |
|
| 293 |
def create_caret_highlighted(caret_line: List[Tuple[int, int]]) -> str: |
| 294 |
"""Creates a line containing alternating sequences of spaces |
| 295 |
and carets, from a list containing a series of tuples denoting |
| 296 |
the range in which the carets are found. |
| 297 |
|
| 298 |
It is the inverse of get_single_line_highlighting_ranges(). |
| 299 |
""" |
| 300 |
line = [] |
| 301 |
insert_caret = False |
| 302 |
for begin, end in caret_line: |
| 303 |
if insert_caret: |
| 304 |
line.append("^" * (end - begin)) |
| 305 |
else: |
| 306 |
line.append(" " * (end - begin)) |
| 307 |
insert_caret = not insert_caret |
| 308 |
return "".join(line) |