Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions personal_python_ast_optimizer/parser/skipper.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,21 @@ def visit_IfExp(self, node: ast.IfExp) -> ast.AST | None:

return parsed_node

def visit_While(self, node: ast.While) -> ast.AST | None:
parsed_node = self.generic_visit(node)

if isinstance(parsed_node, ast.While) and isinstance(
parsed_node.test, ast.Constant
):
if not parsed_node.test.value:
return None

# 1 is faster than True in python 2
# They are the same in python 3, but less size
parsed_node.test.value = 1

return parsed_node

def visit_Return(self, node: ast.Return) -> ast.AST:
if is_return_none(node):
node.value = None
Expand Down Expand Up @@ -553,6 +568,9 @@ def visit_Call(self, node: ast.Call) -> ast.AST | None:

return self.generic_visit(node)

def visit_Constant(self, node: ast.Constant) -> ast.Constant:
return node

def visit_Expr(self, node: ast.Expr) -> ast.AST | None:
if (
isinstance(node.value, ast.Call)
Expand Down Expand Up @@ -811,3 +829,6 @@ def visit_Break(self, node: ast.Break) -> ast.Break:

def visit_Continue(self, node: ast.Continue) -> ast.Continue:
return node

def visit_Constant(self, node: ast.Constant) -> ast.Constant:
return node
16 changes: 16 additions & 0 deletions tests/parser/test_assert.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from personal_python_ast_optimizer.parser.config import TokenTypesConfig
from tests.utils import BeforeAndAfter, run_minifier_and_assert_correct


Expand All @@ -13,3 +14,18 @@ def test_foo():
)

run_minifier_and_assert_correct(before_and_after)


def test_skip_assert():
before_and_after = BeforeAndAfter(
"""
while 1:
assert val
foo()
""",
"while 1:foo()",
)

run_minifier_and_assert_correct(
before_and_after, token_types_config=TokenTypesConfig(skip_asserts=True)
)
19 changes: 19 additions & 0 deletions tests/parser/test_while.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from tests.utils import BeforeAndAfter, run_minifier_and_assert_correct


def test_useless_while():
before_and_after = BeforeAndAfter(
"while 0:\n\tfoo()",
"",
)

run_minifier_and_assert_correct(before_and_after)


def test_while_true():
before_and_after = BeforeAndAfter(
"while True:\n\tfoo()",
"while 1:foo()",
)

run_minifier_and_assert_correct(before_and_after)