Debian Codegraph @

friendly_traceback/utils.py

raw symbols SCIP
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 # purely for type checking
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 # type: ignore # noqa
33 evaluator = pure_eval.Evaluator.from_frame(frame)
34 return evaluator[node] # can raise an exception
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) # removes duplicates
64 words = sorted(list(words)) # get predictable order for tests
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: # example PI -> pi
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 # The following code, including comments, has been adapted from
98 # https://gist.github.com/giststhebearbear/4145811
99
100
101 def _leven(s1: str, s2: str, max_distance: int) -> int:
102 # get the smallest string so our rows are minimized
103 s1, s2 = (s1, s2) if len(s1) <= len(s2) else (s2, s1)
104 # set lengths
105 l1, l2 = len(s1), len(s2)
106
107 # We are simulating an NM matrix where n is the longer string
108 # and m is the shorter string. By doing this we can minimize
109 # memory usage to O(M).
110 # Since we are simulating the matrix we only maintain two rows
111 # at a time the current row and the previous rows.
112 # A move from the current cell looking at the cell before it indicates
113 # consideration of an insert operation.
114 # A move from the current cell looking at the cell above it indicates
115 # consideration of a deletion
116 # Both operations are cost 1
117 # A move from the current cell to the cell up and to the left indicates
118 # an edit operation of 0 cost for a matching character and a 1 cost for
119 # a non matching characters
120 # no row has been previously computed yet, set empty row
121 # Since this is also a Damerau-Levenshtein calculation transposition
122 # costs will be taken into account. These look back 2 characters to
123 # determine optimal cost based on a possible transposition
124 # example: aei -> aie with Levensthein has a cost of 2
125 # match a, change e->i change i->e => aie
126 # Damarau-Levenshtein has a cost of 1
127 # match a, transpose ei to ie => aie
128 prev_row: List[int] = []
129
130 # build first leven matrix row
131 # The first row represents transformation from an empty string
132 # to the shorter string making it static [0-n]
133 # since this row is static we can set it as
134 # cur_row and start computation at the second row or index 1
135 cur_row = [x for x in range(l1 + 1)]
136
137 # use second length to loop through all the rows being built
138 # we start at row one
139 for row_num in range(1, l2 + 1):
140 # set transposition, previous, and current
141 # because the row_num always increments by one
142 # we can use row_num to set the value representing
143 # the first column which is indicative of transforming TO
144 # the empty string from our longer string
145 # transposition row maintains an extra row so that it is possible
146 # for us to apply Damarau's formula
147 transposition_row, prev_row, cur_row = prev_row, cur_row, [row_num] + [0] * l1
148
149 # consider if we have passed the max distance if all paths through
150 # the transposition row are larger than the max we can stop calculating
151 # distance and return the last element in that row and return the max
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 # set the cell value - min distance to reach this
164 # position
165 cur_row[col_num] = min(insertion_cost, deletion_cost, change_cost)
166
167 # test for a possible transposition optimization
168 # check to see if we have at least 2 characters
169 if 1 < row_num <= col_num: # sourcery skip
170 # test for possible transposition
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 # the last cell of the matrix is ALWAYS the shortest distance between the two strings
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) # type: ignore
219 except Exception: # noqa
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 # The following is currently not used in friendly-traceback but
241 # is used by friendly. It is kept here as it is part of
242 # a trio of functions, with one being used in friendly-traceback.
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("^->") # Some lines include --> to indicate that the
253 # error continues on the next line
254 error_lines = {}
255 for index, line in enumerate(lines):
256 if set(line.strip().replace(" ", "")).issubset(caret_set) and "^" in line:
257 # Ensure the line contains only ^ and spaces
258 line = line.replace("-", " ").replace(">", " ").rstrip("\n")
259 # Then, add the amount of spaces corresponding to the number of
260 # characters in the line to be highlighted
261 line = line + " " * (len(lines[index - 1].rstrip("\n")) - len(line))
262 error_lines[index] = get_single_line_highlighting_ranges(line)
263 # includes the remaining range for the line to be highlighted
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 # include the last subrange
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)