Skip to content

Commit

Permalink
[CS2] add parens to chained do IIFE (jashkenas#4666)
Browse files Browse the repository at this point in the history
* add parens to chained do iife [Fixes jashkenas#3736]

* remove debug code

* fixes from code review
  • Loading branch information
Julian Rosse authored and GeoffreyBooth committed Aug 29, 2017
1 parent d7d69a4 commit e54b8a1
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
29 changes: 29 additions & 0 deletions lib/coffeescript/rewriter.js

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

18 changes: 18 additions & 0 deletions src/rewriter.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ exports.Rewriter = class Rewriter
@normalizeLines()
@tagPostfixConditionals()
@addImplicitBracesAndParens()
@addParensToChainedDoIife()
@rescueStowawayComments()
@addLocationDataToGeneratedTokens()
@enforceValidCSXAttributes()
Expand Down Expand Up @@ -512,6 +513,23 @@ exports.Rewriter = class Rewriter
last_column: prevLocationData.last_column
return 1

# Add parens around a `do` IIFE followed by a chained `.` so that the
# chaining applies to the executed function rather than the function
# object (see #3736)
addParensToChainedDoIife: ->
condition = (token, i) ->
@tag(i - 1) is 'OUTDENT'
action = (token, i) ->
return unless token[0] in CALL_CLOSERS
@tokens.splice doIndex, 0, generate '(', '(', @tokens[doIndex]
@tokens.splice i + 1, 0, generate ')', ')', @tokens[i]
doIndex = null
@scanTokens (token, i, tokens) ->
return 1 unless token[1] is 'do' and @tag(i + 1) in ['->', '=>'] and @tag(i + 2) is 'INDENT'
doIndex = i
@detectEnd i + 2, condition, action
return 2

# Because our grammar is LALR(1), it can’t handle some single-line
# expressions that lack ending delimiters. The **Rewriter** adds the implicit
# blocks, so it doesn’t need to. To keep the grammar clean and tidy, trailing
Expand Down
16 changes: 16 additions & 0 deletions test/formatting.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -420,3 +420,19 @@ test "#4576: function chaining on separate rows", ->
.then ->
yes
.then ok

test "#3736: chaining after do IIFE", ->
eq 3,
do ->
a: 3
.a

eq 3,
do -> a: 3
?.a

# preserve existing chaining behavior for non-IIFE `do`
b = c: -> 4
eq 4,
do b
.c

0 comments on commit e54b8a1

Please sign in to comment.