Skip to content

Commit 9e8ab5c

Browse files
committed
Fix function literals as arguments
1 parent 817c39a commit 9e8ab5c

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

src/rewriter.coffee

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,39 @@ exports.Rewriter = class Rewriter
7777
detectEnd: (i, condition, action, opts = {}) ->
7878
{tokens} = this
7979
levels = 0
80+
inImplicitCall = false
8081
while token = tokens[i]
8182
return action.call this, token, i if levels is 0 and condition.call this, token, i
83+
84+
if opts.inSingleLineFunctionLiteral
85+
backStack = []
86+
j = i
87+
88+
# walk backwards til start of current expression ignoring generated tokens
89+
while j >= 0 and (backStack.length or @tag(i) not in ['->', '=>'] and (@tag(i) not in EXPRESSION_START or @tokens[i].generated) and @tag(i) not in LINEBREAKS)
90+
91+
# set flag if inside of implicit call, aka IMPLICIT_FUNC token followed by IMPLICIT_CALL token at current expression level
92+
if @tag(j) in IMPLICIT_FUNC and @tag(j + 1) in IMPLICIT_CALL and backStack.length == 0
93+
inImplicitCall = true
94+
break
95+
96+
backStack.push @tag(j) if @tag(j) in EXPRESSION_END
97+
if @tag(j) in EXPRESSION_START and backStack.length
98+
backStack.pop()
99+
100+
# don't go back further than current expression, only the return expression matters.
101+
if backStack.length == 0
102+
break
103+
104+
j -= 1
105+
82106
if token[0] in EXPRESSION_START
83107
levels += 1
84-
else if token[0] in EXPRESSION_END
108+
# the comma should act as EXPRESSION_END only when
109+
# - expression levels is 0, we don't want to interfer with sub-expression.
110+
# - it is not inside of an implicit call `foo(() -> implicitCall 1, 2)`
111+
# - it is inside of a function literal `opts.inSingleLineFunctionLiteral`
112+
else if token[0] in EXPRESSION_END or (opts.inSingleLineFunctionLiteral and (not inImplicitCall) and token[0] is ',' and levels is 0)
85113
levels -= 1
86114
if levels < 0
87115
return if opts.returnOnNegativeLevel
@@ -728,7 +756,7 @@ exports.Rewriter = class Rewriter
728756
if tag is 'ELSE' and @tag(i - 1) isnt 'OUTDENT'
729757
i = closeElseTag tokens, i
730758
tokens.splice i + 1, 0, indent
731-
@detectEnd i + 2, condition, action
759+
@detectEnd i + 2, condition, action, inSingleLineFunctionLiteral: tag in ['->', '=>']
732760
tokens.splice i, 1 if tag is 'THEN'
733761
return 1
734762
return 1

0 commit comments

Comments
 (0)