MCPcopy Create free account
hub / github.com/catid/supercharger / fix_ast_errors

Function fix_ast_errors

codegen/fix_ast_errors.py:177–243  ·  view source on GitHub ↗
(code, max_attempts=100, expandtabs=True, delete_on_error=True)

Source from the content-addressed store, hash-verified

175 return None
176
177def fix_ast_errors(code, max_attempts=100, expandtabs=True, delete_on_error=True):
178 median_tab_spaces = detect_median_indentation(code)
179 if median_tab_spaces <= 1:
180 median_tab_spaces = 4
181
182 if expandtabs:
183 code = code.expandtabs(median_tab_spaces)
184
185 attempts = 0
186
187 while attempts < max_attempts:
188 try_indent = False
189 try_unindent = False
190 close_delim = None
191 error = None
192
193 try:
194 ast.parse(code)
195 break
196 except Exception as e:
197 error = e
198 #print("ERROR: {}".format(e))
199 #print("CODE:\n---\n{}\n---\n".format(code))
200 if "expected ':'" in e.msg:
201 r, code = try_adding_colon(code, e)
202 if r: continue
203 elif "expected an indented block" in e.msg:
204 try_indent = True
205 elif "unexpected indent" in e.msg or "unindent does not match" in e.msg:
206 try_unindent = True
207 elif "was never closed" in e.msg:
208 close_delim = parse_unbalanced_paren(e.msg)
209 if close_delim:
210 r, code = try_closing_delim(code, error, flip_opening_delimiters(close_delim))
211 if r: continue
212 elif "does not match opening parenthesis" in e.msg:
213 closing, opening = extract_mismatched_delimiters(e.msg)
214 r, code = try_replacing_closing_with_opening(code, e, closing, flip_opening_delimiters(opening))
215 if r: continue
216 else:
217 try_indent = True
218 try_unindent = True
219
220 if error is None:
221 break
222
223 if try_indent:
224 r, code = try_indenting(code, error, delta=1)
225 if r: continue
226 if try_unindent:
227 r, code = try_indenting(code, error, delta=-1)
228 if r: continue
229
230 # Give up if we can't fix the error and don't want to delete the code
231 if not delete_on_error:
232 break
233
234 #print("FAILED TO FIX ERROR: {}".format(error))

Callers 4

clean_codeFunction · 0.90
run_test_casesMethod · 0.90
test_fix_indentationMethod · 0.90
run_test_casesMethod · 0.90

Calls 8

try_adding_colonFunction · 0.85
parse_unbalanced_parenFunction · 0.85
try_closing_delimFunction · 0.85
flip_opening_delimitersFunction · 0.85
try_indentingFunction · 0.85

Tested by 3

run_test_casesMethod · 0.72
test_fix_indentationMethod · 0.72
run_test_casesMethod · 0.72