fixing the trailing-else-in-switch-getting-sucked-in-bug, Issue 195.

This commit is contained in:
Jeremy Ashkenas 2010-02-22 19:22:09 -05:00
parent 15b86a5f7a
commit a64afe6162
6 changed files with 28 additions and 9 deletions

View File

@ -462,7 +462,7 @@
Switch: [o("SWITCH Expression INDENT Whens OUTDENT", function() {
return $4.rewrite_condition($2);
}), o("SWITCH Expression INDENT Whens ELSE Block OUTDENT", function() {
return $4.rewrite_condition($2).add_else($6);
return $4.rewrite_condition($2).add_else($6, true);
})
],
// The inner list of whens.

View File

@ -1246,9 +1246,15 @@
return this;
},
// Rewrite a chain of IfNodes to add a default case as the final else.
add_else: function add_else(exprs) {
this.is_chain() ? this.else_body.add_else(exprs) : (this.else_body = exprs && exprs.unwrap());
this.children.push(exprs);
add_else: function add_else(exprs, statement) {
if (this.is_chain()) {
this.else_body.add_else(exprs);
} else {
if (!(statement)) {
exprs = exprs.unwrap();
}
this.children.push((this.else_body = exprs));
}
return this;
},
// If the else_body is an IfNode itself, then we've got an if-else chain.

View File

@ -356,7 +356,7 @@ case 167:this.$ = (function () {
break;
case 168:this.$ = $$[$0-5+4-1].rewrite_condition($$[$0-5+2-1]);
break;
case 169:this.$ = $$[$0-7+4-1].rewrite_condition($$[$0-7+2-1]).add_else($$[$0-7+6-1]);
case 169:this.$ = $$[$0-7+4-1].rewrite_condition($$[$0-7+2-1]).add_else($$[$0-7+6-1], true);
break;
case 170:this.$ = $$[$0-1+1-1];
break;

View File

@ -394,7 +394,7 @@ grammar: {
# Switch/When blocks.
Switch: [
o "SWITCH Expression INDENT Whens OUTDENT", -> $4.rewrite_condition($2)
o "SWITCH Expression INDENT Whens ELSE Block OUTDENT", -> $4.rewrite_condition($2).add_else($6)
o "SWITCH Expression INDENT Whens ELSE Block OUTDENT", -> $4.rewrite_condition($2).add_else($6, true)
]
# The inner list of whens.

View File

@ -985,9 +985,12 @@ IfNode: exports.IfNode: inherit Node, {
this
# Rewrite a chain of IfNodes to add a default case as the final else.
add_else: (exprs) ->
if @is_chain() then @else_body.add_else(exprs) else @else_body: exprs and exprs.unwrap()
@children.push(exprs)
add_else: (exprs, statement) ->
if @is_chain()
@else_body.add_else exprs
else
exprs: exprs.unwrap() unless statement
@children.push @else_body: exprs
this
# If the else_body is an IfNode itself, then we've got an if-else chain.

View File

@ -41,3 +41,13 @@ result: switch num += 5
ok result
# Ensure that trailing switch elses don't get rewritten.
result: false
switch "word"
when "one thing"
do_something()
else
result: true unless false
ok result