Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 4cc2c30

Browse files
author
Marc Häfner
committed
Fixes jashkenas#2181 -- conditional assignment as subexpression
* Parenthesize compilation of `||=` and `&&=` (when needed). * Fix variable caching for `?=`
1 parent a5513c4 commit 4cc2c30

3 files changed

Lines changed: 28 additions & 6 deletions

File tree

lib/coffee-script/nodes.js

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

src/nodes.coffee

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1240,8 +1240,12 @@ exports.Assign = class Assign extends Base
12401240
if not left.properties.length and left.base instanceof Literal and
12411241
left.base.value != "this" and not o.scope.check left.base.value
12421242
@variable.error "the variable \"#{left.base.value}\" can't be assigned with #{@context} because it has not been declared before"
1243-
if "?" in @context then o.isExistentialEquals = true
1244-
new Op(@context[...-1], left, new Assign(right, @value, '=')).compileToFragments o
1243+
if "?" in @context
1244+
o.isExistentialEquals = true
1245+
new If(new Existence(left), right, type: 'if').addElse(new Assign(right, @value, '=')).compileToFragments o
1246+
else
1247+
fragments = new Op(@context[...-1], left, new Assign(right, @value, '=')).compileToFragments o
1248+
if o.level <= LEVEL_LIST then fragments else @wrapInBraces fragments
12451249

12461250
# Compile the assignment from an array splice literal, using JavaScript's
12471251
# `Array#splice` method.
@@ -1652,7 +1656,7 @@ exports.Op = class Op extends Base
16521656

16531657
# Keep reference to the left expression, unless this an existential assignment
16541658
compileExistence: (o) ->
1655-
if !o.isExistentialEquals and @first.isComplex()
1659+
if @first.isComplex()
16561660
ref = new Literal o.scope.freeVariable 'ref'
16571661
fst = new Parens new Assign ref, @first
16581662
else

test/assignment.coffee

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,9 @@ test "compound assignment should be careful about caching variables", ->
8181
eq 5, base.five
8282
eq 5, count
8383

84+
eq 5, base().five ?= 6
85+
eq 6, count
86+
8487
test "compound assignment with implicit objects", ->
8588
obj = undefined
8689
obj ?=
@@ -380,3 +383,9 @@ test "#2613: parens on LHS of destructuring", ->
380383
a = {}
381384
[(a).b] = [1, 2, 3]
382385
eq a.b, 1
386+
387+
test "#2181: conditional assignment as a subexpression", ->
388+
a = false
389+
false && a or= true
390+
eq false, a
391+
eq false, not a or= true

0 commit comments

Comments
 (0)