jashkenas / coffeescript

Unfancy JavaScript
https://coffeescript.org/
MIT License
16.46k stars 1.98k forks source link

Additional indentation causes scope breakage #3741

Closed morungos closed 9 years ago

morungos commented 9 years ago

This is a corner-case I found with indentation. I've tried to simplify it down from a long set of database methods using knex.js, but it does appear to depend on the interaction of several factors. Basically, code that appears sound translates in a way that a variable is out of scope.

Here's the basic problematic case:

a
  .b () ->
    x = c
      .d () ->
        @e()
      .f

    x

Under CS 1.8.0, this translates to:

a.b(function() {
  var x;
  return x = c.d(function() {
    return this.e();
  }).f;
});

x;

And x is out of scope, apparently lifted out of the b callback. Removing the call to .d and its method makes the scoping work right. So, interestingly, does removing the .f line. More curiously, removing all the indentation to the b callback also makes everything fine. i.e.,

a
.b () ->
  x = c
    .d () ->
      @e()
    .f

  x

works right. So this appears to be a case where additional indentation across a consistently intuitive block breaks scoping inside that block. The workaround seems to be related to #3620, basically, never using indentation for method calls, but this does negatively affect readability.

vendethiel commented 9 years ago

(that's a duplicate, but I can't seem to find it right now..)

vendethiel commented 9 years ago

Here it is. #3652