Skip to content

Commit

Permalink
fixes #1509: compile initial comments/literals outside of safety wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelficarra committed Dec 12, 2011
1 parent 5f1314c commit 26a28ab
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 9 deletions.
32 changes: 27 additions & 5 deletions lib/coffee-script/nodes.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 18 additions & 4 deletions src/nodes.coffee
Expand Up @@ -243,18 +243,32 @@ exports.Block = class Block extends Base
# It would be better not to generate them in the first place, but for now,
# clean up obvious double-parentheses.
compileRoot: (o) ->
o.indent = @tab = if o.bare then '' else TAB
o.indent = ""
o.scope = new Scope null, this, null
o.level = LEVEL_TOP
@spaced = yes
code = @compileWithDeclarations o
prelude = ""
hasReturn = no
@traverseChildren no, (e) ->
hasReturn = yes if e instanceof Return
!hasReturn
if hasReturn or not o.bare
preludeExps = for exp, i in @expressions
e = exp.unwrap()
break unless e instanceof Comment or e instanceof Literal
exp
rest = @expressions[preludeExps.length...]
@expressions = preludeExps
prelude = "#{@compileNode o}\n\n" if preludeExps.length
@expressions = rest
# We assume that we will need the safety wrapper.
# This is our best guess without actually compiling.
o.indent = TAB
code = @compileWithDeclarations o
# the `1` below accounts for `arguments`, always "in scope"
return code if (o.bare or o.scope.variables.length <= 1) and not hasReturn
"(function() {\n#{code}\n}).call(this);\n"
if hasReturn or (not o.bare and o.scope.variables.length > 1)
return "#{prelude}(function() {\n#{code}\n}).call(this);\n"
prelude + code

# Compile the expressions body for the contents of a function, with
# declarations of all inner variables pushed up to the top.
Expand Down

2 comments on commit 26a28ab

@jashkenas
Copy link
Owner

Choose a reason for hiding this comment

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

This is a nice feature, but perhaps the implementation could be cleaned up a bit... Can we extract this into a detectPrelude method, or something similar?

@michaelficarra
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

If you can think of a way that would actually be prettier, go ahead.

Please sign in to comment.