From 3ddde7aa82ce42a8322fae3992887e8d881514ec Mon Sep 17 00:00:00 2001 From: Knut Wannheden Date: Thu, 14 Nov 2024 15:37:30 +0100 Subject: [PATCH] Small corrections to array slice parsing --- rewrite/rewrite/python/_parser_visitor.py | 24 +++++++++++++++-------- rewrite/tests/python/all/array_test.py | 10 ++++++++++ 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/rewrite/rewrite/python/_parser_visitor.py b/rewrite/rewrite/python/_parser_visitor.py index 1cb624cd..d897acbe 100644 --- a/rewrite/rewrite/python/_parser_visitor.py +++ b/rewrite/rewrite/python/_parser_visitor.py @@ -1743,14 +1743,22 @@ def visit_SetComp(self, node): def visit_Slice(self, node): prefix = self.__whitespace() - if node.lower: - lower = self.__pad_right(self.__convert(node.lower), self.__source_before(':')) - else: - lower = self.__pad_right(j.Empty(random_id(), Space.EMPTY, Markers.EMPTY), self.__source_before(':')) - upper = self.__pad_right( - self.__convert(node.upper) if node.upper else j.Empty(random_id(), Space.EMPTY, Markers.EMPTY), - self.__source_before(':') if node.step else self.__whitespace('\n')) - step = self.__pad_right(self.__convert(node.step), self.__whitespace('\n')) if node.step else None + + lower_expr = self.__convert(node.lower) if node.lower else None + right_padding = self.__whitespace(':') + 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() + 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 + return py.Slice( random_id(), prefix, diff --git a/rewrite/tests/python/all/array_test.py b/rewrite/tests/python/all/array_test.py index 11212be9..17c68228 100644 --- a/rewrite/tests/python/all/array_test.py +++ b/rewrite/tests/python/all/array_test.py @@ -26,6 +26,16 @@ def test_array_slice_no_upper(): rewrite_run(python("a = [1, 2][0:]")) +def test_array_slice_all_empty(): + # language=python + rewrite_run(python("a = [1, 2][ : : ]")) + + +def test_array_slice_empty_upper_and_step(): + # language=python + rewrite_run(python("a = [1, 2][0::]")) + + def test_array_slice_no_lower(): # language=python rewrite_run(python("a = [1, 2][:1]"))