Skip to content

Commit

Permalink
Correct parsing of array slices
Browse files Browse the repository at this point in the history
  • Loading branch information
knutwannheden committed Nov 19, 2024
1 parent 3ddde7a commit 8d9a5a0
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
16 changes: 9 additions & 7 deletions rewrite/rewrite/python/_parser_visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1745,19 +1745,21 @@ def visit_Slice(self, node):
prefix = self.__whitespace()

lower_expr = self.__convert(node.lower) if node.lower else None
right_padding = self.__whitespace(':')
right_padding = self.__whitespace(':') if node.lower else Space.EMPTY
lower = self.__pad_right(lower_expr, right_padding) if lower_expr else None
self._cursor += 1

upper_expr = self.__convert(node.upper) if node.upper else None
right_padding = self.__whitespace()
upper = self.__pad_right(upper_expr if node.upper else j.Empty(random_id(), Space.EMPTY, Markers.EMPTY), right_padding)
has_step = self.__cursor_at(':')
upper = self.__pad_right(upper_expr if node.upper else j.Empty(random_id(), self.__whitespace(), Markers.EMPTY), right_padding)
self._cursor += 1

step = self.__pad_right(
self.__convert(node.step) if node.step else j.Empty(random_id(), Space.EMPTY, Markers.EMPTY),
self.__whitespace(']')) if node.step or has_step else None
if has_step:
self._cursor += 1
step = self.__pad_right(
self.__convert(node.step) if node.step else j.Empty(random_id(), Space.EMPTY, Markers.EMPTY),
self.__whitespace(']')) if node.step or has_step else Space.EMPTY
else:
step = None

return py.Slice(
random_id(),
Expand Down
11 changes: 11 additions & 0 deletions rewrite/tests/python/all/array_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ def test_array_slice_all_empty():
rewrite_run(python("a = [1, 2][ : : ]"))


def test_comment():
# language=python
rewrite_run(
python(r'''
a = d[:0]
a = d[0:]
'''
)
)


def test_array_slice_empty_upper_and_step():
# language=python
rewrite_run(python("a = [1, 2][0::]"))
Expand Down

0 comments on commit 8d9a5a0

Please sign in to comment.