Skip to content
This repository was archived by the owner on Oct 1, 2019. It is now read-only.

Improve nested if printing #20

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 3 additions & 3 deletions src/printer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,13 +143,13 @@ function printIf(path, print) {
const n = path.getValue();

if (n.orelse && n.orelse.length > 0) {
if (n.orelse[0].ast_type === "If") {
if (n.orelse.length === 1 && n.orelse[0].ast_type === "If") {
return concat(path.map(printElseBody, "orelse"));
}
return concat([
hardline,
"else:",
concat(path.map(printElseBody, "orelse"))
indent(concat(path.map(printElseBody, "orelse")))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just don't use printElseBody here and you should be good. You only need special-case handling for the elif case.

]);
}
}
Expand All @@ -170,7 +170,7 @@ function printIf(path, print) {
])
);
} else {
parts.push(indent(concat([hardline, path.call(print)])));
parts.push(concat([hardline, path.call(print)]));
}

const orElse = printOrElse(path);
Expand Down
16 changes: 16 additions & 0 deletions tests/python_elif_multi_body/__snapshots__/jsfmt.spec.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,27 @@ if condition:
else:
assert something
another_statement()

if foo:
foo()
else:
if bar:
bar()
if baz:
baz()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if condition:
pass
else:
assert something
another_statement()

if foo:
foo()
else:
if bar:
bar()
if baz:
baz()

`;
8 changes: 8 additions & 0 deletions tests/python_elif_multi_body/elif_multi_body.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,11 @@
else:
assert something
another_statement()

if foo:
foo()
else:
if bar:
bar()
if baz:
baz()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It'd be great to see some tests that have elif in them! Maybe something like

if foo:
    foo()
elif bar:
    bar()
else:
    if baz:
        baz()
    elif garply:
        garply()
    else:
        qux()

Maybe also a simple case like:

if a:
    a()
else:
    if b:
        b()

My guess is that to make the above cases work (and not, for instance, collapse the end of the second case into elif b) we're going to need to modify the printer function to use n.source (probably looking at what it starts with) to determine if the orelse is an else or elif.