From accc5a7a1cf59c7d60558ed527b226fc3814b37a Mon Sep 17 00:00:00 2001 From: hsfzxjy Date: Wed, 10 Feb 2021 13:12:21 +0800 Subject: [PATCH] Fix bug: `source_from_ast` should consider the garbage at the end --- lambdex/utils/ast.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/lambdex/utils/ast.py b/lambdex/utils/ast.py index d9c3462..a7ecfbf 100644 --- a/lambdex/utils/ast.py +++ b/lambdex/utils/ast.py @@ -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):