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

[CS2] add parens to chained do IIFE #4666

Merged
merged 3 commits into from
Aug 29, 2017
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
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