diff --git a/parso/python/diff.py b/parso/python/diff.py index b373073..5ca4fef 100644 --- a/parso/python/diff.py +++ b/parso/python/diff.py @@ -638,21 +638,23 @@ class _NodesTree(object): working_stack = new_working_stack had_valid_suite_last = True - elif (last_node.type in ('error_leaf', 'error_node') or - _is_flow_node(new_nodes[-1])): - # Error leafs/nodes don't have a defined start/end. Error - # nodes might not end with a newline (e.g. if there's an - # open `(`). Therefore ignore all of them unless they are - # succeeded with valid parser state. - # If we copy flows at the end, they might be continued - # after the copy limit (in the new parser). - # In this while loop we try to remove until we find a newline. - new_nodes.pop() - while new_nodes: - last_node = new_nodes[-1] - if last_node.get_last_leaf().type == 'newline': - break + if new_nodes: + last_node = new_nodes[-1] + if (last_node.type in ('error_leaf', 'error_node') or + _is_flow_node(new_nodes[-1])): + # Error leafs/nodes don't have a defined start/end. Error + # nodes might not end with a newline (e.g. if there's an + # open `(`). Therefore ignore all of them unless they are + # succeeded with valid parser state. + # If we copy flows at the end, they might be continued + # after the copy limit (in the new parser). + # In this while loop we try to remove until we find a newline. new_nodes.pop() + while new_nodes: + last_node = new_nodes[-1] + if last_node.get_last_leaf().type == 'newline': + break + new_nodes.pop() if new_nodes: if had_valid_suite_last: diff --git a/test/test_diff_parser.py b/test/test_diff_parser.py index de6a9ee..af4acf6 100644 --- a/test/test_diff_parser.py +++ b/test/test_diff_parser.py @@ -852,3 +852,35 @@ def test_error_dedent_issues(differ): differ.initialize(code1) differ.parse(code2, parsers=5, copies=1, expect_error_leaves=True) differ.parse(code1, parsers=1, copies=0) + + +def test_random_text_insertion(differ): + code1 = dedent('''\ +class C: + def f(): + return node + + def g(): + try: + 1 + except KeyError: + 2 + ''') + + code2 = dedent('''\ +class C: + def f(): + return node +Some'random text: yeah + for push in plan.dfa_pushes: + + def g(): + try: + 1 + except KeyError: + 2 + ''') + + differ.initialize(code1) + differ.parse(code2, parsers=1, copies=1, expect_error_leaves=True) + differ.parse(code1, parsers=1, copies=1)