Skip to content

Commit b1f5ffd

Browse files
committed
add parens to chained do iife [Fixes jashkenas#3736]
1 parent d7d69a4 commit b1f5ffd

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed

lib/coffeescript/rewriter.js

Lines changed: 30 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/rewriter.coffee

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ exports.Rewriter = class Rewriter
5353
@normalizeLines()
5454
@tagPostfixConditionals()
5555
@addImplicitBracesAndParens()
56+
@addParensToChainedDoIife()
5657
@rescueStowawayComments()
5758
@addLocationDataToGeneratedTokens()
5859
@enforceValidCSXAttributes()
@@ -512,6 +513,23 @@ exports.Rewriter = class Rewriter
512513
last_column: prevLocationData.last_column
513514
return 1
514515

516+
# Add parens around a `do` IIFE followed by a chained `.` so that the
517+
# chaining applies to the executed function rather than the function
518+
# object (see #3736)
519+
addParensToChainedDoIife: ->
520+
condition = (token, i) ->
521+
@tag(i - 1) is 'OUTDENT'
522+
action = (token, i) ->
523+
return unless token[0] is '.'
524+
@tokens.splice doIndex, 0, generate '(', '(', @tokens[doIndex][2]
525+
@tokens.splice i + 1, 0, generate ')', ')', ['', 'implicit parentheses', token[2]]
526+
doIndex = null
527+
@scanTokens (token, i, tokens) ->
528+
return 1 unless token[1] is 'do' and @tag(i + 1) in ['->', '=>'] and @tag(i + 2) is 'INDENT'
529+
doIndex = i
530+
@detectEnd i + 2, condition, action, log: yes
531+
return 2
532+
515533
# Because our grammar is LALR(1), it can’t handle some single-line
516534
# expressions that lack ending delimiters. The **Rewriter** adds the implicit
517535
# blocks, so it doesn’t need to. To keep the grammar clean and tidy, trailing

test/formatting.coffee

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -420,3 +420,19 @@ test "#4576: function chaining on separate rows", ->
420420
.then ->
421421
yes
422422
.then ok
423+
424+
test "#3736: chaining after do IIFE", ->
425+
eq 3,
426+
do ->
427+
a: 3
428+
.a
429+
430+
eq 3,
431+
do -> a: 3
432+
.a
433+
434+
# preserve existing chaining behavior for non-IIFE `do`
435+
b = c: -> 4
436+
eq 4,
437+
do b
438+
.c

0 commit comments

Comments
 (0)