Skip to content

Commit

Permalink
bpo-40726: handle uninitalized end_lineno on ast.increment_lineno (GH…
Browse files Browse the repository at this point in the history
…-20312)

(cherry picked from commit 8f4380d)

Co-authored-by: Batuhan Taskaya <batuhanosmantaskaya@gmail.com>
  • Loading branch information
miss-islington and isidentical committed Aug 5, 2020
1 parent ea68063 commit a132098
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
13 changes: 10 additions & 3 deletions Lib/ast.py
Expand Up @@ -180,7 +180,11 @@ def copy_location(new_node, old_node):
for attr in 'lineno', 'col_offset', 'end_lineno', 'end_col_offset':
if attr in old_node._attributes and attr in new_node._attributes:
value = getattr(old_node, attr, None)
if value is not None:
# end_lineno and end_col_offset are optional attributes, and they
# should be copied whether the value is None or not.
if value is not None or (
hasattr(old_node, attr) and attr.startswith("end_")
):
setattr(new_node, attr, value)
return new_node

Expand Down Expand Up @@ -229,8 +233,11 @@ def increment_lineno(node, n=1):
for child in walk(node):
if 'lineno' in child._attributes:
child.lineno = getattr(child, 'lineno', 0) + n
if 'end_lineno' in child._attributes:
child.end_lineno = getattr(child, 'end_lineno', 0) + n
if (
"end_lineno" in child._attributes
and (end_lineno := getattr(child, "end_lineno", 0)) is not None
):
child.end_lineno = end_lineno + n
return node


Expand Down
11 changes: 11 additions & 0 deletions Lib/test/test_ast.py
Expand Up @@ -812,6 +812,12 @@ def test_copy_location(self):
'lineno=1, col_offset=4, end_lineno=1, end_col_offset=5), lineno=1, '
'col_offset=0, end_lineno=1, end_col_offset=5))'
)
src = ast.Call(col_offset=1, lineno=1, end_lineno=1, end_col_offset=1)
new = ast.copy_location(src, ast.Call(col_offset=None, lineno=None))
self.assertIsNone(new.end_lineno)
self.assertIsNone(new.end_col_offset)
self.assertEqual(new.lineno, 1)
self.assertEqual(new.col_offset, 1)

def test_fix_missing_locations(self):
src = ast.parse('write("spam")')
Expand Down Expand Up @@ -851,6 +857,11 @@ def test_increment_lineno(self):
'lineno=4, col_offset=4, end_lineno=4, end_col_offset=5), lineno=4, '
'col_offset=0, end_lineno=4, end_col_offset=5))'
)
src = ast.Call(
func=ast.Name("test", ast.Load()), args=[], keywords=[], lineno=1
)
self.assertEqual(ast.increment_lineno(src).lineno, 2)
self.assertIsNone(ast.increment_lineno(src).end_lineno)

def test_iter_fields(self):
node = ast.parse('foo()', mode='eval')
Expand Down
@@ -0,0 +1,2 @@
Handle cases where the ``end_lineno`` is ``None`` on
:func:`ast.increment_lineno`.

0 comments on commit a132098

Please sign in to comment.