Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle nested if statements with alternates in printer #3180

Merged
merged 1 commit into from
Dec 18, 2015
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
8 changes: 7 additions & 1 deletion packages/babel-generator/src/generators/statements.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export function IfStatement(node: Object) {
this.push(")");
this.space();

let needsBlock = node.alternate && t.isIfStatement(node.consequent);
let needsBlock = node.alternate && t.isIfStatement(getLastStatement(node.consequent));
if (needsBlock) {
this.push("{");
this.newline();
Expand All @@ -38,6 +38,12 @@ export function IfStatement(node: Object) {
}
}

// Recursively get the last statement.
function getLastStatement(statement) {
if (!t.isStatement(statement.body)) return statement;
return getLastStatement(statement.body);
}

export function ForStatement(node: Object) {
this.keyword("for");
this.push("(");
Expand Down
22 changes: 21 additions & 1 deletion packages/babel-generator/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,32 @@ suite("generation", function () {
assert.ok(t.VISITOR_KEYS[type], type + " should not exist");
});
});
});


test("valid code", function() {
suite("programmatic generation", function() {
test("numeric member expression", function() {
// Should not generate `0.foo`
var mem = t.memberExpression(t.numericLiteral(60702), t.identifier("foo"));
new Function(generate.default(mem).code);
});

test("nested if statements needs block", function() {
var ifStatement = t.ifStatement(
t.stringLiteral("top cond"),
t.whileStatement(
t.stringLiteral("while cond"),
t.ifStatement(
t.stringLiteral("nested"),
t.expressionStatement(t.numericLiteral(1))
)
),
t.expressionStatement(t.stringLiteral("alt"))
);

var ast = parse(generate.default(ifStatement).code);
assert.equal(ast.program.body[0].consequent.type, 'BlockStatement');
});
});

var suites = require("babel-helper-fixtures").default(__dirname + "/fixtures");
Expand Down