Skip to content

Commit

Permalink
Fix bug: source_from_ast should consider the garbage at the end
Browse files Browse the repository at this point in the history
  • Loading branch information
hsfzxjy committed Feb 10, 2021
1 parent 9687d38 commit accc5a7
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion lambdex/utils/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,19 @@ def ast_from_source(source, keyword: str):
source_lines = ['\n'] * lnum + inspect.getblock(lines[lnum:])
source = ''.join(source_lines)

return ast.parse(source).body[0]
# Some garbage may still remain at the end, we alternatively try compiling
# and popping the last character until the source is valid.
exc = None
original_source = source
while source:
try:
return ast.parse(source).body[0]
except SyntaxError as e:
source = source[:-1]
exc = e
else:
# This should never happen
raise RuntimeError('cannot parse the snippet into AST:\n{}'.format(original_source)) from exc


def recursively_set_attr(node: ast.AST, attrname: str, value):
Expand Down

0 comments on commit accc5a7

Please sign in to comment.