jashkenas--coffeescript/test/assignment.coffee

930 lines
21 KiB
CoffeeScript
Raw Normal View History

2010-12-29 05:48:54 +00:00
# Assignment
# ----------
2010-12-29 19:06:57 +00:00
# * Assignment
# * Compound Assignment
# * Destructuring Assignment
# * Context Property (@) Assignment
# * Existential Assignment (?=)
# * Assignment to variables similar to generated variables
2010-12-29 19:06:57 +00:00
2010-12-29 05:48:54 +00:00
test "context property assignment (using @)", ->
nonce = {}
addMethod = ->
@method = -> nonce
this
eq nonce, addMethod.call({}).method()
test "unassignable values", ->
nonce = {}
for nonref in ['', '""', '0', 'f()'].concat CoffeeScript.RESERVED
eq nonce, (try CoffeeScript.compile "#{nonref} = v" catch e then nonce)
2011-03-12 02:41:12 +00:00
# Compound Assignment
2010-12-29 05:48:54 +00:00
2011-01-03 09:17:00 +00:00
test "boolean operators", ->
nonce = {}
a = 0
a or= nonce
eq nonce, a
b = 1
b or= nonce
eq 1, b
c = 0
c and= nonce
eq 0, c
d = 1
d and= nonce
eq nonce, d
# ensure that RHS is treated as a group
e = f = false
e and= f or true
eq false, e
test "compound assignment as a sub expression", ->
[a, b, c] = [1, 2, 3]
eq 6, (a + b += c)
eq 1, a
eq 5, b
eq 3, c
# *note: this test could still use refactoring*
test "compound assignment should be careful about caching variables", ->
count = 0
list = []
list[++count] or= 1
eq 1, list[1]
eq 1, count
list[++count] ?= 2
eq 2, list[2]
eq 2, count
list[count++] and= 6
eq 6, list[2]
eq 3, count
base = ->
++count
base
base().four or= 4
eq 4, base.four
eq 4, count
base().five ?= 5
eq 5, base.five
eq 5, count
eq 5, base().five ?= 6
eq 6, count
2011-01-03 09:17:00 +00:00
test "compound assignment with implicit objects", ->
obj = undefined
obj ?=
one: 1
eq 1, obj.one
obj and=
two: 2
eq undefined, obj.one
eq 2, obj.two
2010-12-29 05:48:54 +00:00
test "compound assignment (math operators)", ->
num = 10
num -= 5
eq 5, num
num *= 10
eq 50, num
num /= 10
eq 5, num
num %= 3
eq 2, num
test "more compound assignment", ->
a = {}
val = undefined
val ||= a
val ||= true
eq a, val
b = {}
val &&= true
eq val, true
val &&= b
eq b, val
c = {}
val = null
val ?= c
val ?= true
eq c, val
test "#1192: assignment starting with object literals", ->
doesNotThrow (-> CoffeeScript.run "{}.p = 0")
doesNotThrow (-> CoffeeScript.run "{}.p++")
doesNotThrow (-> CoffeeScript.run "{}[0] = 1")
doesNotThrow (-> CoffeeScript.run """{a: 1, 'b', "#{1}": 2}.p = 0""")
doesNotThrow (-> CoffeeScript.run "{a:{0:{}}}.a[0] = 0")
2010-12-29 05:48:54 +00:00
2011-03-12 02:41:12 +00:00
# Destructuring Assignment
2010-12-29 05:48:54 +00:00
2011-01-03 09:17:00 +00:00
test "empty destructuring assignment", ->
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
{} = {}
[] = []
2011-01-03 09:17:00 +00:00
test "chained destructuring assignments", ->
[a] = {0: b} = {'0': c} = [nonce={}]
eq nonce, a
eq nonce, b
eq nonce, c
test "variable swapping to verify caching of RHS values when appropriate", ->
a = nonceA = {}
b = nonceB = {}
c = nonceC = {}
[a, b, c] = [b, c, a]
eq nonceB, a
eq nonceC, b
eq nonceA, c
[a, b, c] = [b, c, a]
eq nonceC, a
eq nonceA, b
eq nonceB, c
fn = ->
[a, b, c] = [b, c, a]
arrayEq [nonceA,nonceB,nonceC], fn()
eq nonceA, a
eq nonceB, b
eq nonceC, c
test "#713: destructuring assignment should return right-hand-side value", ->
2011-01-03 09:17:00 +00:00
nonces = [nonceA={},nonceB={}]
eq nonces, [a, b] = [c, d] = nonces
eq nonceA, a
eq nonceA, c
eq nonceB, b
eq nonceB, d
test "destructuring assignment with splats", ->
a = {}; b = {}; c = {}; d = {}; e = {}
[x,y...,z] = [a,b,c,d,e]
eq a, x
arrayEq [b,c,d], y
eq e, z
# Should not trigger implicit call, e.g. rest ... => rest(...)
[x,y ...,z] = [a,b,c,d,e]
eq a, x
arrayEq [b,c,d], y
eq e, z
2011-01-03 09:17:00 +00:00
test "deep destructuring assignment with splats", ->
a={}; b={}; c={}; d={}; e={}; f={}; g={}; h={}; i={}
[u, [v, w..., x], y..., z] = [a, [b, c, d, e], f, g, h, i]
eq a, u
eq b, v
arrayEq [c,d], w
eq e, x
arrayEq [f,g,h], y
eq i, z
test "destructuring assignment with objects", ->
a={}; b={}; c={}
obj = {a,b,c}
{a:x, b:y, c:z} = obj
eq a, x
eq b, y
eq c, z
test "deep destructuring assignment with objects", ->
a={}; b={}; c={}; d={}
obj = {
a
b: {
'c': {
d: [
b
{e: c, f: d}
]
}
}
}
{a: w, 'b': {c: d: [x, {'f': z, e: y}]}} = obj
eq a, w
eq b, x
eq c, y
eq d, z
test "destructuring assignment with objects and splats", ->
a={}; b={}; c={}; d={}
obj = a: b: [a, b, c, d]
{a: b: [y, z...]} = obj
eq a, y
arrayEq [b,c,d], z
# Should not trigger implicit call, e.g. rest ... => rest(...)
{a: b: [y, z ...]} = obj
eq a, y
arrayEq [b,c,d], z
2011-01-03 09:17:00 +00:00
test "destructuring assignment against an expression", ->
a={}; b={}
[y, z] = if true then [a, b] else [b, a]
eq a, y
eq b, z
[CS2] Destructuring object spreads (#4493) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * Correct comment * object destructuring * Allow custom position of the rest element. * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * object destructuring * Allow custom position of the rest element. * rest element in object destructuring * rest element in object destructuring * fix string interpolation * merging * fixing splats in object literal * Rest element in parameter destructuring * merging with CS2 * merged with CS2 * Add support for the object spread initializer. https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md * Fix misspellings, trailing whitespace, other minor details * merging with beta2 * refactor object spread properties * small fix * - Fixed object spread function parameters. - Clean up "Assign" and moved all logic for object rest properties in single method (compileObjectDestruct). - Add helper function "objectWithoutKeys" to the "UTILITIES" for use with object rest properties, e.g. {a, b, r...} = obj => {a, b} = obj, r = objectWithoutKeys(...) - Clean up "Obj" and moved all logic for object spread properties in single method (compileSpread). - Clean up "Code". - Add method "hasSplat" to "Obj" and "Value" for checking if Obj contains the splat. - Enable placing spread syntax triple dots on either right or left, per #85 (https://github.com/coffeescript6/discuss/issues/85) * Fixed typos * Remove unused code * Removed dots (e.g. splat) on the left side from the grammar * Initial release for deep spread properties, e.g. obj2 = {obj.b..., a: 1} or {obj[b][c]..., d: 7} Tests need to be prepared! * 1. Object literal spread properties Object literals: - obj = { {b:{c:{d:1}}}..., a:1 } Parenthetical: - obj = { ( body ), a:1 } - obj = { ( body )..., a:1 } Invocation: - obj = { ( (args) -> ... )(params), a:1 } - obj = { ( (args) -> ... )(params)..., a:1 } - obj = { foo(), a:1 } - obj = { foo()..., a:1 } 2. Refactor, cleanup & other optimizations. * Merged with 2.0 * Cleanup * Some more cleanup. * Fixed error with freeVariable and object destructuring. * Fixed errors with object spread properties. * Improvements, fixed errors. * Minor improvement. * Minor improvements. * Typo. * Remove unnecessary whitespace. * Remove unnecessary whitespace. * Changed few "assertErrorFormat" tests since parentheses are now allowed in the Obj. * Whitespace cleanup * Comments cleanup * fix destructured obj param declarations * refine fix; add test * Refactor function args ({a, b...}) * Additional tests for object destructuring in function argument. * Minor improvement for object destructuring variable declaration. * refactor function args ({a, b...}) and ({a, b...} = {}); Obj And Param cleanup * fix comment * Fix object destructuring variable declaration. * more tests with default values * fix typo * Fixed default values in object destructuring. * small fix * Babel’s tests for object rest spread * Style: spaces after colons in object declarations * Cleanup comments * Simplify Babel tests * Fix comments * Fix destructuring with splats in multiple objects * Add test for default values in detsructuring assignment with splats * Handle default values when assigning to object splats * Rewrite traverseRest to fix handling of dynamic keys * Fix double parens around destructuring with splats * Update compileObjectDestruct comments * Improve formatting of top-level destructures with splats and tidy parens * Added a bigger destructuring-with-defaults test and fixed a bug * Refactor destructuring grammar to allow additional forms * Add a missing case to ObjSpreadExpr * These tests shouldn’t run in the browser * Fix test.html
2017-06-30 05:57:42 +00:00
test "destructuring assignment with objects and splats: ES2015", ->
obj = {a: 1, b: 2, c: 3, d: 4, e: 5}
throws (-> CoffeeScript.compile "{a, r..., s...} = x"), null, "multiple rest elements are disallowed"
throws (-> CoffeeScript.compile "{a, r..., s..., b} = x"), null, "multiple rest elements are disallowed"
prop = "b"
{a, b, r...} = obj
eq a, 1
eq b, 2
eq r.e, obj.e
eq r.a, undefined
{d, c: x, r...} = obj
eq x, 3
eq d, 4
eq r.c, undefined
eq r.b, 2
{a, 'b': z, g = 9, r...} = obj
eq g, 9
eq z, 2
eq r.b, undefined
test "destructuring assignment with splats and default values", ->
obj = {}
c = {b: 1}
{ a: {b} = c, d...} = obj
eq b, 1
deepEqual d, {}
# Should not trigger implicit call, e.g. rest ... => rest(...)
{
a: {b} = c
d ...
} = obj
eq b, 1
deepEqual d, {}
[CS2] Destructuring object spreads (#4493) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * Correct comment * object destructuring * Allow custom position of the rest element. * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * object destructuring * Allow custom position of the rest element. * rest element in object destructuring * rest element in object destructuring * fix string interpolation * merging * fixing splats in object literal * Rest element in parameter destructuring * merging with CS2 * merged with CS2 * Add support for the object spread initializer. https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md * Fix misspellings, trailing whitespace, other minor details * merging with beta2 * refactor object spread properties * small fix * - Fixed object spread function parameters. - Clean up "Assign" and moved all logic for object rest properties in single method (compileObjectDestruct). - Add helper function "objectWithoutKeys" to the "UTILITIES" for use with object rest properties, e.g. {a, b, r...} = obj => {a, b} = obj, r = objectWithoutKeys(...) - Clean up "Obj" and moved all logic for object spread properties in single method (compileSpread). - Clean up "Code". - Add method "hasSplat" to "Obj" and "Value" for checking if Obj contains the splat. - Enable placing spread syntax triple dots on either right or left, per #85 (https://github.com/coffeescript6/discuss/issues/85) * Fixed typos * Remove unused code * Removed dots (e.g. splat) on the left side from the grammar * Initial release for deep spread properties, e.g. obj2 = {obj.b..., a: 1} or {obj[b][c]..., d: 7} Tests need to be prepared! * 1. Object literal spread properties Object literals: - obj = { {b:{c:{d:1}}}..., a:1 } Parenthetical: - obj = { ( body ), a:1 } - obj = { ( body )..., a:1 } Invocation: - obj = { ( (args) -> ... )(params), a:1 } - obj = { ( (args) -> ... )(params)..., a:1 } - obj = { foo(), a:1 } - obj = { foo()..., a:1 } 2. Refactor, cleanup & other optimizations. * Merged with 2.0 * Cleanup * Some more cleanup. * Fixed error with freeVariable and object destructuring. * Fixed errors with object spread properties. * Improvements, fixed errors. * Minor improvement. * Minor improvements. * Typo. * Remove unnecessary whitespace. * Remove unnecessary whitespace. * Changed few "assertErrorFormat" tests since parentheses are now allowed in the Obj. * Whitespace cleanup * Comments cleanup * fix destructured obj param declarations * refine fix; add test * Refactor function args ({a, b...}) * Additional tests for object destructuring in function argument. * Minor improvement for object destructuring variable declaration. * refactor function args ({a, b...}) and ({a, b...} = {}); Obj And Param cleanup * fix comment * Fix object destructuring variable declaration. * more tests with default values * fix typo * Fixed default values in object destructuring. * small fix * Babel’s tests for object rest spread * Style: spaces after colons in object declarations * Cleanup comments * Simplify Babel tests * Fix comments * Fix destructuring with splats in multiple objects * Add test for default values in detsructuring assignment with splats * Handle default values when assigning to object splats * Rewrite traverseRest to fix handling of dynamic keys * Fix double parens around destructuring with splats * Update compileObjectDestruct comments * Improve formatting of top-level destructures with splats and tidy parens * Added a bigger destructuring-with-defaults test and fixed a bug * Refactor destructuring grammar to allow additional forms * Add a missing case to ObjSpreadExpr * These tests shouldn’t run in the browser * Fix test.html
2017-06-30 05:57:42 +00:00
test "destructuring assignment with splat with default value", ->
obj = {}
c = {val: 1}
{ a: {b...} = c } = obj
deepEqual b, val: 1
test "destructuring assignment with multiple splats in different objects", ->
obj = { a: {val: 1}, b: {val: 2} }
{ a: {a...}, b: {b...} } = obj
deepEqual a, val: 1
deepEqual b, val: 2
o = {
props: {
p: {
n: 1
m: 5
}
s: 6
}
}
{p: {m, q..., t = {obj...}}, r...} = o.props
eq m, o.props.p.m
deepEqual r, s: 6
deepEqual q, n: 1
deepEqual t, obj
@props = o.props
{p: {m}, r...} = @props
eq m, @props.p.m
deepEqual r, s: 6
{p: {m}, r...} = {o.props..., p:{m:9}}
eq m, 9
# Should not trigger implicit call, e.g. rest ... => rest(...)
{
a: {
a ...
}
b: {
b ...
}
} = obj
deepEqual a, val: 1
deepEqual b, val: 2
[CS2] Destructuring object spreads (#4493) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * Correct comment * object destructuring * Allow custom position of the rest element. * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * object destructuring * Allow custom position of the rest element. * rest element in object destructuring * rest element in object destructuring * fix string interpolation * merging * fixing splats in object literal * Rest element in parameter destructuring * merging with CS2 * merged with CS2 * Add support for the object spread initializer. https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md * Fix misspellings, trailing whitespace, other minor details * merging with beta2 * refactor object spread properties * small fix * - Fixed object spread function parameters. - Clean up "Assign" and moved all logic for object rest properties in single method (compileObjectDestruct). - Add helper function "objectWithoutKeys" to the "UTILITIES" for use with object rest properties, e.g. {a, b, r...} = obj => {a, b} = obj, r = objectWithoutKeys(...) - Clean up "Obj" and moved all logic for object spread properties in single method (compileSpread). - Clean up "Code". - Add method "hasSplat" to "Obj" and "Value" for checking if Obj contains the splat. - Enable placing spread syntax triple dots on either right or left, per #85 (https://github.com/coffeescript6/discuss/issues/85) * Fixed typos * Remove unused code * Removed dots (e.g. splat) on the left side from the grammar * Initial release for deep spread properties, e.g. obj2 = {obj.b..., a: 1} or {obj[b][c]..., d: 7} Tests need to be prepared! * 1. Object literal spread properties Object literals: - obj = { {b:{c:{d:1}}}..., a:1 } Parenthetical: - obj = { ( body ), a:1 } - obj = { ( body )..., a:1 } Invocation: - obj = { ( (args) -> ... )(params), a:1 } - obj = { ( (args) -> ... )(params)..., a:1 } - obj = { foo(), a:1 } - obj = { foo()..., a:1 } 2. Refactor, cleanup & other optimizations. * Merged with 2.0 * Cleanup * Some more cleanup. * Fixed error with freeVariable and object destructuring. * Fixed errors with object spread properties. * Improvements, fixed errors. * Minor improvement. * Minor improvements. * Typo. * Remove unnecessary whitespace. * Remove unnecessary whitespace. * Changed few "assertErrorFormat" tests since parentheses are now allowed in the Obj. * Whitespace cleanup * Comments cleanup * fix destructured obj param declarations * refine fix; add test * Refactor function args ({a, b...}) * Additional tests for object destructuring in function argument. * Minor improvement for object destructuring variable declaration. * refactor function args ({a, b...}) and ({a, b...} = {}); Obj And Param cleanup * fix comment * Fix object destructuring variable declaration. * more tests with default values * fix typo * Fixed default values in object destructuring. * small fix * Babel’s tests for object rest spread * Style: spaces after colons in object declarations * Cleanup comments * Simplify Babel tests * Fix comments * Fix destructuring with splats in multiple objects * Add test for default values in detsructuring assignment with splats * Handle default values when assigning to object splats * Rewrite traverseRest to fix handling of dynamic keys * Fix double parens around destructuring with splats * Update compileObjectDestruct comments * Improve formatting of top-level destructures with splats and tidy parens * Added a bigger destructuring-with-defaults test and fixed a bug * Refactor destructuring grammar to allow additional forms * Add a missing case to ObjSpreadExpr * These tests shouldn’t run in the browser * Fix test.html
2017-06-30 05:57:42 +00:00
test "destructuring assignment with dynamic keys and splats", ->
i = 0
foo = -> ++i
obj = {1: 'a', 2: 'b'}
{ "#{foo()}": a, b... } = obj
eq a, 'a'
eq i, 1
deepEqual b, 2: 'b'
# Tests from https://babeljs.io/docs/plugins/transform-object-rest-spread/.
test "destructuring assignment with objects and splats: Babel tests", ->
# What Babel calls “rest properties:”
{ x, y, z... } = { x: 1, y: 2, a: 3, b: 4 }
eq x, 1
eq y, 2
deepEqual z, { a: 3, b: 4 }
# What Babel calls “spread properties:”
n = { x, y, z... }
deepEqual n, { x: 1, y: 2, a: 3, b: 4 }
# Should not trigger implicit call, e.g. rest ... => rest(...)
{ x, y, z ... } = { x: 1, y: 2, a: 3, b: 4 }
eq x, 1
eq y, 2
deepEqual z, { a: 3, b: 4 }
n = { x, y, z ... }
deepEqual n, { x: 1, y: 2, a: 3, b: 4 }
[CS2] Destructuring object spreads (#4493) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * Correct comment * object destructuring * Allow custom position of the rest element. * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * object destructuring * Allow custom position of the rest element. * rest element in object destructuring * rest element in object destructuring * fix string interpolation * merging * fixing splats in object literal * Rest element in parameter destructuring * merging with CS2 * merged with CS2 * Add support for the object spread initializer. https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md * Fix misspellings, trailing whitespace, other minor details * merging with beta2 * refactor object spread properties * small fix * - Fixed object spread function parameters. - Clean up "Assign" and moved all logic for object rest properties in single method (compileObjectDestruct). - Add helper function "objectWithoutKeys" to the "UTILITIES" for use with object rest properties, e.g. {a, b, r...} = obj => {a, b} = obj, r = objectWithoutKeys(...) - Clean up "Obj" and moved all logic for object spread properties in single method (compileSpread). - Clean up "Code". - Add method "hasSplat" to "Obj" and "Value" for checking if Obj contains the splat. - Enable placing spread syntax triple dots on either right or left, per #85 (https://github.com/coffeescript6/discuss/issues/85) * Fixed typos * Remove unused code * Removed dots (e.g. splat) on the left side from the grammar * Initial release for deep spread properties, e.g. obj2 = {obj.b..., a: 1} or {obj[b][c]..., d: 7} Tests need to be prepared! * 1. Object literal spread properties Object literals: - obj = { {b:{c:{d:1}}}..., a:1 } Parenthetical: - obj = { ( body ), a:1 } - obj = { ( body )..., a:1 } Invocation: - obj = { ( (args) -> ... )(params), a:1 } - obj = { ( (args) -> ... )(params)..., a:1 } - obj = { foo(), a:1 } - obj = { foo()..., a:1 } 2. Refactor, cleanup & other optimizations. * Merged with 2.0 * Cleanup * Some more cleanup. * Fixed error with freeVariable and object destructuring. * Fixed errors with object spread properties. * Improvements, fixed errors. * Minor improvement. * Minor improvements. * Typo. * Remove unnecessary whitespace. * Remove unnecessary whitespace. * Changed few "assertErrorFormat" tests since parentheses are now allowed in the Obj. * Whitespace cleanup * Comments cleanup * fix destructured obj param declarations * refine fix; add test * Refactor function args ({a, b...}) * Additional tests for object destructuring in function argument. * Minor improvement for object destructuring variable declaration. * refactor function args ({a, b...}) and ({a, b...} = {}); Obj And Param cleanup * fix comment * Fix object destructuring variable declaration. * more tests with default values * fix typo * Fixed default values in object destructuring. * small fix * Babel’s tests for object rest spread * Style: spaces after colons in object declarations * Cleanup comments * Simplify Babel tests * Fix comments * Fix destructuring with splats in multiple objects * Add test for default values in detsructuring assignment with splats * Handle default values when assigning to object splats * Rewrite traverseRest to fix handling of dynamic keys * Fix double parens around destructuring with splats * Update compileObjectDestruct comments * Improve formatting of top-level destructures with splats and tidy parens * Added a bigger destructuring-with-defaults test and fixed a bug * Refactor destructuring grammar to allow additional forms * Add a missing case to ObjSpreadExpr * These tests shouldn’t run in the browser * Fix test.html
2017-06-30 05:57:42 +00:00
test "deep destructuring assignment with objects: ES2015", ->
a1={}; b1={}; c1={}; d1={}
obj = {
a: a1
b: {
'c': {
d: {
b1
e: c1
f: d1
}
}
}
b2: {b1, c1}
}
{a: w, b: {c: {d: {b1: bb, r1...}}}, r2...} = obj
eq r1.e, c1
eq r2.b, undefined
eq bb, b1
eq r2.b2, obj.b2
# Should not trigger implicit call, e.g. rest ... => rest(...)
{a: w, b: {c: {d: {b1: bb, r1 ...}}}, r2 ...} = obj
eq r1.e, c1
eq r2.b, undefined
eq bb, b1
eq r2.b2, obj.b2
[CS2] Destructuring object spreads (#4493) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * Correct comment * object destructuring * Allow custom position of the rest element. * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * object destructuring * Allow custom position of the rest element. * rest element in object destructuring * rest element in object destructuring * fix string interpolation * merging * fixing splats in object literal * Rest element in parameter destructuring * merging with CS2 * merged with CS2 * Add support for the object spread initializer. https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md * Fix misspellings, trailing whitespace, other minor details * merging with beta2 * refactor object spread properties * small fix * - Fixed object spread function parameters. - Clean up "Assign" and moved all logic for object rest properties in single method (compileObjectDestruct). - Add helper function "objectWithoutKeys" to the "UTILITIES" for use with object rest properties, e.g. {a, b, r...} = obj => {a, b} = obj, r = objectWithoutKeys(...) - Clean up "Obj" and moved all logic for object spread properties in single method (compileSpread). - Clean up "Code". - Add method "hasSplat" to "Obj" and "Value" for checking if Obj contains the splat. - Enable placing spread syntax triple dots on either right or left, per #85 (https://github.com/coffeescript6/discuss/issues/85) * Fixed typos * Remove unused code * Removed dots (e.g. splat) on the left side from the grammar * Initial release for deep spread properties, e.g. obj2 = {obj.b..., a: 1} or {obj[b][c]..., d: 7} Tests need to be prepared! * 1. Object literal spread properties Object literals: - obj = { {b:{c:{d:1}}}..., a:1 } Parenthetical: - obj = { ( body ), a:1 } - obj = { ( body )..., a:1 } Invocation: - obj = { ( (args) -> ... )(params), a:1 } - obj = { ( (args) -> ... )(params)..., a:1 } - obj = { foo(), a:1 } - obj = { foo()..., a:1 } 2. Refactor, cleanup & other optimizations. * Merged with 2.0 * Cleanup * Some more cleanup. * Fixed error with freeVariable and object destructuring. * Fixed errors with object spread properties. * Improvements, fixed errors. * Minor improvement. * Minor improvements. * Typo. * Remove unnecessary whitespace. * Remove unnecessary whitespace. * Changed few "assertErrorFormat" tests since parentheses are now allowed in the Obj. * Whitespace cleanup * Comments cleanup * fix destructured obj param declarations * refine fix; add test * Refactor function args ({a, b...}) * Additional tests for object destructuring in function argument. * Minor improvement for object destructuring variable declaration. * refactor function args ({a, b...}) and ({a, b...} = {}); Obj And Param cleanup * fix comment * Fix object destructuring variable declaration. * more tests with default values * fix typo * Fixed default values in object destructuring. * small fix * Babel’s tests for object rest spread * Style: spaces after colons in object declarations * Cleanup comments * Simplify Babel tests * Fix comments * Fix destructuring with splats in multiple objects * Add test for default values in detsructuring assignment with splats * Handle default values when assigning to object splats * Rewrite traverseRest to fix handling of dynamic keys * Fix double parens around destructuring with splats * Update compileObjectDestruct comments * Improve formatting of top-level destructures with splats and tidy parens * Added a bigger destructuring-with-defaults test and fixed a bug * Refactor destructuring grammar to allow additional forms * Add a missing case to ObjSpreadExpr * These tests shouldn’t run in the browser * Fix test.html
2017-06-30 05:57:42 +00:00
test "deep destructuring assignment with defaults: ES2015", ->
obj =
b: { c: 1, baz: 'qux' }
foo: 'bar'
j =
f: 'world'
i =
some: 'prop'
{
a...
b: { c, d... }
e: {
f: hello
g: { h... } = i
} = j
} = obj
deepEqual a, foo: 'bar'
eq c, 1
deepEqual d, baz: 'qux'
eq hello, 'world'
deepEqual h, some: 'prop'
# Should not trigger implicit call, e.g. rest ... => rest(...)
{
a ...
b: {
c,
d ...
}
e: {
f: hello
g: {
h ...
} = i
} = j
} = obj
deepEqual a, foo: 'bar'
eq c, 1
deepEqual d, baz: 'qux'
eq hello, 'world'
deepEqual h, some: 'prop'
[CS2] Destructuring object spreads (#4493) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * Correct comment * object destructuring * Allow custom position of the rest element. * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * object destructuring * Allow custom position of the rest element. * rest element in object destructuring * rest element in object destructuring * fix string interpolation * merging * fixing splats in object literal * Rest element in parameter destructuring * merging with CS2 * merged with CS2 * Add support for the object spread initializer. https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md * Fix misspellings, trailing whitespace, other minor details * merging with beta2 * refactor object spread properties * small fix * - Fixed object spread function parameters. - Clean up "Assign" and moved all logic for object rest properties in single method (compileObjectDestruct). - Add helper function "objectWithoutKeys" to the "UTILITIES" for use with object rest properties, e.g. {a, b, r...} = obj => {a, b} = obj, r = objectWithoutKeys(...) - Clean up "Obj" and moved all logic for object spread properties in single method (compileSpread). - Clean up "Code". - Add method "hasSplat" to "Obj" and "Value" for checking if Obj contains the splat. - Enable placing spread syntax triple dots on either right or left, per #85 (https://github.com/coffeescript6/discuss/issues/85) * Fixed typos * Remove unused code * Removed dots (e.g. splat) on the left side from the grammar * Initial release for deep spread properties, e.g. obj2 = {obj.b..., a: 1} or {obj[b][c]..., d: 7} Tests need to be prepared! * 1. Object literal spread properties Object literals: - obj = { {b:{c:{d:1}}}..., a:1 } Parenthetical: - obj = { ( body ), a:1 } - obj = { ( body )..., a:1 } Invocation: - obj = { ( (args) -> ... )(params), a:1 } - obj = { ( (args) -> ... )(params)..., a:1 } - obj = { foo(), a:1 } - obj = { foo()..., a:1 } 2. Refactor, cleanup & other optimizations. * Merged with 2.0 * Cleanup * Some more cleanup. * Fixed error with freeVariable and object destructuring. * Fixed errors with object spread properties. * Improvements, fixed errors. * Minor improvement. * Minor improvements. * Typo. * Remove unnecessary whitespace. * Remove unnecessary whitespace. * Changed few "assertErrorFormat" tests since parentheses are now allowed in the Obj. * Whitespace cleanup * Comments cleanup * fix destructured obj param declarations * refine fix; add test * Refactor function args ({a, b...}) * Additional tests for object destructuring in function argument. * Minor improvement for object destructuring variable declaration. * refactor function args ({a, b...}) and ({a, b...} = {}); Obj And Param cleanup * fix comment * Fix object destructuring variable declaration. * more tests with default values * fix typo * Fixed default values in object destructuring. * small fix * Babel’s tests for object rest spread * Style: spaces after colons in object declarations * Cleanup comments * Simplify Babel tests * Fix comments * Fix destructuring with splats in multiple objects * Add test for default values in detsructuring assignment with splats * Handle default values when assigning to object splats * Rewrite traverseRest to fix handling of dynamic keys * Fix double parens around destructuring with splats * Update compileObjectDestruct comments * Improve formatting of top-level destructures with splats and tidy parens * Added a bigger destructuring-with-defaults test and fixed a bug * Refactor destructuring grammar to allow additional forms * Add a missing case to ObjSpreadExpr * These tests shouldn’t run in the browser * Fix test.html
2017-06-30 05:57:42 +00:00
test "object spread properties: ES2015", ->
obj = {a: 1, b: 2, c: 3, d: 4, e: 5}
obj2 = {obj..., c:9}
eq obj2.c, 9
eq obj.a, obj2.a
# Should not trigger implicit call, e.g. rest ... => rest(...)
obj2 = {
obj ...
c:9
}
eq obj2.c, 9
eq obj.a, obj2.a
[CS2] Destructuring object spreads (#4493) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * Correct comment * object destructuring * Allow custom position of the rest element. * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * object destructuring * Allow custom position of the rest element. * rest element in object destructuring * rest element in object destructuring * fix string interpolation * merging * fixing splats in object literal * Rest element in parameter destructuring * merging with CS2 * merged with CS2 * Add support for the object spread initializer. https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md * Fix misspellings, trailing whitespace, other minor details * merging with beta2 * refactor object spread properties * small fix * - Fixed object spread function parameters. - Clean up "Assign" and moved all logic for object rest properties in single method (compileObjectDestruct). - Add helper function "objectWithoutKeys" to the "UTILITIES" for use with object rest properties, e.g. {a, b, r...} = obj => {a, b} = obj, r = objectWithoutKeys(...) - Clean up "Obj" and moved all logic for object spread properties in single method (compileSpread). - Clean up "Code". - Add method "hasSplat" to "Obj" and "Value" for checking if Obj contains the splat. - Enable placing spread syntax triple dots on either right or left, per #85 (https://github.com/coffeescript6/discuss/issues/85) * Fixed typos * Remove unused code * Removed dots (e.g. splat) on the left side from the grammar * Initial release for deep spread properties, e.g. obj2 = {obj.b..., a: 1} or {obj[b][c]..., d: 7} Tests need to be prepared! * 1. Object literal spread properties Object literals: - obj = { {b:{c:{d:1}}}..., a:1 } Parenthetical: - obj = { ( body ), a:1 } - obj = { ( body )..., a:1 } Invocation: - obj = { ( (args) -> ... )(params), a:1 } - obj = { ( (args) -> ... )(params)..., a:1 } - obj = { foo(), a:1 } - obj = { foo()..., a:1 } 2. Refactor, cleanup & other optimizations. * Merged with 2.0 * Cleanup * Some more cleanup. * Fixed error with freeVariable and object destructuring. * Fixed errors with object spread properties. * Improvements, fixed errors. * Minor improvement. * Minor improvements. * Typo. * Remove unnecessary whitespace. * Remove unnecessary whitespace. * Changed few "assertErrorFormat" tests since parentheses are now allowed in the Obj. * Whitespace cleanup * Comments cleanup * fix destructured obj param declarations * refine fix; add test * Refactor function args ({a, b...}) * Additional tests for object destructuring in function argument. * Minor improvement for object destructuring variable declaration. * refactor function args ({a, b...}) and ({a, b...} = {}); Obj And Param cleanup * fix comment * Fix object destructuring variable declaration. * more tests with default values * fix typo * Fixed default values in object destructuring. * small fix * Babel’s tests for object rest spread * Style: spaces after colons in object declarations * Cleanup comments * Simplify Babel tests * Fix comments * Fix destructuring with splats in multiple objects * Add test for default values in detsructuring assignment with splats * Handle default values when assigning to object splats * Rewrite traverseRest to fix handling of dynamic keys * Fix double parens around destructuring with splats * Update compileObjectDestruct comments * Improve formatting of top-level destructures with splats and tidy parens * Added a bigger destructuring-with-defaults test and fixed a bug * Refactor destructuring grammar to allow additional forms * Add a missing case to ObjSpreadExpr * These tests shouldn’t run in the browser * Fix test.html
2017-06-30 05:57:42 +00:00
obj2 = {obj..., a: 8, c: 9, obj...}
eq obj2.c, 3
eq obj.a, obj2.a
# Should not trigger implicit call, e.g. rest ... => rest(...)
obj2 = {
obj ...
a: 8
c: 9
obj ...
}
eq obj2.c, 3
eq obj.a, obj2.a
[CS2] Destructuring object spreads (#4493) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * Correct comment * object destructuring * Allow custom position of the rest element. * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * object destructuring * Allow custom position of the rest element. * rest element in object destructuring * rest element in object destructuring * fix string interpolation * merging * fixing splats in object literal * Rest element in parameter destructuring * merging with CS2 * merged with CS2 * Add support for the object spread initializer. https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md * Fix misspellings, trailing whitespace, other minor details * merging with beta2 * refactor object spread properties * small fix * - Fixed object spread function parameters. - Clean up "Assign" and moved all logic for object rest properties in single method (compileObjectDestruct). - Add helper function "objectWithoutKeys" to the "UTILITIES" for use with object rest properties, e.g. {a, b, r...} = obj => {a, b} = obj, r = objectWithoutKeys(...) - Clean up "Obj" and moved all logic for object spread properties in single method (compileSpread). - Clean up "Code". - Add method "hasSplat" to "Obj" and "Value" for checking if Obj contains the splat. - Enable placing spread syntax triple dots on either right or left, per #85 (https://github.com/coffeescript6/discuss/issues/85) * Fixed typos * Remove unused code * Removed dots (e.g. splat) on the left side from the grammar * Initial release for deep spread properties, e.g. obj2 = {obj.b..., a: 1} or {obj[b][c]..., d: 7} Tests need to be prepared! * 1. Object literal spread properties Object literals: - obj = { {b:{c:{d:1}}}..., a:1 } Parenthetical: - obj = { ( body ), a:1 } - obj = { ( body )..., a:1 } Invocation: - obj = { ( (args) -> ... )(params), a:1 } - obj = { ( (args) -> ... )(params)..., a:1 } - obj = { foo(), a:1 } - obj = { foo()..., a:1 } 2. Refactor, cleanup & other optimizations. * Merged with 2.0 * Cleanup * Some more cleanup. * Fixed error with freeVariable and object destructuring. * Fixed errors with object spread properties. * Improvements, fixed errors. * Minor improvement. * Minor improvements. * Typo. * Remove unnecessary whitespace. * Remove unnecessary whitespace. * Changed few "assertErrorFormat" tests since parentheses are now allowed in the Obj. * Whitespace cleanup * Comments cleanup * fix destructured obj param declarations * refine fix; add test * Refactor function args ({a, b...}) * Additional tests for object destructuring in function argument. * Minor improvement for object destructuring variable declaration. * refactor function args ({a, b...}) and ({a, b...} = {}); Obj And Param cleanup * fix comment * Fix object destructuring variable declaration. * more tests with default values * fix typo * Fixed default values in object destructuring. * small fix * Babel’s tests for object rest spread * Style: spaces after colons in object declarations * Cleanup comments * Simplify Babel tests * Fix comments * Fix destructuring with splats in multiple objects * Add test for default values in detsructuring assignment with splats * Handle default values when assigning to object splats * Rewrite traverseRest to fix handling of dynamic keys * Fix double parens around destructuring with splats * Update compileObjectDestruct comments * Improve formatting of top-level destructures with splats and tidy parens * Added a bigger destructuring-with-defaults test and fixed a bug * Refactor destructuring grammar to allow additional forms * Add a missing case to ObjSpreadExpr * These tests shouldn’t run in the browser * Fix test.html
2017-06-30 05:57:42 +00:00
obj3 = {obj..., b: 7, g: {obj2..., c: 1}}
eq obj3.g.c, 1
eq obj3.b, 7
deepEqual obj3.g, {obj..., c: 1}
(({a, b, r...}) ->
eq 1, a
deepEqual r, {c: 3, d: 44, e: 55}
) {obj2..., d: 44, e: 55}
obj = {a: 1, b: 2, c: {d: 3, e: 4, f: {g: 5}}}
obj4 = {a: 10, obj.c...}
eq obj4.a, 10
eq obj4.d, 3
eq obj4.f.g, 5
deepEqual obj4.f, obj.c.f
# Should not trigger implicit call, e.g. rest ... => rest(...)
(({
a
b
r ...
}) ->
eq 1, a
deepEqual r, {c: 3, d: 44, e: 55}
) {
obj2 ...
d: 44
e: 55
}
# Should not trigger implicit call, e.g. rest ... => rest(...)
obj4 = {
a: 10
obj.c ...
}
eq obj4.a, 10
eq obj4.d, 3
eq obj4.f.g, 5
deepEqual obj4.f, obj.c.f
[CS2] Destructuring object spreads (#4493) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * Correct comment * object destructuring * Allow custom position of the rest element. * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * object destructuring * Allow custom position of the rest element. * rest element in object destructuring * rest element in object destructuring * fix string interpolation * merging * fixing splats in object literal * Rest element in parameter destructuring * merging with CS2 * merged with CS2 * Add support for the object spread initializer. https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md * Fix misspellings, trailing whitespace, other minor details * merging with beta2 * refactor object spread properties * small fix * - Fixed object spread function parameters. - Clean up "Assign" and moved all logic for object rest properties in single method (compileObjectDestruct). - Add helper function "objectWithoutKeys" to the "UTILITIES" for use with object rest properties, e.g. {a, b, r...} = obj => {a, b} = obj, r = objectWithoutKeys(...) - Clean up "Obj" and moved all logic for object spread properties in single method (compileSpread). - Clean up "Code". - Add method "hasSplat" to "Obj" and "Value" for checking if Obj contains the splat. - Enable placing spread syntax triple dots on either right or left, per #85 (https://github.com/coffeescript6/discuss/issues/85) * Fixed typos * Remove unused code * Removed dots (e.g. splat) on the left side from the grammar * Initial release for deep spread properties, e.g. obj2 = {obj.b..., a: 1} or {obj[b][c]..., d: 7} Tests need to be prepared! * 1. Object literal spread properties Object literals: - obj = { {b:{c:{d:1}}}..., a:1 } Parenthetical: - obj = { ( body ), a:1 } - obj = { ( body )..., a:1 } Invocation: - obj = { ( (args) -> ... )(params), a:1 } - obj = { ( (args) -> ... )(params)..., a:1 } - obj = { foo(), a:1 } - obj = { foo()..., a:1 } 2. Refactor, cleanup & other optimizations. * Merged with 2.0 * Cleanup * Some more cleanup. * Fixed error with freeVariable and object destructuring. * Fixed errors with object spread properties. * Improvements, fixed errors. * Minor improvement. * Minor improvements. * Typo. * Remove unnecessary whitespace. * Remove unnecessary whitespace. * Changed few "assertErrorFormat" tests since parentheses are now allowed in the Obj. * Whitespace cleanup * Comments cleanup * fix destructured obj param declarations * refine fix; add test * Refactor function args ({a, b...}) * Additional tests for object destructuring in function argument. * Minor improvement for object destructuring variable declaration. * refactor function args ({a, b...}) and ({a, b...} = {}); Obj And Param cleanup * fix comment * Fix object destructuring variable declaration. * more tests with default values * fix typo * Fixed default values in object destructuring. * small fix * Babel’s tests for object rest spread * Style: spaces after colons in object declarations * Cleanup comments * Simplify Babel tests * Fix comments * Fix destructuring with splats in multiple objects * Add test for default values in detsructuring assignment with splats * Handle default values when assigning to object splats * Rewrite traverseRest to fix handling of dynamic keys * Fix double parens around destructuring with splats * Update compileObjectDestruct comments * Improve formatting of top-level destructures with splats and tidy parens * Added a bigger destructuring-with-defaults test and fixed a bug * Refactor destructuring grammar to allow additional forms * Add a missing case to ObjSpreadExpr * These tests shouldn’t run in the browser * Fix test.html
2017-06-30 05:57:42 +00:00
obj5 = {obj..., ((k) -> {b: k})(99)...}
eq obj5.b, 99
deepEqual obj5.c, obj.c
# Should not trigger implicit call, e.g. rest ... => rest(...)
obj5 = {
obj ...
((k) -> {b: k})(99) ...
}
eq obj5.b, 99
deepEqual obj5.c, obj.c
[CS2] Destructuring object spreads (#4493) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * Correct comment * object destructuring * Allow custom position of the rest element. * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * object destructuring * Allow custom position of the rest element. * rest element in object destructuring * rest element in object destructuring * fix string interpolation * merging * fixing splats in object literal * Rest element in parameter destructuring * merging with CS2 * merged with CS2 * Add support for the object spread initializer. https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md * Fix misspellings, trailing whitespace, other minor details * merging with beta2 * refactor object spread properties * small fix * - Fixed object spread function parameters. - Clean up "Assign" and moved all logic for object rest properties in single method (compileObjectDestruct). - Add helper function "objectWithoutKeys" to the "UTILITIES" for use with object rest properties, e.g. {a, b, r...} = obj => {a, b} = obj, r = objectWithoutKeys(...) - Clean up "Obj" and moved all logic for object spread properties in single method (compileSpread). - Clean up "Code". - Add method "hasSplat" to "Obj" and "Value" for checking if Obj contains the splat. - Enable placing spread syntax triple dots on either right or left, per #85 (https://github.com/coffeescript6/discuss/issues/85) * Fixed typos * Remove unused code * Removed dots (e.g. splat) on the left side from the grammar * Initial release for deep spread properties, e.g. obj2 = {obj.b..., a: 1} or {obj[b][c]..., d: 7} Tests need to be prepared! * 1. Object literal spread properties Object literals: - obj = { {b:{c:{d:1}}}..., a:1 } Parenthetical: - obj = { ( body ), a:1 } - obj = { ( body )..., a:1 } Invocation: - obj = { ( (args) -> ... )(params), a:1 } - obj = { ( (args) -> ... )(params)..., a:1 } - obj = { foo(), a:1 } - obj = { foo()..., a:1 } 2. Refactor, cleanup & other optimizations. * Merged with 2.0 * Cleanup * Some more cleanup. * Fixed error with freeVariable and object destructuring. * Fixed errors with object spread properties. * Improvements, fixed errors. * Minor improvement. * Minor improvements. * Typo. * Remove unnecessary whitespace. * Remove unnecessary whitespace. * Changed few "assertErrorFormat" tests since parentheses are now allowed in the Obj. * Whitespace cleanup * Comments cleanup * fix destructured obj param declarations * refine fix; add test * Refactor function args ({a, b...}) * Additional tests for object destructuring in function argument. * Minor improvement for object destructuring variable declaration. * refactor function args ({a, b...}) and ({a, b...} = {}); Obj And Param cleanup * fix comment * Fix object destructuring variable declaration. * more tests with default values * fix typo * Fixed default values in object destructuring. * small fix * Babel’s tests for object rest spread * Style: spaces after colons in object declarations * Cleanup comments * Simplify Babel tests * Fix comments * Fix destructuring with splats in multiple objects * Add test for default values in detsructuring assignment with splats * Handle default values when assigning to object splats * Rewrite traverseRest to fix handling of dynamic keys * Fix double parens around destructuring with splats * Update compileObjectDestruct comments * Improve formatting of top-level destructures with splats and tidy parens * Added a bigger destructuring-with-defaults test and fixed a bug * Refactor destructuring grammar to allow additional forms * Add a missing case to ObjSpreadExpr * These tests shouldn’t run in the browser * Fix test.html
2017-06-30 05:57:42 +00:00
fn = -> {c: {d: 33, e: 44, f: {g: 55}}}
obj6 = {obj..., fn()...}
eq obj6.c.d, 33
deepEqual obj6.c, {d: 33, e: 44, f: {g: 55}}
obj7 = {obj..., fn()..., {c: {d: 55, e: 66, f: {77}}}...}
eq obj7.c.d, 55
deepEqual obj6.c, {d: 33, e: 44, f: {g: 55}}
# Should not trigger implicit call, e.g. rest ... => rest(...)
obj7 = {
obj ...
fn() ...
{c: {d: 55, e: 66, f: {77}}} ...
}
eq obj7.c.d, 55
deepEqual obj6.c, {d: 33, e: 44, f: {g: 55}}
obj =
a:
b:
c:
d:
e: {}
obj9 = {a:1, obj.a.b.c..., g:3}
deepEqual obj9.d, {e: {}}
a = "a"
c = "c"
obj9 = {a:1, obj[a].b[c]..., g:3}
deepEqual obj9.d, {e: {}}
obj9 = {a:1, obj.a["b"].c["d"]..., g:3}
deepEqual obj9["e"], {}
[CS2] Destructuring object spreads (#4493) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * Correct comment * object destructuring * Allow custom position of the rest element. * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * object destructuring * Allow custom position of the rest element. * rest element in object destructuring * rest element in object destructuring * fix string interpolation * merging * fixing splats in object literal * Rest element in parameter destructuring * merging with CS2 * merged with CS2 * Add support for the object spread initializer. https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md * Fix misspellings, trailing whitespace, other minor details * merging with beta2 * refactor object spread properties * small fix * - Fixed object spread function parameters. - Clean up "Assign" and moved all logic for object rest properties in single method (compileObjectDestruct). - Add helper function "objectWithoutKeys" to the "UTILITIES" for use with object rest properties, e.g. {a, b, r...} = obj => {a, b} = obj, r = objectWithoutKeys(...) - Clean up "Obj" and moved all logic for object spread properties in single method (compileSpread). - Clean up "Code". - Add method "hasSplat" to "Obj" and "Value" for checking if Obj contains the splat. - Enable placing spread syntax triple dots on either right or left, per #85 (https://github.com/coffeescript6/discuss/issues/85) * Fixed typos * Remove unused code * Removed dots (e.g. splat) on the left side from the grammar * Initial release for deep spread properties, e.g. obj2 = {obj.b..., a: 1} or {obj[b][c]..., d: 7} Tests need to be prepared! * 1. Object literal spread properties Object literals: - obj = { {b:{c:{d:1}}}..., a:1 } Parenthetical: - obj = { ( body ), a:1 } - obj = { ( body )..., a:1 } Invocation: - obj = { ( (args) -> ... )(params), a:1 } - obj = { ( (args) -> ... )(params)..., a:1 } - obj = { foo(), a:1 } - obj = { foo()..., a:1 } 2. Refactor, cleanup & other optimizations. * Merged with 2.0 * Cleanup * Some more cleanup. * Fixed error with freeVariable and object destructuring. * Fixed errors with object spread properties. * Improvements, fixed errors. * Minor improvement. * Minor improvements. * Typo. * Remove unnecessary whitespace. * Remove unnecessary whitespace. * Changed few "assertErrorFormat" tests since parentheses are now allowed in the Obj. * Whitespace cleanup * Comments cleanup * fix destructured obj param declarations * refine fix; add test * Refactor function args ({a, b...}) * Additional tests for object destructuring in function argument. * Minor improvement for object destructuring variable declaration. * refactor function args ({a, b...}) and ({a, b...} = {}); Obj And Param cleanup * fix comment * Fix object destructuring variable declaration. * more tests with default values * fix typo * Fixed default values in object destructuring. * small fix * Babel’s tests for object rest spread * Style: spaces after colons in object declarations * Cleanup comments * Simplify Babel tests * Fix comments * Fix destructuring with splats in multiple objects * Add test for default values in detsructuring assignment with splats * Handle default values when assigning to object splats * Rewrite traverseRest to fix handling of dynamic keys * Fix double parens around destructuring with splats * Update compileObjectDestruct comments * Improve formatting of top-level destructures with splats and tidy parens * Added a bigger destructuring-with-defaults test and fixed a bug * Refactor destructuring grammar to allow additional forms * Add a missing case to ObjSpreadExpr * These tests shouldn’t run in the browser * Fix test.html
2017-06-30 05:57:42 +00:00
test "bracket insertion when necessary", ->
[a] = [0] ? [1]
eq a, 0
2011-01-03 09:17:00 +00:00
# for implicit destructuring assignment in comprehensions, see the comprehension tests
test "destructuring assignment with context (@) properties", ->
a={}; b={}; c={}; d={}; e={}
obj =
fn: () ->
local = [a, {b, c}, d, e]
[@a, {b: @b, c: @c}, @d, @e] = local
eq undefined, obj[key] for key in ['a','b','c','d','e']
obj.fn()
eq a, obj.a
eq b, obj.b
eq c, obj.c
eq d, obj.d
eq e, obj.e
test "#1024: destructure empty assignments to produce javascript-like results", ->
2011-01-11 04:09:21 +00:00
eq 2 * [] = 3 + 5, 16
test "#1005: invalid identifiers allowed on LHS of destructuring assignment", ->
disallowed = ['eval', 'arguments'].concat CoffeeScript.RESERVED
2011-08-11 06:17:48 +00:00
throws (-> CoffeeScript.compile "[#{disallowed.join ', '}] = x"), null, 'all disallowed'
throws (-> CoffeeScript.compile "[#{disallowed.join '..., '}...] = x"), null, 'all disallowed as splats'
t = tSplat = null
for v in disallowed when v isnt 'class' # `class` by itself is an expression
2011-08-11 06:17:48 +00:00
throws (-> CoffeeScript.compile t), null, t = "[#{v}] = x"
throws (-> CoffeeScript.compile tSplat), null, tSplat = "[#{v}...] = x"
doesNotThrow ->
for v in disallowed
CoffeeScript.compile "[a.#{v}] = x"
CoffeeScript.compile "[a.#{v}...] = x"
CoffeeScript.compile "[@#{v}] = x"
CoffeeScript.compile "[@#{v}...] = x"
test "#2055: destructuring assignment with `new`", ->
{length} = new Array
eq 0, length
2014-01-24 16:00:34 +00:00
test "#156: destructuring with expansion", ->
array = [1..5]
[first, ..., last] = array
eq 1, first
eq 5, last
[..., lastButOne, last] = array
eq 4, lastButOne
eq 5, last
[first, second, ..., last] = array
eq 2, second
[..., last] = 'strings as well -> x'
eq 'x', last
throws (-> CoffeeScript.compile "[1, ..., 3]"), null, "prohibit expansion outside of assignment"
throws (-> CoffeeScript.compile "[..., a, b...] = c"), null, "prohibit expansion and a splat"
throws (-> CoffeeScript.compile "[...] = c"), null, "prohibit lone expansion"
2015-02-07 19:16:59 +00:00
test "destructuring with dynamic keys", ->
{"#{'a'}": a, """#{'b'}""": b, c} = {a: 1, b: 2, c: 3}
eq 1, a
eq 2, b
eq 3, c
throws -> CoffeeScript.compile '{"#{a}"} = b'
test "simple array destructuring defaults", ->
[a = 1] = []
eq 1, a
[a = 2] = [undefined]
eq 2, a
[a = 3] = [null]
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
eq null, a # Breaking change in CS2: per ES2015, default values are applied for `undefined` but not for `null`.
[a = 4] = [0]
eq 0, a
arr = [a = 5]
eq 5, a
arrayEq [5], arr
test "simple object destructuring defaults", ->
{b = 1} = {}
eq b, 1
{b = 2} = {b: undefined}
eq b, 2
{b = 3} = {b: null}
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
eq b, null # Breaking change in CS2: per ES2015, default values are applied for `undefined` but not for `null`.
{b = 4} = {b: 0}
eq b, 0
{b: c = 1} = {}
eq c, 1
{b: c = 2} = {b: undefined}
eq c, 2
{b: c = 3} = {b: null}
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
eq c, null # Breaking change in CS2: per ES2015, default values are applied for `undefined` but not for `null`.
{b: c = 4} = {b: 0}
eq c, 0
test "multiple array destructuring defaults", ->
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
[a = 1, b = 2, c] = [undefined, 12, 13]
eq a, 1
eq b, 12
eq c, 13
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
[a, b = 2, c = 3] = [undefined, 12, 13]
eq a, undefined
eq b, 12
eq c, 13
[a = 1, b, c = 3] = [11, 12]
eq a, 11
eq b, 12
eq c, 3
test "multiple object destructuring defaults", ->
{a = 1, b: bb = 2, 'c': c = 3, "#{0}": d = 4} = {"#{'b'}": 12}
eq a, 1
eq bb, 12
eq c, 3
eq d, 4
test "array destructuring defaults with splats", ->
[..., a = 9] = []
eq a, 9
[..., b = 9] = [19]
eq b, 19
test "deep destructuring assignment with defaults", ->
[a, [{b = 1, c = 3}] = [c: 2]] = [0]
eq a, 0
eq b, 1
eq c, 2
test "destructuring assignment with context (@) properties and defaults", ->
a={}; b={}; c={}; d={}; e={}
obj =
fn: () ->
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
local = [a, {b, c: undefined}, d]
[@a, {b: @b = b, @c = c}, @d, @e = e] = local
eq undefined, obj[key] for key in ['a','b','c','d','e']
obj.fn()
eq a, obj.a
eq b, obj.b
eq c, obj.c
eq d, obj.d
eq e, obj.e
test "destructuring assignment with defaults single evaluation", ->
callCount = 0
fn = -> callCount++
[a = fn()] = []
eq 0, a
eq 1, callCount
[a = fn()] = [10]
eq 10, a
eq 1, callCount
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
{a = fn(), b: c = fn()} = {a: 20, b: undefined}
eq 20, a
eq c, 1
eq callCount, 2
2011-01-03 09:17:00 +00:00
2011-03-12 02:41:12 +00:00
# Existential Assignment
2011-01-03 09:17:00 +00:00
test "existential assignment", ->
nonce = {}
a = false
a ?= nonce
eq false, a
b = undefined
b ?= nonce
eq nonce, b
c = null
c ?= nonce
eq nonce, c
test "#1627: prohibit conditional assignment of undefined variables", ->
2011-10-04 01:57:33 +00:00
throws (-> CoffeeScript.compile "x ?= 10"), null, "prohibit (x ?= 10)"
throws (-> CoffeeScript.compile "x ||= 10"), null, "prohibit (x ||= 10)"
throws (-> CoffeeScript.compile "x or= 10"), null, "prohibit (x or= 10)"
throws (-> CoffeeScript.compile "do -> x ?= 10"), null, "prohibit (do -> x ?= 10)"
throws (-> CoffeeScript.compile "do -> x ||= 10"), null, "prohibit (do -> x ||= 10)"
throws (-> CoffeeScript.compile "do -> x or= 10"), null, "prohibit (do -> x or= 10)"
doesNotThrow (-> CoffeeScript.compile "x = null; x ?= 10"), "allow (x = null; x ?= 10)"
doesNotThrow (-> CoffeeScript.compile "x = null; x ||= 10"), "allow (x = null; x ||= 10)"
doesNotThrow (-> CoffeeScript.compile "x = null; x or= 10"), "allow (x = null; x or= 10)"
doesNotThrow (-> CoffeeScript.compile "x = null; do -> x ?= 10"), "allow (x = null; do -> x ?= 10)"
doesNotThrow (-> CoffeeScript.compile "x = null; do -> x ||= 10"), "allow (x = null; do -> x ||= 10)"
doesNotThrow (-> CoffeeScript.compile "x = null; do -> x or= 10"), "allow (x = null; do -> x or= 10)"
2013-02-01 11:07:19 +00:00
2011-10-04 01:57:33 +00:00
throws (-> CoffeeScript.compile "-> -> -> x ?= 10"), null, "prohibit (-> -> -> x ?= 10)"
doesNotThrow (-> CoffeeScript.compile "x = null; -> -> -> x ?= 10"), "allow (x = null; -> -> -> x ?= 10)"
2013-02-01 11:07:19 +00:00
test "more existential assignment", ->
global.temp ?= 0
eq global.temp, 0
global.temp or= 100
eq global.temp, 100
delete global.temp
2011-05-11 13:11:41 +00:00
test "#1348, #1216: existential assignment compilation", ->
nonce = {}
a = nonce
b = (a ?= 0)
eq nonce, b
2011-05-11 13:11:41 +00:00
#the first ?= compiles into a statement; the second ?= compiles to a ternary expression
eq a ?= b ?= 1, nonce
2013-02-01 11:07:19 +00:00
2011-05-11 13:11:41 +00:00
if a then a ?= 2 else a = 3
eq a, nonce
test "#1591, #1101: splatted expressions in destructuring assignment must be assignable", ->
nonce = {}
for nonref in ['', '""', '0', 'f()', '(->)'].concat CoffeeScript.RESERVED
eq nonce, (try CoffeeScript.compile "[#{nonref}...] = v" catch e then nonce)
2011-12-24 12:04:34 +00:00
test "#1643: splatted accesses in destructuring assignments should not be declared as variables", ->
nonce = {}
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
accesses = ['o.a', 'o["a"]', '(o.a)', '(o.a).a', '@o.a', 'C::a', 'f().a', 'o?.a', 'o?.a.b', 'f?().a']
for access in accesses
2011-09-09 22:59:35 +00:00
for i,j in [1,2,3] #position can matter
2011-12-24 12:04:34 +00:00
code =
"""
2011-12-24 12:04:34 +00:00
nonce = {}; nonce2 = {}; nonce3 = {};
@o = o = new (class C then a:{}); f = -> o
[#{new Array(i).join('x,')}#{access}...] = [#{new Array(i).join('0,')}nonce, nonce2, nonce3]
unless #{access}[0] is nonce and #{access}[1] is nonce2 and #{access}[2] is nonce3 then throw new Error('[...]')
"""
2011-09-09 22:59:35 +00:00
eq nonce, unless (try CoffeeScript.run code, bare: true catch e then true) then nonce
# subpatterns like `[[a]...]` and `[{a}...]`
subpatterns = ['[sub, sub2, sub3]', '{0: sub, 1: sub2, 2: sub3}']
for subpattern in subpatterns
for i,j in [1,2,3]
code =
"""
2011-12-24 12:04:34 +00:00
nonce = {}; nonce2 = {}; nonce3 = {};
[#{new Array(i).join('x,')}#{subpattern}...] = [#{new Array(i).join('0,')}nonce, nonce2, nonce3]
unless sub is nonce and sub2 is nonce2 and sub3 is nonce3 then throw new Error('[sub...]')
"""
2011-09-09 22:59:35 +00:00
eq nonce, unless (try CoffeeScript.run code, bare: true catch e then true) then nonce
2011-12-14 23:31:20 +00:00
test "#1838: Regression with variable assignment", ->
name =
'dave'
2011-12-24 12:04:34 +00:00
eq name, 'dave'
test '#2211: splats in destructured parameters', ->
doesNotThrow -> CoffeeScript.compile '([a...]) ->'
doesNotThrow -> CoffeeScript.compile '([a...],b) ->'
doesNotThrow -> CoffeeScript.compile '([a...],[b...]) ->'
throws -> CoffeeScript.compile '([a...,[a...]]) ->'
doesNotThrow -> CoffeeScript.compile '([a...,[b...]]) ->'
test '#2213: invocations within destructured parameters', ->
throws -> CoffeeScript.compile '([a()])->'
throws -> CoffeeScript.compile '([a:b()])->'
throws -> CoffeeScript.compile '([a:b.c()])->'
throws -> CoffeeScript.compile '({a()})->'
throws -> CoffeeScript.compile '({a:b()})->'
throws -> CoffeeScript.compile '({a:b.c()})->'
test '#2532: compound assignment with terminator', ->
doesNotThrow -> CoffeeScript.compile """
a = "hello"
a +=
"
world
!
"
"""
2013-02-01 11:07:19 +00:00
test "#2613: parens on LHS of destructuring", ->
a = {}
[(a).b] = [1, 2, 3]
eq a.b, 1
test "#2181: conditional assignment as a subexpression", ->
a = false
false && a or= true
eq false, a
eq false, not a or= true
test "#1500: Assignment to variables similar to generated variables", ->
len = 0
x = ((results = null; n) for n in [1, 2, 3])
arrayEq [1, 2, 3], x
eq 0, len
for x in [1, 2, 3]
f = ->
i = 0
f()
eq 'undefined', typeof i
ref = 2
x = ref * 2 ? 1
eq x, 4
eq 'undefined', typeof ref1
x = {}
base = -> x
name = -1
base()[-name] ?= 2
eq x[1], 2
eq base(), x
eq name, -1
f = (@a, a) -> [@a, a]
arrayEq [1, 2], f.call scope = {}, 1, 2
eq 1, scope.a
try throw 'foo'
catch error
eq error, 'foo'
eq error, 'foo'
doesNotThrow -> CoffeeScript.compile '(@slice...) ->'
test "Assignment to variables similar to helper functions", ->
f = (slice...) -> slice
arrayEq [1, 2, 3], f 1, 2, 3
eq 'undefined', typeof slice1
class A
class B extends A
extend = 3
hasProp = 4
value: 5
method: (bind, bind1) => [bind, bind1, extend, hasProp, @value]
{method} = new B
arrayEq [1, 2, 3, 4, 5], method 1, 2
modulo = -1 %% 3
eq 2, modulo
indexOf = [1, 2, 3]
ok 2 in indexOf
test "#4566: destructuring with nested default values", ->
{a: {b = 1}} = a: {}
eq 1, b
{c: {d} = {}} = c: d: 3
eq 3, d
{e: {f = 5} = {}} = {}
eq 5, f
test "#4674: _extends utility for object spreads 1", ->
eqJS(
"{a, b..., c..., d}"
"""
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
_extends({a}, b, c, {d});
"""
)
test "#4674: _extends utility for object spreads 2", ->
_extends = -> 3
a = b: 1
c = d: 2
e = {a..., c...}
eq e.b, 1
eq e.d, 2
test "#4673: complex destructured object spread variables", ->
b = c: 1
{{a...}...} = b
eq a.c, 1
d = {}
{d.e...} = f: 1
eq d.e.f, 1
{{g}...} = g: 1
eq g, 1