2010-12-29 00:48:54 -05:00
|
|
|
|
# Classes
|
|
|
|
|
# -------
|
|
|
|
|
|
2010-12-29 14:06:57 -05:00
|
|
|
|
# * Class Definition
|
|
|
|
|
# * Class Instantiation
|
|
|
|
|
# * Inheritance and Super
|
[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 00:55:30 -05:00
|
|
|
|
# * ES2015+ Class Interoperability
|
2010-12-29 14:06:57 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "classes with a four-level inheritance chain", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class Base
|
|
|
|
|
func: (string) ->
|
|
|
|
|
"zero/#{string}"
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
@static: (string) ->
|
|
|
|
|
"static/#{string}"
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class FirstChild extends Base
|
|
|
|
|
func: (string) ->
|
|
|
|
|
super('one/') + string
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
SecondChild = class extends FirstChild
|
|
|
|
|
func: (string) ->
|
|
|
|
|
super('two/') + string
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
thirdCtor = ->
|
|
|
|
|
@array = [1, 2, 3]
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class ThirdChild extends SecondChild
|
[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 00:55:30 -05:00
|
|
|
|
constructor: ->
|
|
|
|
|
super()
|
|
|
|
|
thirdCtor.call this
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
# Gratuitous comment for testing.
|
|
|
|
|
func: (string) ->
|
|
|
|
|
super('three/') + string
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
result = (new ThirdChild).func 'four'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
ok result is 'zero/one/two/three/four'
|
|
|
|
|
ok Base.static('word') is 'static/word'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
ok (new ThirdChild).array.join(' ') is '1 2 3'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "constructors with inheritance and super", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
identity = (f) -> f
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class TopClass
|
|
|
|
|
constructor: (arg) ->
|
|
|
|
|
@prop = 'top-' + arg
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class SuperClass extends TopClass
|
|
|
|
|
constructor: (arg) ->
|
|
|
|
|
identity super 'super-' + arg
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class SubClass extends SuperClass
|
|
|
|
|
constructor: ->
|
|
|
|
|
identity super 'sub'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
ok (new SubClass).prop is 'top-super-sub'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
test "'super' with accessors", ->
|
|
|
|
|
class Base
|
|
|
|
|
m: -> 4
|
|
|
|
|
n: -> 5
|
|
|
|
|
o: -> 6
|
2011-03-11 21:55:26 -05:00
|
|
|
|
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
name = 'o'
|
|
|
|
|
class A extends Base
|
|
|
|
|
m: -> super()
|
|
|
|
|
n: -> super.n()
|
|
|
|
|
"#{name}": -> super()
|
|
|
|
|
p: -> super[name]()
|
2011-03-11 21:55:26 -05:00
|
|
|
|
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
a = new A
|
|
|
|
|
eq 4, a.m()
|
|
|
|
|
eq 5, a.n()
|
|
|
|
|
eq 6, a.o()
|
|
|
|
|
eq 6, a.p()
|
2011-03-11 21:55:26 -05:00
|
|
|
|
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
test "soaked 'super' invocation", ->
|
|
|
|
|
class Base
|
|
|
|
|
method: -> 2
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
class A extends Base
|
|
|
|
|
method: -> super?()
|
|
|
|
|
noMethod: -> super?()
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
a = new A
|
|
|
|
|
eq 2, a.method()
|
|
|
|
|
eq undefined, a.noMethod()
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
name = 'noMethod'
|
|
|
|
|
class B extends Base
|
|
|
|
|
"#{'method'}": -> super?()
|
|
|
|
|
"#{'noMethod'}": -> super?() ? super['method']()
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
b = new B
|
|
|
|
|
eq 2, b.method()
|
|
|
|
|
eq 2, b.noMethod()
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "'@' referring to the current instance, and not being coerced into a call", ->
|
|
|
|
|
|
|
|
|
|
class ClassName
|
|
|
|
|
amI: ->
|
|
|
|
|
@ instanceof ClassName
|
|
|
|
|
|
|
|
|
|
obj = new ClassName
|
|
|
|
|
ok obj.amI()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test "super() calls in constructors of classes that are defined as object properties", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class Hive
|
|
|
|
|
constructor: (name) -> @name = name
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class Hive.Bee extends Hive
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
constructor: (name) -> super name
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
maya = new Hive.Bee 'Maya'
|
|
|
|
|
ok maya.name is 'Maya'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "classes with JS-keyword properties", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class Class
|
|
|
|
|
class: 'class'
|
|
|
|
|
name: -> @class
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
instance = new Class
|
|
|
|
|
ok instance.class is 'class'
|
|
|
|
|
ok instance.name() is 'class'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
2017-06-14 18:11:53 -04:00
|
|
|
|
test "Classes with methods that are pre-bound to the instance, or statically, to the class", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class Dog
|
|
|
|
|
constructor: (name) ->
|
|
|
|
|
@name = name
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2017-06-14 18:11:53 -04:00
|
|
|
|
bark: =>
|
|
|
|
|
"#{@name} woofs!"
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
@static = =>
|
|
|
|
|
new this('Dog')
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2017-06-14 18:11:53 -04:00
|
|
|
|
spark = new Dog('Spark')
|
|
|
|
|
fido = new Dog('Fido')
|
|
|
|
|
fido.bark = spark.bark
|
|
|
|
|
|
|
|
|
|
ok fido.bark() is 'Spark woofs!'
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
obj = func: Dog.static
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
ok obj.func().name is 'Dog'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
2017-06-14 18:11:53 -04:00
|
|
|
|
test "a bound function in a bound function", ->
|
|
|
|
|
|
|
|
|
|
class Mini
|
|
|
|
|
num: 10
|
|
|
|
|
generate: =>
|
|
|
|
|
for i in [1..3]
|
|
|
|
|
=>
|
|
|
|
|
@num
|
|
|
|
|
|
|
|
|
|
m = new Mini
|
|
|
|
|
eq (func() for func in m.generate()).join(' '), '10 10 10'
|
|
|
|
|
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "contructor called with varargs", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class Connection
|
|
|
|
|
constructor: (one, two, three) ->
|
|
|
|
|
[@one, @two, @three] = [one, two, three]
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
out: ->
|
|
|
|
|
"#{@one}-#{@two}-#{@three}"
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
list = [3, 2, 1]
|
|
|
|
|
conn = new Connection list...
|
|
|
|
|
ok conn instanceof Connection
|
|
|
|
|
ok conn.out() is '3-2-1'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "calling super and passing along all arguments", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class Parent
|
|
|
|
|
method: (args...) -> @args = args
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class Child extends Parent
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
method: -> super arguments...
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
c = new Child
|
|
|
|
|
c.method 1, 2, 3, 4
|
|
|
|
|
ok c.args.join(' ') is '1 2 3 4'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "classes wrapped in decorators", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
func = (klass) ->
|
|
|
|
|
klass::prop = 'value'
|
|
|
|
|
klass
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
func class Test
|
|
|
|
|
prop2: 'value2'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
ok (new Test).prop is 'value'
|
|
|
|
|
ok (new Test).prop2 is 'value2'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "anonymous classes", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
obj =
|
|
|
|
|
klass: class
|
|
|
|
|
method: -> 'value'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
instance = new obj.klass
|
|
|
|
|
ok instance.method() is 'value'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "Implicit objects as static properties", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class Static
|
|
|
|
|
@static =
|
|
|
|
|
one: 1
|
|
|
|
|
two: 2
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
ok Static.static.one is 1
|
|
|
|
|
ok Static.static.two is 2
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "nothing classes", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
c = class
|
|
|
|
|
ok c instanceof Function
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
|
|
|
|
|
2011-12-15 12:29:03 -05:00
|
|
|
|
test "classes with static-level implicit objects", ->
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-15 12:29:03 -05:00
|
|
|
|
class A
|
|
|
|
|
@static = one: 1
|
|
|
|
|
two: 2
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-15 12:29:03 -05:00
|
|
|
|
class B
|
|
|
|
|
@static = one: 1,
|
|
|
|
|
two: 2
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-15 12:29:03 -05:00
|
|
|
|
eq A.static.one, 1
|
|
|
|
|
eq A.static.two, undefined
|
|
|
|
|
eq (new A).two, 2
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-15 12:29:03 -05:00
|
|
|
|
eq B.static.one, 1
|
|
|
|
|
eq B.static.two, 2
|
|
|
|
|
eq (new B).two, undefined
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "classes with value'd constructors", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
counter = 0
|
|
|
|
|
classMaker = ->
|
2011-05-06 01:00:35 -04:00
|
|
|
|
inner = ++counter
|
2011-03-11 21:55:26 -05:00
|
|
|
|
->
|
|
|
|
|
@value = inner
|
2018-03-18 02:02:40 -04:00
|
|
|
|
@
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class One
|
|
|
|
|
constructor: classMaker()
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class Two
|
|
|
|
|
constructor: classMaker()
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-05-10 09:24:20 -04:00
|
|
|
|
eq (new One).value, 1
|
|
|
|
|
eq (new Two).value, 2
|
|
|
|
|
eq (new One).value, 1
|
|
|
|
|
eq (new Two).value, 2
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
2013-03-04 04:26:55 -05:00
|
|
|
|
test "executable class bodies", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class A
|
|
|
|
|
if true
|
|
|
|
|
b: 'b'
|
|
|
|
|
else
|
|
|
|
|
c: 'c'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
a = new A
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
eq a.b, 'b'
|
|
|
|
|
eq a.c, undefined
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
2013-03-04 04:26:55 -05:00
|
|
|
|
test "#2502: parenthesizing inner object values", ->
|
|
|
|
|
|
|
|
|
|
class A
|
|
|
|
|
category: (type: 'string')
|
|
|
|
|
sections: (type: 'number', default: 0)
|
|
|
|
|
|
|
|
|
|
eq (new A).category.type, 'string'
|
|
|
|
|
|
|
|
|
|
eq (new A).sections.default, 0
|
|
|
|
|
|
|
|
|
|
|
2013-04-05 21:31:24 -04:00
|
|
|
|
test "conditional prototype property assignment", ->
|
|
|
|
|
debug = false
|
|
|
|
|
|
|
|
|
|
class Person
|
|
|
|
|
if debug
|
|
|
|
|
age: -> 10
|
|
|
|
|
else
|
|
|
|
|
age: -> 20
|
|
|
|
|
|
|
|
|
|
eq (new Person).age(), 20
|
|
|
|
|
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "mild metaprogramming", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class Base
|
|
|
|
|
@attr: (name) ->
|
|
|
|
|
@::[name] = (val) ->
|
|
|
|
|
if arguments.length > 0
|
|
|
|
|
@["_#{name}"] = val
|
|
|
|
|
else
|
|
|
|
|
@["_#{name}"]
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class Robot extends Base
|
|
|
|
|
@attr 'power'
|
|
|
|
|
@attr 'speed'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
robby = new Robot
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
ok robby.power() is undefined
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
robby.power 11
|
|
|
|
|
robby.speed Infinity
|
|
|
|
|
|
|
|
|
|
eq robby.power(), 11
|
|
|
|
|
eq robby.speed(), Infinity
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test "namespaced classes do not reserve their function name in outside scope", ->
|
|
|
|
|
|
|
|
|
|
one = {}
|
|
|
|
|
two = {}
|
|
|
|
|
|
|
|
|
|
class one.Klass
|
|
|
|
|
@label = "one"
|
|
|
|
|
|
|
|
|
|
class two.Klass
|
|
|
|
|
@label = "two"
|
|
|
|
|
|
|
|
|
|
eq typeof Klass, 'undefined'
|
|
|
|
|
eq one.Klass.label, 'one'
|
|
|
|
|
eq two.Klass.label, 'two'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test "nested classes", ->
|
|
|
|
|
|
|
|
|
|
class Outer
|
|
|
|
|
constructor: ->
|
|
|
|
|
@label = 'outer'
|
|
|
|
|
|
|
|
|
|
class @Inner
|
|
|
|
|
constructor: ->
|
|
|
|
|
@label = 'inner'
|
|
|
|
|
|
|
|
|
|
eq (new Outer).label, 'outer'
|
|
|
|
|
eq (new Outer.Inner).label, 'inner'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test "variables in constructor bodies are correctly scoped", ->
|
|
|
|
|
|
|
|
|
|
class A
|
|
|
|
|
x = 1
|
2010-12-29 00:48:54 -05:00
|
|
|
|
constructor: ->
|
2011-03-11 21:55:26 -05:00
|
|
|
|
x = 10
|
|
|
|
|
y = 20
|
|
|
|
|
y = 2
|
|
|
|
|
captured: ->
|
|
|
|
|
{x, y}
|
|
|
|
|
|
|
|
|
|
a = new A
|
|
|
|
|
eq a.captured().x, 10
|
|
|
|
|
eq a.captured().y, 2
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "Issue #924: Static methods in nested classes", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class A
|
|
|
|
|
@B: class
|
|
|
|
|
@c = -> 5
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
eq A.B.c(), 5
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "`class extends this`", ->
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
class A
|
|
|
|
|
func: -> 'A'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
B = null
|
|
|
|
|
makeClass = ->
|
|
|
|
|
B = class extends this
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
func: -> super() + ' B'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
makeClass.call A
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
eq (new B()).func(), 'A B'
|
2010-12-29 00:48:54 -05:00
|
|
|
|
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "ensure that constructors invoked with splats return a new object", ->
|
2010-12-30 22:48:31 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
args = [1, 2, 3]
|
|
|
|
|
Type = (@args) ->
|
|
|
|
|
type = new Type args
|
2010-12-30 22:48:31 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
ok type and type instanceof Type
|
|
|
|
|
ok type.args and type.args instanceof Array
|
|
|
|
|
ok v is args[i] for v, i in type.args
|
2010-12-30 22:48:31 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
Type1 = (@a, @b, @c) ->
|
|
|
|
|
type1 = new Type1 args...
|
2010-12-30 22:48:31 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
ok type1 instanceof Type1
|
|
|
|
|
eq type1.constructor, Type1
|
|
|
|
|
ok type1.a is args[0] and type1.b is args[1] and type1.c is args[2]
|
2010-12-30 22:48:31 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
# Ensure that constructors invoked with splats cache the function.
|
|
|
|
|
called = 0
|
|
|
|
|
get = -> if called++ then false else class Type
|
[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 00:55:30 -05:00
|
|
|
|
new (get()) args...
|
2010-12-30 22:48:31 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "`new` shouldn't add extra parens", ->
|
2010-12-30 22:48:31 -05:00
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
ok new Date().constructor is Date
|
2010-12-30 22:48:31 -05:00
|
|
|
|
|
|
|
|
|
|
2011-03-11 21:55:26 -05:00
|
|
|
|
test "`new` works against bare function", ->
|
2011-05-28 18:58:48 -04:00
|
|
|
|
|
|
|
|
|
eq Date, new ->
|
|
|
|
|
Date
|
2011-04-27 21:56:08 -04:00
|
|
|
|
|
2018-10-08 13:20:27 -04:00
|
|
|
|
test "`new` works against statement", ->
|
|
|
|
|
|
|
|
|
|
class A
|
|
|
|
|
(new try A) instanceof A
|
2011-04-27 21:56:08 -04:00
|
|
|
|
|
2011-05-06 01:00:35 -04:00
|
|
|
|
test "#1182: a subclass should be able to set its constructor to an external function", ->
|
2011-04-27 21:56:08 -04:00
|
|
|
|
ctor = ->
|
|
|
|
|
@val = 1
|
[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 00:55:30 -05:00
|
|
|
|
return
|
2011-04-27 21:56:08 -04:00
|
|
|
|
class A
|
|
|
|
|
class B extends A
|
|
|
|
|
constructor: ctor
|
2011-05-06 01:00:35 -04:00
|
|
|
|
eq (new B).val, 1
|
|
|
|
|
|
|
|
|
|
test "#1182: external constructors continued", ->
|
|
|
|
|
ctor = ->
|
|
|
|
|
class A
|
|
|
|
|
class B extends A
|
|
|
|
|
method: ->
|
|
|
|
|
constructor: ctor
|
|
|
|
|
ok B::method
|
|
|
|
|
|
|
|
|
|
test "#1313: misplaced __extends", ->
|
|
|
|
|
nonce = {}
|
|
|
|
|
class A
|
|
|
|
|
class B extends A
|
|
|
|
|
prop: nonce
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
constructor: -> super()
|
2011-05-06 01:00:35 -04:00
|
|
|
|
eq nonce, B::prop
|
2011-05-06 09:48:12 -04:00
|
|
|
|
|
|
|
|
|
test "#1182: execution order needs to be considered as well", ->
|
|
|
|
|
counter = 0
|
|
|
|
|
makeFn = (n) -> eq n, ++counter; ->
|
|
|
|
|
class B extends (makeFn 1)
|
|
|
|
|
@B: makeFn 2
|
|
|
|
|
constructor: makeFn 3
|
2011-05-08 17:16:45 -04:00
|
|
|
|
|
2017-06-14 18:11:53 -04:00
|
|
|
|
test "#1182: external constructors with bound functions", ->
|
|
|
|
|
fn = ->
|
|
|
|
|
{one: 1}
|
|
|
|
|
this
|
|
|
|
|
class B
|
|
|
|
|
class A
|
|
|
|
|
constructor: fn
|
|
|
|
|
method: => this instanceof A
|
|
|
|
|
ok (new A).method.call(new B)
|
|
|
|
|
|
|
|
|
|
test "#1372: bound class methods with reserved names", ->
|
|
|
|
|
class C
|
|
|
|
|
delete: =>
|
|
|
|
|
ok C::delete
|
|
|
|
|
|
2011-05-25 03:22:06 -04:00
|
|
|
|
test "#1380: `super` with reserved names", ->
|
|
|
|
|
class C
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
do: -> super()
|
2011-05-25 03:22:06 -04:00
|
|
|
|
ok C::do
|
2011-05-25 12:57:45 -04:00
|
|
|
|
|
|
|
|
|
class B
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
0: -> super()
|
2011-05-25 12:57:45 -04:00
|
|
|
|
ok B::[0]
|
2011-08-04 13:40:37 -04:00
|
|
|
|
|
|
|
|
|
test "#1464: bound class methods should keep context", ->
|
|
|
|
|
nonce = {}
|
|
|
|
|
nonce2 = {}
|
|
|
|
|
class C
|
|
|
|
|
constructor: (@id) ->
|
|
|
|
|
@boundStaticColon: => new this(nonce)
|
|
|
|
|
@boundStaticEqual= => new this(nonce2)
|
|
|
|
|
eq nonce, C.boundStaticColon().id
|
|
|
|
|
eq nonce2, C.boundStaticEqual().id
|
2011-08-07 01:48:27 -04:00
|
|
|
|
|
2011-08-11 01:52:10 -04:00
|
|
|
|
test "#1009: classes with reserved words as determined names", -> (->
|
|
|
|
|
eq 'function', typeof (class @for)
|
|
|
|
|
ok not /\beval\b/.test (class @eval).toString()
|
|
|
|
|
ok not /\barguments\b/.test (class @arguments).toString()
|
|
|
|
|
).call {}
|
2011-08-07 05:02:01 -04:00
|
|
|
|
|
|
|
|
|
test "#1482: classes can extend expressions", ->
|
|
|
|
|
id = (x) -> x
|
|
|
|
|
nonce = {}
|
|
|
|
|
class A then nonce: nonce
|
|
|
|
|
class B extends id A
|
|
|
|
|
eq nonce, (new B).nonce
|
2011-08-12 17:16:25 -04:00
|
|
|
|
|
|
|
|
|
test "#1598: super works for static methods too", ->
|
|
|
|
|
|
|
|
|
|
class Parent
|
|
|
|
|
method: ->
|
|
|
|
|
'NO'
|
|
|
|
|
@method: ->
|
|
|
|
|
'yes'
|
|
|
|
|
|
|
|
|
|
class Child extends Parent
|
|
|
|
|
@method: ->
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
'pass? ' + super()
|
2011-08-12 17:16:25 -04:00
|
|
|
|
|
|
|
|
|
eq Child.method(), 'pass? yes'
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-14 11:02:10 -05:00
|
|
|
|
test "#1842: Regression with bound functions within bound class methods", ->
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-14 11:02:10 -05:00
|
|
|
|
class Store
|
|
|
|
|
@bound: =>
|
|
|
|
|
do =>
|
|
|
|
|
eq this, Store
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-14 11:02:10 -05:00
|
|
|
|
Store.bound()
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-14 11:06:01 -05:00
|
|
|
|
# And a fancier case:
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-14 11:06:01 -05:00
|
|
|
|
class Store
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-14 11:06:01 -05:00
|
|
|
|
eq this, Store
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-14 11:06:01 -05:00
|
|
|
|
@bound: =>
|
|
|
|
|
do =>
|
|
|
|
|
eq this, Store
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-14 11:06:01 -05:00
|
|
|
|
@unbound: ->
|
|
|
|
|
eq this, Store
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2017-06-14 18:11:53 -04:00
|
|
|
|
instance: =>
|
2011-12-14 11:06:01 -05:00
|
|
|
|
ok this instanceof Store
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-14 11:06:01 -05:00
|
|
|
|
Store.bound()
|
|
|
|
|
Store.unbound()
|
2011-12-14 12:17:21 -05:00
|
|
|
|
(new Store).instance()
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-14 12:17:21 -05:00
|
|
|
|
test "#1876: Class @A extends A", ->
|
|
|
|
|
class A
|
|
|
|
|
class @A extends A
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-14 12:17:21 -05:00
|
|
|
|
ok (new @A) instanceof A
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-15 16:03:01 -05:00
|
|
|
|
test "#1813: Passing class definitions as expressions", ->
|
|
|
|
|
ident = (x) -> x
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-15 16:03:01 -05:00
|
|
|
|
result = ident class A then x = 1
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-15 16:03:01 -05:00
|
|
|
|
eq result, A
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-15 16:03:01 -05:00
|
|
|
|
result = ident class B extends A
|
|
|
|
|
x = 1
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2011-12-15 16:03:01 -05:00
|
|
|
|
eq result, B
|
2011-12-24 07:04:34 -05:00
|
|
|
|
|
2013-02-28 08:37:30 -05:00
|
|
|
|
test "#1966: external constructors should produce their return value", ->
|
|
|
|
|
ctor = -> {}
|
|
|
|
|
class A then constructor: ctor
|
|
|
|
|
ok (new A) not instanceof A
|
|
|
|
|
|
2011-12-27 19:54:14 -05:00
|
|
|
|
test "#1980: regression with an inherited class with static function members", ->
|
2012-01-16 15:50:09 -05:00
|
|
|
|
|
2011-12-27 19:54:14 -05:00
|
|
|
|
class A
|
|
|
|
|
|
|
|
|
|
class B extends A
|
|
|
|
|
@static: => 'value'
|
2012-01-16 15:50:09 -05:00
|
|
|
|
|
2012-01-12 18:34:50 -05:00
|
|
|
|
eq B.static(), 'value'
|
2012-01-16 15:50:09 -05:00
|
|
|
|
|
2012-01-12 18:34:50 -05:00
|
|
|
|
test "#1534: class then 'use strict'", ->
|
2012-01-14 15:07:32 -05:00
|
|
|
|
# [14.1 Directive Prologues and the Use Strict Directive](http://es5.github.com/#x14.1)
|
2012-01-12 18:34:50 -05:00
|
|
|
|
nonce = {}
|
2012-01-16 14:09:06 -05:00
|
|
|
|
error = 'do -> ok this'
|
2012-01-14 15:07:32 -05:00
|
|
|
|
strictTest = "do ->'use strict';#{error}"
|
2012-01-13 13:59:24 -05:00
|
|
|
|
return unless (try CoffeeScript.run strictTest, bare: yes catch e then nonce) is nonce
|
2012-01-16 15:50:09 -05:00
|
|
|
|
|
2012-01-14 15:07:32 -05:00
|
|
|
|
throws -> CoffeeScript.run "class then 'use strict';#{error}", bare: yes
|
|
|
|
|
doesNotThrow -> CoffeeScript.run "class then #{error}", bare: yes
|
|
|
|
|
doesNotThrow -> CoffeeScript.run "class then #{error};'use strict'", bare: yes
|
2012-01-16 15:50:09 -05:00
|
|
|
|
|
2012-01-14 15:07:32 -05:00
|
|
|
|
# comments are ignored in the Directive Prologue
|
|
|
|
|
comments = ["""
|
2012-01-13 13:59:24 -05:00
|
|
|
|
class
|
|
|
|
|
### comment ###
|
|
|
|
|
'use strict'
|
2012-01-14 15:07:32 -05:00
|
|
|
|
#{error}""",
|
|
|
|
|
"""
|
2012-01-13 13:59:24 -05:00
|
|
|
|
class
|
|
|
|
|
### comment 1 ###
|
|
|
|
|
### comment 2 ###
|
|
|
|
|
'use strict'
|
2012-01-14 15:07:32 -05:00
|
|
|
|
#{error}""",
|
|
|
|
|
"""
|
2012-01-13 13:59:24 -05:00
|
|
|
|
class
|
|
|
|
|
### comment 1 ###
|
|
|
|
|
### comment 2 ###
|
|
|
|
|
'use strict'
|
2012-01-14 15:07:32 -05:00
|
|
|
|
#{error}
|
|
|
|
|
### comment 3 ###"""
|
|
|
|
|
]
|
2012-01-13 13:59:24 -05:00
|
|
|
|
throws (-> CoffeeScript.run comment, bare: yes) for comment in comments
|
2012-01-16 15:50:09 -05:00
|
|
|
|
|
|
|
|
|
# [ES5 §14.1](http://es5.github.com/#x14.1) allows for other directives
|
2012-01-14 15:07:32 -05:00
|
|
|
|
directives = ["""
|
|
|
|
|
class
|
|
|
|
|
'directive 1'
|
|
|
|
|
'use strict'
|
|
|
|
|
#{error}""",
|
|
|
|
|
"""
|
|
|
|
|
class
|
|
|
|
|
'use strict'
|
|
|
|
|
'directive 2'
|
|
|
|
|
#{error}""",
|
|
|
|
|
"""
|
2012-01-13 13:59:24 -05:00
|
|
|
|
class
|
|
|
|
|
### comment 1 ###
|
2012-01-14 15:07:32 -05:00
|
|
|
|
'directive 1'
|
2012-01-13 13:59:24 -05:00
|
|
|
|
'use strict'
|
2012-01-14 15:07:32 -05:00
|
|
|
|
#{error}""",
|
|
|
|
|
"""
|
|
|
|
|
class
|
|
|
|
|
### comment 1 ###
|
|
|
|
|
'directive 1'
|
|
|
|
|
### comment 2 ###
|
|
|
|
|
'use strict'
|
|
|
|
|
#{error}"""
|
|
|
|
|
]
|
|
|
|
|
throws (-> CoffeeScript.run directive, bare: yes) for directive in directives
|
2012-04-11 18:35:51 -04:00
|
|
|
|
|
|
|
|
|
test "#2052: classes should work in strict mode", ->
|
|
|
|
|
try
|
|
|
|
|
do ->
|
|
|
|
|
'use strict'
|
|
|
|
|
class A
|
|
|
|
|
catch e
|
|
|
|
|
ok no
|
2013-01-07 00:08:32 -05:00
|
|
|
|
|
2013-10-26 00:54:54 -04:00
|
|
|
|
test "directives in class with extends ", ->
|
|
|
|
|
strictTest = """
|
|
|
|
|
class extends Object
|
|
|
|
|
### comment ###
|
|
|
|
|
'use strict'
|
|
|
|
|
do -> eq this, undefined
|
|
|
|
|
"""
|
|
|
|
|
CoffeeScript.run strictTest, bare: yes
|
|
|
|
|
|
2013-01-07 00:08:32 -05:00
|
|
|
|
test "#2630: class bodies can't reference arguments", ->
|
2019-12-16 00:16:55 -05:00
|
|
|
|
throwsCompileError 'class Test then arguments'
|
2013-02-01 06:30:22 -05:00
|
|
|
|
|
2016-09-26 09:33:44 -04:00
|
|
|
|
# #4320: Don't be too eager when checking, though.
|
|
|
|
|
class Test
|
|
|
|
|
arguments: 5
|
|
|
|
|
eq 5, Test::arguments
|
|
|
|
|
|
2013-02-24 13:09:01 -05:00
|
|
|
|
test "#2319: fn class n extends o.p [INDENT] x = 123", ->
|
|
|
|
|
first = ->
|
|
|
|
|
|
|
|
|
|
base = onebase: ->
|
|
|
|
|
|
|
|
|
|
first class OneKeeper extends base.onebase
|
|
|
|
|
one = 1
|
|
|
|
|
one: -> one
|
|
|
|
|
|
2013-02-28 08:37:30 -05:00
|
|
|
|
eq new OneKeeper().one(), 1
|
2013-02-28 08:37:47 -05:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test "#2599: other typed constructors should be inherited", ->
|
|
|
|
|
class Base
|
|
|
|
|
constructor: -> return {}
|
|
|
|
|
|
|
|
|
|
class Derived extends Base
|
|
|
|
|
|
|
|
|
|
ok (new Derived) not instanceof Derived
|
|
|
|
|
ok (new Derived) not instanceof Base
|
|
|
|
|
ok (new Base) not instanceof Base
|
|
|
|
|
|
[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 00:55:30 -05:00
|
|
|
|
test "extending native objects works with and without defining a constructor", ->
|
|
|
|
|
class MyArray extends Array
|
|
|
|
|
method: -> 'yes!'
|
2013-02-28 08:37:47 -05:00
|
|
|
|
|
[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 00:55:30 -05:00
|
|
|
|
myArray = new MyArray
|
|
|
|
|
ok myArray instanceof MyArray
|
|
|
|
|
ok 'yes!', myArray.method()
|
2013-02-28 08:37:47 -05:00
|
|
|
|
|
[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 00:55:30 -05:00
|
|
|
|
class OverrideArray extends Array
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
constructor: -> super()
|
2013-02-28 08:37:47 -05:00
|
|
|
|
method: -> 'yes!'
|
|
|
|
|
|
[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 00:55:30 -05:00
|
|
|
|
overrideArray = new OverrideArray
|
|
|
|
|
ok overrideArray instanceof OverrideArray
|
|
|
|
|
eq 'yes!', overrideArray.method()
|
2013-03-04 05:11:38 -05:00
|
|
|
|
|
2017-06-14 18:11:53 -04:00
|
|
|
|
|
|
|
|
|
test "#2782: non-alphanumeric-named bound functions", ->
|
|
|
|
|
class A
|
|
|
|
|
'b:c': =>
|
|
|
|
|
'd'
|
|
|
|
|
|
|
|
|
|
eq (new A)['b:c'](), 'd'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test "#2781: overriding bound functions", ->
|
|
|
|
|
class A
|
|
|
|
|
a: ->
|
|
|
|
|
@b()
|
|
|
|
|
b: =>
|
|
|
|
|
1
|
|
|
|
|
|
|
|
|
|
class B extends A
|
|
|
|
|
b: =>
|
|
|
|
|
2
|
|
|
|
|
|
|
|
|
|
b = (new A).b
|
|
|
|
|
eq b(), 1
|
|
|
|
|
|
|
|
|
|
b = (new B).b
|
|
|
|
|
eq b(), 2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test "#2791: bound function with destructured argument", ->
|
|
|
|
|
class Foo
|
|
|
|
|
method: ({a}) => 'Bar'
|
|
|
|
|
|
|
|
|
|
eq (new Foo).method({a: 'Bar'}), 'Bar'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test "#2796: ditto, ditto, ditto", ->
|
|
|
|
|
answer = null
|
|
|
|
|
|
|
|
|
|
outsideMethod = (func) ->
|
|
|
|
|
func.call message: 'wrong!'
|
|
|
|
|
|
|
|
|
|
class Base
|
|
|
|
|
constructor: ->
|
|
|
|
|
@message = 'right!'
|
|
|
|
|
outsideMethod @echo
|
|
|
|
|
|
|
|
|
|
echo: =>
|
|
|
|
|
answer = @message
|
|
|
|
|
|
|
|
|
|
new Base
|
|
|
|
|
eq answer, 'right!'
|
|
|
|
|
|
2013-10-31 18:25:11 -04:00
|
|
|
|
test "#3063: Class bodies cannot contain pure statements", ->
|
2019-12-16 00:16:55 -05:00
|
|
|
|
throwsCompileError """
|
2013-10-31 18:25:11 -04:00
|
|
|
|
class extends S
|
|
|
|
|
return if S.f
|
|
|
|
|
@f: => this
|
|
|
|
|
"""
|
2013-11-12 10:47:43 -05:00
|
|
|
|
|
|
|
|
|
test "#2949: super in static method with reserved name", ->
|
|
|
|
|
class Foo
|
|
|
|
|
@static: -> 'baz'
|
|
|
|
|
|
|
|
|
|
class Bar extends Foo
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
@static: -> super()
|
2013-11-12 10:47:43 -05:00
|
|
|
|
|
|
|
|
|
eq Bar.static(), 'baz'
|
2013-11-12 11:00:20 -05:00
|
|
|
|
|
|
|
|
|
test "#3232: super in static methods (not object-assigned)", ->
|
|
|
|
|
class Foo
|
|
|
|
|
@baz = -> true
|
|
|
|
|
@qux = -> true
|
|
|
|
|
|
|
|
|
|
class Bar extends Foo
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
@baz = -> super()
|
|
|
|
|
Bar.qux = -> super()
|
2013-11-12 11:00:20 -05:00
|
|
|
|
|
|
|
|
|
ok Bar.baz()
|
|
|
|
|
ok Bar.qux()
|
2015-01-11 10:56:08 -05:00
|
|
|
|
|
|
|
|
|
test "#1392 calling `super` in methods defined on namespaced classes", ->
|
|
|
|
|
class Base
|
|
|
|
|
m: -> 5
|
|
|
|
|
n: -> 4
|
|
|
|
|
namespace =
|
|
|
|
|
A: ->
|
|
|
|
|
B: ->
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
class namespace.A extends Base
|
|
|
|
|
m: -> super()
|
2015-01-11 10:56:08 -05:00
|
|
|
|
|
|
|
|
|
eq 5, (new namespace.A).m()
|
|
|
|
|
namespace.B::m = namespace.A::m
|
|
|
|
|
namespace.A::m = null
|
|
|
|
|
eq 5, (new namespace.B).m()
|
|
|
|
|
|
|
|
|
|
class C
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
@a: class extends Base
|
|
|
|
|
m: -> super()
|
2015-01-11 10:56:08 -05:00
|
|
|
|
eq 5, (new C.a).m()
|
|
|
|
|
|
2017-01-19 16:46:42 -05:00
|
|
|
|
|
2017-06-13 02:11:39 -04:00
|
|
|
|
test "#4436 immediately instantiated named class", ->
|
|
|
|
|
ok new class Foo
|
|
|
|
|
|
|
|
|
|
|
2017-01-19 16:46:42 -05:00
|
|
|
|
test "dynamic method names", ->
|
|
|
|
|
class A
|
|
|
|
|
"#{name = 'm'}": -> 1
|
|
|
|
|
eq 1, new A().m()
|
|
|
|
|
|
|
|
|
|
class B extends A
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
"#{name = 'm'}": -> super()
|
2017-01-19 16:46:42 -05:00
|
|
|
|
eq 1, new B().m()
|
|
|
|
|
|
|
|
|
|
getName = -> 'm'
|
|
|
|
|
class C
|
|
|
|
|
"#{name = getName()}": -> 1
|
|
|
|
|
eq 1, new C().m()
|
|
|
|
|
|
|
|
|
|
|
2015-01-11 10:56:08 -05:00
|
|
|
|
test "dynamic method names and super", ->
|
|
|
|
|
class Base
|
|
|
|
|
@m: -> 6
|
|
|
|
|
m: -> 5
|
Fix #3597: Allow interpolations in object keys
The following is now allowed:
o =
a: 1
b: 2
"#{'c'}": 3
"#{'d'}": 4
e: 5
"#{'f'}": 6
g: 7
It compiles to:
o = (
obj = {
a: 1,
b: 2
},
obj["" + 'c'] = 3,
obj["" + 'd'] = 4,
obj.e = 5,
obj["" + 'f'] = 6,
obj.g = 7,
obj
);
- Closes #3039. Empty interpolations in object keys are now _supposed_ to be
allowed.
- Closes #1131. No need to improve error messages for attempted key
interpolation anymore.
- Implementing this required fixing the following bug: `("" + a): 1` used to
error out on the colon, saying "unexpected colon". But really, it is the
attempted object key that is unexpected. Now the error is on the opening
parenthesis instead.
- However, the above fix broke some error message tests for regexes. The easiest
way to fix this was to make a seemingly unrelated change: The error messages
for unexpected identifiers, numbers, strings and regexes now say for example
'unexpected string' instead of 'unexpected """some #{really long} string"""'.
In other words, the tag _name_ is used instead of the tag _value_.
This was way easier to implement, and is more helpful to the user. Using the
tag value is good for operators, reserved words and the like, but not for
tokens which can contain any text. For example, 'unexpected identifier' is
better than 'unexpected expected' (if a variable called 'expected' was used
erraneously).
- While writing tests for the above point I found a few minor bugs with string
locations which have been fixed.
2015-02-07 14:16:59 -05:00
|
|
|
|
m2: -> 4.5
|
2015-01-11 10:56:08 -05:00
|
|
|
|
n: -> 4
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
|
|
|
|
|
name = -> count++; 'n'
|
|
|
|
|
count = 0
|
2015-01-11 10:56:08 -05:00
|
|
|
|
|
|
|
|
|
m = 'm'
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
class A extends Base
|
|
|
|
|
"#{m}": -> super()
|
|
|
|
|
"#{name()}": -> super()
|
|
|
|
|
|
2015-01-11 10:56:08 -05:00
|
|
|
|
m = 'n'
|
|
|
|
|
eq 5, (new A).m()
|
|
|
|
|
|
|
|
|
|
eq 4, (new A).n()
|
|
|
|
|
eq 1, count
|
|
|
|
|
|
|
|
|
|
m = 'm'
|
Fix #3597: Allow interpolations in object keys
The following is now allowed:
o =
a: 1
b: 2
"#{'c'}": 3
"#{'d'}": 4
e: 5
"#{'f'}": 6
g: 7
It compiles to:
o = (
obj = {
a: 1,
b: 2
},
obj["" + 'c'] = 3,
obj["" + 'd'] = 4,
obj.e = 5,
obj["" + 'f'] = 6,
obj.g = 7,
obj
);
- Closes #3039. Empty interpolations in object keys are now _supposed_ to be
allowed.
- Closes #1131. No need to improve error messages for attempted key
interpolation anymore.
- Implementing this required fixing the following bug: `("" + a): 1` used to
error out on the colon, saying "unexpected colon". But really, it is the
attempted object key that is unexpected. Now the error is on the opening
parenthesis instead.
- However, the above fix broke some error message tests for regexes. The easiest
way to fix this was to make a seemingly unrelated change: The error messages
for unexpected identifiers, numbers, strings and regexes now say for example
'unexpected string' instead of 'unexpected """some #{really long} string"""'.
In other words, the tag _name_ is used instead of the tag _value_.
This was way easier to implement, and is more helpful to the user. Using the
tag value is good for operators, reserved words and the like, but not for
tokens which can contain any text. For example, 'unexpected identifier' is
better than 'unexpected expected' (if a variable called 'expected' was used
erraneously).
- While writing tests for the above point I found a few minor bugs with string
locations which have been fixed.
2015-02-07 14:16:59 -05:00
|
|
|
|
m2 = 'm2'
|
2015-01-11 10:56:08 -05:00
|
|
|
|
count = 0
|
|
|
|
|
class B extends Base
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
@[name()] = -> super()
|
|
|
|
|
"#{m}": -> super()
|
|
|
|
|
"#{m2}": -> super()
|
2015-01-11 10:56:08 -05:00
|
|
|
|
b = new B
|
Fix #3597: Allow interpolations in object keys
The following is now allowed:
o =
a: 1
b: 2
"#{'c'}": 3
"#{'d'}": 4
e: 5
"#{'f'}": 6
g: 7
It compiles to:
o = (
obj = {
a: 1,
b: 2
},
obj["" + 'c'] = 3,
obj["" + 'd'] = 4,
obj.e = 5,
obj["" + 'f'] = 6,
obj.g = 7,
obj
);
- Closes #3039. Empty interpolations in object keys are now _supposed_ to be
allowed.
- Closes #1131. No need to improve error messages for attempted key
interpolation anymore.
- Implementing this required fixing the following bug: `("" + a): 1` used to
error out on the colon, saying "unexpected colon". But really, it is the
attempted object key that is unexpected. Now the error is on the opening
parenthesis instead.
- However, the above fix broke some error message tests for regexes. The easiest
way to fix this was to make a seemingly unrelated change: The error messages
for unexpected identifiers, numbers, strings and regexes now say for example
'unexpected string' instead of 'unexpected """some #{really long} string"""'.
In other words, the tag _name_ is used instead of the tag _value_.
This was way easier to implement, and is more helpful to the user. Using the
tag value is good for operators, reserved words and the like, but not for
tokens which can contain any text. For example, 'unexpected identifier' is
better than 'unexpected expected' (if a variable called 'expected' was used
erraneously).
- While writing tests for the above point I found a few minor bugs with string
locations which have been fixed.
2015-02-07 14:16:59 -05:00
|
|
|
|
m = m2 = 'n'
|
2015-01-11 10:56:08 -05:00
|
|
|
|
eq 6, B.m()
|
|
|
|
|
eq 5, b.m()
|
Fix #3597: Allow interpolations in object keys
The following is now allowed:
o =
a: 1
b: 2
"#{'c'}": 3
"#{'d'}": 4
e: 5
"#{'f'}": 6
g: 7
It compiles to:
o = (
obj = {
a: 1,
b: 2
},
obj["" + 'c'] = 3,
obj["" + 'd'] = 4,
obj.e = 5,
obj["" + 'f'] = 6,
obj.g = 7,
obj
);
- Closes #3039. Empty interpolations in object keys are now _supposed_ to be
allowed.
- Closes #1131. No need to improve error messages for attempted key
interpolation anymore.
- Implementing this required fixing the following bug: `("" + a): 1` used to
error out on the colon, saying "unexpected colon". But really, it is the
attempted object key that is unexpected. Now the error is on the opening
parenthesis instead.
- However, the above fix broke some error message tests for regexes. The easiest
way to fix this was to make a seemingly unrelated change: The error messages
for unexpected identifiers, numbers, strings and regexes now say for example
'unexpected string' instead of 'unexpected """some #{really long} string"""'.
In other words, the tag _name_ is used instead of the tag _value_.
This was way easier to implement, and is more helpful to the user. Using the
tag value is good for operators, reserved words and the like, but not for
tokens which can contain any text. For example, 'unexpected identifier' is
better than 'unexpected expected' (if a variable called 'expected' was used
erraneously).
- While writing tests for the above point I found a few minor bugs with string
locations which have been fixed.
2015-02-07 14:16:59 -05:00
|
|
|
|
eq 4.5, b.m2()
|
2015-01-11 10:56:08 -05:00
|
|
|
|
eq 1, count
|
|
|
|
|
|
|
|
|
|
class C extends B
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
m: -> super()
|
2015-01-11 10:56:08 -05:00
|
|
|
|
eq 5, (new C).m()
|
[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 00:55:30 -05:00
|
|
|
|
|
|
|
|
|
# ES2015+ class interoperability
|
|
|
|
|
# Based on https://github.com/balupton/es6-javascript-class-interop
|
|
|
|
|
# Helper functions to generate true ES classes to extend:
|
|
|
|
|
getBasicClass = ->
|
|
|
|
|
```
|
|
|
|
|
class BasicClass {
|
|
|
|
|
constructor (greeting) {
|
|
|
|
|
this.greeting = greeting || 'hi'
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
BasicClass
|
|
|
|
|
|
|
|
|
|
getExtendedClass = (BaseClass) ->
|
|
|
|
|
```
|
|
|
|
|
class ExtendedClass extends BaseClass {
|
|
|
|
|
constructor (greeting, name) {
|
|
|
|
|
super(greeting || 'hello')
|
|
|
|
|
this.name = name
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
ExtendedClass
|
|
|
|
|
|
|
|
|
|
test "can instantiate a basic ES class", ->
|
|
|
|
|
BasicClass = getBasicClass()
|
|
|
|
|
i = new BasicClass 'howdy!'
|
|
|
|
|
eq i.greeting, 'howdy!'
|
|
|
|
|
|
|
|
|
|
test "can instantiate an extended ES class", ->
|
|
|
|
|
BasicClass = getBasicClass()
|
|
|
|
|
ExtendedClass = getExtendedClass BasicClass
|
|
|
|
|
i = new ExtendedClass 'yo', 'buddy'
|
|
|
|
|
eq i.greeting, 'yo'
|
|
|
|
|
eq i.name, 'buddy'
|
|
|
|
|
|
|
|
|
|
test "can extend a basic ES class", ->
|
|
|
|
|
BasicClass = getBasicClass()
|
|
|
|
|
class ExtendedClass extends BasicClass
|
|
|
|
|
constructor: (@name) ->
|
|
|
|
|
super()
|
|
|
|
|
i = new ExtendedClass 'dude'
|
|
|
|
|
eq i.name, 'dude'
|
|
|
|
|
|
|
|
|
|
test "can extend an extended ES class", ->
|
|
|
|
|
BasicClass = getBasicClass()
|
|
|
|
|
ExtendedClass = getExtendedClass BasicClass
|
|
|
|
|
|
|
|
|
|
class ExtendedExtendedClass extends ExtendedClass
|
|
|
|
|
constructor: (@value) ->
|
|
|
|
|
super()
|
|
|
|
|
getDoubledValue: ->
|
|
|
|
|
@value * 2
|
|
|
|
|
|
|
|
|
|
i = new ExtendedExtendedClass 7
|
|
|
|
|
eq i.getDoubledValue(), 14
|
|
|
|
|
|
|
|
|
|
test "CoffeeScript class can be extended in ES", ->
|
|
|
|
|
class CoffeeClass
|
|
|
|
|
constructor: (@favoriteDrink = 'latte', @size = 'grande') ->
|
|
|
|
|
getDrinkOrder: ->
|
|
|
|
|
"#{@size} #{@favoriteDrink}"
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
class ECMAScriptClass extends CoffeeClass {
|
|
|
|
|
constructor (favoriteDrink) {
|
|
|
|
|
super(favoriteDrink);
|
|
|
|
|
this.favoriteDrink = this.favoriteDrink + ' with a dash of semicolons';
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
e = new ECMAScriptClass 'coffee'
|
|
|
|
|
eq e.getDrinkOrder(), 'grande coffee with a dash of semicolons'
|
|
|
|
|
|
|
|
|
|
test "extended CoffeeScript class can be extended in ES", ->
|
|
|
|
|
class CoffeeClass
|
|
|
|
|
constructor: (@favoriteDrink = 'latte') ->
|
|
|
|
|
|
|
|
|
|
class CoffeeClassWithDrinkOrder extends CoffeeClass
|
|
|
|
|
constructor: (@favoriteDrink, @size = 'grande') ->
|
|
|
|
|
super()
|
|
|
|
|
getDrinkOrder: ->
|
|
|
|
|
"#{@size} #{@favoriteDrink}"
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
class ECMAScriptClass extends CoffeeClassWithDrinkOrder {
|
|
|
|
|
constructor (favoriteDrink) {
|
|
|
|
|
super(favoriteDrink);
|
|
|
|
|
this.favoriteDrink = this.favoriteDrink + ' with a dash of semicolons';
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
e = new ECMAScriptClass 'coffee'
|
|
|
|
|
eq e.getDrinkOrder(), 'grande coffee with a dash of semicolons'
|
|
|
|
|
|
|
|
|
|
test "`this` access after `super` in extended classes", ->
|
|
|
|
|
class Base
|
|
|
|
|
|
|
|
|
|
class Test extends Base
|
|
|
|
|
constructor: (param, @param) ->
|
|
|
|
|
eq param, nonce
|
|
|
|
|
|
|
|
|
|
result = { super: super(), @param, @method }
|
|
|
|
|
eq result.super, this
|
|
|
|
|
eq result.param, @param
|
|
|
|
|
eq result.method, @method
|
2017-06-14 18:11:53 -04:00
|
|
|
|
ok result.method isnt Test::method
|
|
|
|
|
|
|
|
|
|
method: =>
|
[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 00:55:30 -05:00
|
|
|
|
|
|
|
|
|
nonce = {}
|
|
|
|
|
new Test nonce, {}
|
|
|
|
|
|
|
|
|
|
test "`@`-params and bound methods with multiple `super` paths (blocks)", ->
|
|
|
|
|
nonce = {}
|
|
|
|
|
|
|
|
|
|
class Base
|
|
|
|
|
constructor: (@name) ->
|
|
|
|
|
|
|
|
|
|
class Test extends Base
|
|
|
|
|
constructor: (param, @param) ->
|
|
|
|
|
if param
|
|
|
|
|
super 'param'
|
|
|
|
|
eq @name, 'param'
|
|
|
|
|
else
|
|
|
|
|
super 'not param'
|
|
|
|
|
eq @name, 'not param'
|
|
|
|
|
eq @param, nonce
|
2017-06-14 18:11:53 -04:00
|
|
|
|
ok @method isnt Test::method
|
|
|
|
|
method: =>
|
[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 00:55:30 -05:00
|
|
|
|
new Test true, nonce
|
|
|
|
|
new Test false, nonce
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test "`@`-params and bound methods with multiple `super` paths (expressions)", ->
|
|
|
|
|
nonce = {}
|
|
|
|
|
|
|
|
|
|
class Base
|
|
|
|
|
constructor: (@name) ->
|
|
|
|
|
|
|
|
|
|
class Test extends Base
|
|
|
|
|
constructor: (param, @param) ->
|
|
|
|
|
# Contrived example: force each path into an expression with inline assertions
|
|
|
|
|
if param
|
|
|
|
|
result = (
|
|
|
|
|
eq (super 'param'), @;
|
|
|
|
|
eq @name, 'param';
|
|
|
|
|
eq @param, nonce;
|
2017-06-14 18:11:53 -04:00
|
|
|
|
ok @method isnt Test::method
|
[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 00:55:30 -05:00
|
|
|
|
)
|
|
|
|
|
else
|
|
|
|
|
result = (
|
|
|
|
|
eq (super 'not param'), @;
|
|
|
|
|
eq @name, 'not param';
|
|
|
|
|
eq @param, nonce;
|
2017-06-14 18:11:53 -04:00
|
|
|
|
ok @method isnt Test::method
|
[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 00:55:30 -05:00
|
|
|
|
)
|
2017-06-14 18:11:53 -04:00
|
|
|
|
method: =>
|
[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 00:55:30 -05:00
|
|
|
|
new Test true, nonce
|
|
|
|
|
new Test false, nonce
|
|
|
|
|
|
|
|
|
|
test "constructor super in arrow functions", ->
|
|
|
|
|
class Test extends (class)
|
|
|
|
|
constructor: (@param) ->
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
do => super()
|
[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 00:55:30 -05:00
|
|
|
|
eq @param, nonce
|
|
|
|
|
|
|
|
|
|
new Test nonce = {}
|
|
|
|
|
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
# TODO Some of these tests use CoffeeScript.compile and CoffeeScript.run when they could use
|
|
|
|
|
# regular test mechanics.
|
|
|
|
|
# TODO Some of these tests might be better placed in `test/error_messages.coffee`.
|
|
|
|
|
# TODO Some of these tests are duplicates.
|
|
|
|
|
|
[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 00:55:30 -05:00
|
|
|
|
# Ensure that we always throw if we experience more than one super()
|
|
|
|
|
# call in a constructor. This ends up being a runtime error.
|
|
|
|
|
# Should be caught at compile time.
|
|
|
|
|
test "multiple super calls", ->
|
|
|
|
|
throwsA = """
|
|
|
|
|
class A
|
|
|
|
|
constructor: (@drink) ->
|
|
|
|
|
make: -> "Making a #{@drink}"
|
|
|
|
|
|
|
|
|
|
class MultiSuper extends A
|
|
|
|
|
constructor: (drink) ->
|
|
|
|
|
super(drink)
|
|
|
|
|
super(drink)
|
|
|
|
|
@newDrink = drink
|
|
|
|
|
new MultiSuper('Late').make()
|
|
|
|
|
"""
|
|
|
|
|
throws -> CoffeeScript.run throwsA, bare: yes
|
|
|
|
|
|
|
|
|
|
# Basic test to ensure we can pass @params in a constuctor and
|
|
|
|
|
# inheritance works correctly
|
|
|
|
|
test "@ params", ->
|
|
|
|
|
class A
|
|
|
|
|
constructor: (@drink, @shots, @flavor) ->
|
|
|
|
|
make: -> "Making a #{@flavor} #{@drink} with #{@shots} shot(s)"
|
|
|
|
|
|
|
|
|
|
a = new A('Machiato', 2, 'chocolate')
|
|
|
|
|
eq a.make(), "Making a chocolate Machiato with 2 shot(s)"
|
|
|
|
|
|
|
|
|
|
class B extends A
|
|
|
|
|
b = new B('Machiato', 2, 'chocolate')
|
|
|
|
|
eq b.make(), "Making a chocolate Machiato with 2 shot(s)"
|
|
|
|
|
|
|
|
|
|
# Ensure we can accept @params with default parameters in a constructor
|
|
|
|
|
test "@ params with defaults in a constructor", ->
|
|
|
|
|
class A
|
|
|
|
|
# Multiple @ params with defaults
|
|
|
|
|
constructor: (@drink = 'Americano', @shots = '1', @flavor = 'caramel') ->
|
|
|
|
|
make: -> "Making a #{@flavor} #{@drink} with #{@shots} shot(s)"
|
|
|
|
|
|
|
|
|
|
a = new A()
|
|
|
|
|
eq a.make(), "Making a caramel Americano with 1 shot(s)"
|
|
|
|
|
|
|
|
|
|
# Ensure we can handle default constructors with class params
|
|
|
|
|
test "@ params with class params", ->
|
|
|
|
|
class Beverage
|
|
|
|
|
drink: 'Americano'
|
|
|
|
|
shots: '1'
|
|
|
|
|
flavor: 'caramel'
|
|
|
|
|
|
|
|
|
|
class A
|
|
|
|
|
# Class creation as a default param with `this`
|
|
|
|
|
constructor: (@drink = new Beverage()) ->
|
|
|
|
|
a = new A()
|
|
|
|
|
eq a.drink.drink, 'Americano'
|
|
|
|
|
|
|
|
|
|
beverage = new Beverage
|
|
|
|
|
class B
|
|
|
|
|
# class costruction with a default external param
|
|
|
|
|
constructor: (@drink = beverage) ->
|
|
|
|
|
|
|
|
|
|
b = new B()
|
|
|
|
|
eq b.drink.drink, 'Americano'
|
|
|
|
|
|
|
|
|
|
class C
|
|
|
|
|
# Default constructor with anonymous empty class
|
|
|
|
|
constructor: (@meta = class) ->
|
|
|
|
|
c = new C()
|
|
|
|
|
ok c.meta instanceof Function
|
|
|
|
|
|
|
|
|
|
test "@ params without super, including errors", ->
|
|
|
|
|
classA = """
|
|
|
|
|
class A
|
|
|
|
|
constructor: (@drink) ->
|
|
|
|
|
make: -> "Making a #{@drink}"
|
|
|
|
|
a = new A('Machiato')
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
throwsB = """
|
|
|
|
|
class B extends A
|
|
|
|
|
#implied super
|
|
|
|
|
constructor: (@drink) ->
|
|
|
|
|
b = new B('Machiato')
|
|
|
|
|
"""
|
2019-12-16 00:16:55 -05:00
|
|
|
|
throwsCompileError classA + throwsB, bare: yes
|
[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 00:55:30 -05:00
|
|
|
|
|
|
|
|
|
test "@ params super race condition", ->
|
|
|
|
|
classA = """
|
|
|
|
|
class A
|
|
|
|
|
constructor: (@drink) ->
|
|
|
|
|
make: -> "Making a #{@drink}"
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
throwsB = """
|
|
|
|
|
class B extends A
|
|
|
|
|
constructor: (@params) ->
|
|
|
|
|
|
|
|
|
|
b = new B('Machiato')
|
|
|
|
|
"""
|
2019-12-16 00:16:55 -05:00
|
|
|
|
throwsCompileError classA + throwsB, bare: yes
|
[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 00:55:30 -05:00
|
|
|
|
|
|
|
|
|
# Race condition with @ and super
|
|
|
|
|
throwsC = """
|
|
|
|
|
class C extends A
|
|
|
|
|
constructor: (@params) ->
|
|
|
|
|
super(@params)
|
|
|
|
|
|
|
|
|
|
c = new C('Machiato')
|
|
|
|
|
"""
|
2019-12-16 00:16:55 -05:00
|
|
|
|
throwsCompileError classA + throwsC, bare: yes
|
[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 00:55:30 -05:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test "@ with super call", ->
|
|
|
|
|
class D
|
|
|
|
|
make: -> "Making a #{@drink}"
|
|
|
|
|
|
|
|
|
|
class E extends D
|
|
|
|
|
constructor: (@drink) ->
|
|
|
|
|
super()
|
|
|
|
|
|
|
|
|
|
e = new E('Machiato')
|
|
|
|
|
eq e.make(), "Making a Machiato"
|
|
|
|
|
|
|
|
|
|
test "@ with splats and super call", ->
|
|
|
|
|
class A
|
|
|
|
|
make: -> "Making a #{@drink}"
|
|
|
|
|
|
|
|
|
|
class B extends A
|
|
|
|
|
constructor: (@drink...) ->
|
|
|
|
|
super()
|
|
|
|
|
|
|
|
|
|
B = new B('Machiato')
|
|
|
|
|
eq B.make(), "Making a Machiato"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test "super and external constructors", ->
|
|
|
|
|
# external constructor with @ param is allowed
|
|
|
|
|
ctorA = (@drink) ->
|
|
|
|
|
class A
|
|
|
|
|
constructor: ctorA
|
|
|
|
|
make: -> "Making a #{@drink}"
|
|
|
|
|
a = new A('Machiato')
|
|
|
|
|
eq a.make(), "Making a Machiato"
|
|
|
|
|
|
|
|
|
|
# External constructor with super
|
|
|
|
|
throwsC = """
|
|
|
|
|
class B
|
|
|
|
|
constructor: (@drink) ->
|
|
|
|
|
make: -> "Making a #{@drink}"
|
|
|
|
|
|
|
|
|
|
ctorC = (drink) ->
|
|
|
|
|
super(drink)
|
|
|
|
|
|
|
|
|
|
class C extends B
|
|
|
|
|
constructor: ctorC
|
|
|
|
|
c = new C('Machiato')
|
|
|
|
|
"""
|
2019-12-16 00:16:55 -05:00
|
|
|
|
throwsCompileError throwsC, bare: yes
|
[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 00:55:30 -05:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test "bound functions without super", ->
|
|
|
|
|
# Bound function with @
|
|
|
|
|
# Throw on compile, since bound
|
|
|
|
|
# constructors are illegal
|
|
|
|
|
throwsA = """
|
|
|
|
|
class A
|
|
|
|
|
constructor: (drink) =>
|
|
|
|
|
@drink = drink
|
|
|
|
|
|
|
|
|
|
"""
|
2019-12-16 00:16:55 -05:00
|
|
|
|
throwsCompileError throwsA, bare: yes
|
[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 00:55:30 -05:00
|
|
|
|
|
|
|
|
|
test "super in a bound function in a constructor", ->
|
|
|
|
|
throwsB = """
|
|
|
|
|
class A
|
|
|
|
|
class B extends A
|
|
|
|
|
constructor: do => super
|
|
|
|
|
"""
|
2019-12-16 00:16:55 -05:00
|
|
|
|
throwsCompileError throwsB, bare: yes
|
[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 00:55:30 -05:00
|
|
|
|
|
|
|
|
|
test "super in a bound function", ->
|
|
|
|
|
class A
|
|
|
|
|
constructor: (@drink) ->
|
|
|
|
|
make: -> "Making a #{@drink}"
|
|
|
|
|
|
|
|
|
|
class B extends A
|
2017-06-14 18:11:53 -04:00
|
|
|
|
make: (@flavor) =>
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
super() + " with #{@flavor}"
|
[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 00:55:30 -05:00
|
|
|
|
|
|
|
|
|
b = new B('Machiato')
|
|
|
|
|
eq b.make('vanilla'), "Making a Machiato with vanilla"
|
|
|
|
|
|
|
|
|
|
# super in a bound function in a bound function
|
|
|
|
|
class C extends A
|
2017-06-14 18:11:53 -04:00
|
|
|
|
make: (@flavor) =>
|
[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 00:55:30 -05:00
|
|
|
|
func = () =>
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
super() + " with #{@flavor}"
|
[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 00:55:30 -05:00
|
|
|
|
func()
|
|
|
|
|
|
|
|
|
|
c = new C('Machiato')
|
|
|
|
|
eq c.make('vanilla'), "Making a Machiato with vanilla"
|
|
|
|
|
|
|
|
|
|
# bound function in a constructor
|
|
|
|
|
class D extends A
|
|
|
|
|
constructor: (drink) ->
|
|
|
|
|
super(drink)
|
|
|
|
|
x = =>
|
|
|
|
|
eq @drink, "Machiato"
|
|
|
|
|
x()
|
|
|
|
|
d = new D('Machiato')
|
|
|
|
|
eq d.make(), "Making a Machiato"
|
|
|
|
|
|
|
|
|
|
# duplicate
|
|
|
|
|
test "super in a try/catch", ->
|
|
|
|
|
classA = """
|
|
|
|
|
class A
|
|
|
|
|
constructor: (param) ->
|
|
|
|
|
throw "" unless param
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
throwsB = """
|
|
|
|
|
class B extends A
|
|
|
|
|
constructor: ->
|
|
|
|
|
try
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
super()
|
[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 00:55:30 -05:00
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
throwsC = """
|
|
|
|
|
ctor = ->
|
|
|
|
|
try
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
super()
|
[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 00:55:30 -05:00
|
|
|
|
|
|
|
|
|
class C extends A
|
|
|
|
|
constructor: ctor
|
|
|
|
|
"""
|
|
|
|
|
throws -> CoffeeScript.run classA + throwsB, bare: yes
|
|
|
|
|
throws -> CoffeeScript.run classA + throwsC, bare: yes
|
|
|
|
|
|
|
|
|
|
test "mixed ES6 and CS6 classes with a four-level inheritance chain", ->
|
|
|
|
|
# Extended test
|
|
|
|
|
# ES2015+ class interoperability
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
class Base {
|
|
|
|
|
constructor (greeting) {
|
|
|
|
|
this.greeting = greeting || 'hi';
|
|
|
|
|
}
|
|
|
|
|
func (string) {
|
|
|
|
|
return 'zero/' + string;
|
|
|
|
|
}
|
|
|
|
|
static staticFunc (string) {
|
|
|
|
|
return 'static/' + string;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
class FirstChild extends Base
|
|
|
|
|
func: (string) ->
|
|
|
|
|
super('one/') + string
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
class SecondChild extends FirstChild {
|
|
|
|
|
func (string) {
|
|
|
|
|
return super.func('two/' + string);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
thirdCtor = ->
|
|
|
|
|
@array = [1, 2, 3]
|
|
|
|
|
|
|
|
|
|
class ThirdChild extends SecondChild
|
|
|
|
|
constructor: ->
|
|
|
|
|
super()
|
|
|
|
|
thirdCtor.call this
|
|
|
|
|
func: (string) ->
|
|
|
|
|
super('three/') + string
|
|
|
|
|
|
|
|
|
|
result = (new ThirdChild).func 'four'
|
|
|
|
|
ok result is 'zero/one/two/three/four'
|
|
|
|
|
ok Base.staticFunc('word') is 'static/word'
|
|
|
|
|
|
|
|
|
|
# exercise extends in a nested class
|
|
|
|
|
test "nested classes with super", ->
|
|
|
|
|
class Outer
|
|
|
|
|
constructor: ->
|
|
|
|
|
@label = 'outer'
|
|
|
|
|
|
|
|
|
|
class @Inner
|
|
|
|
|
constructor: ->
|
|
|
|
|
@label = 'inner'
|
|
|
|
|
|
|
|
|
|
class @ExtendedInner extends @Inner
|
|
|
|
|
constructor: ->
|
|
|
|
|
tmp = super()
|
|
|
|
|
@label = tmp.label + ' extended'
|
|
|
|
|
|
|
|
|
|
@extender: () =>
|
|
|
|
|
class ExtendedSelf extends @
|
|
|
|
|
constructor: ->
|
|
|
|
|
tmp = super()
|
|
|
|
|
@label = tmp.label + ' from this'
|
|
|
|
|
new ExtendedSelf
|
|
|
|
|
|
|
|
|
|
eq (new Outer).label, 'outer'
|
|
|
|
|
eq (new Outer.Inner).label, 'inner'
|
|
|
|
|
eq (new Outer.ExtendedInner).label, 'inner extended'
|
|
|
|
|
eq (Outer.extender()).label, 'outer from this'
|
|
|
|
|
|
|
|
|
|
test "Static methods generate 'static' keywords", ->
|
|
|
|
|
compile = """
|
|
|
|
|
class CheckStatic
|
|
|
|
|
constructor: (@drink) ->
|
|
|
|
|
@className: -> 'CheckStatic'
|
|
|
|
|
|
|
|
|
|
c = new CheckStatic('Machiato')
|
|
|
|
|
"""
|
|
|
|
|
result = CoffeeScript.compile compile, bare: yes
|
|
|
|
|
ok result.match(' static ')
|
|
|
|
|
|
|
|
|
|
test "Static methods in nested classes", ->
|
|
|
|
|
class Outer
|
|
|
|
|
@name: -> 'Outer'
|
|
|
|
|
|
|
|
|
|
class @Inner
|
|
|
|
|
@name: -> 'Inner'
|
|
|
|
|
|
|
|
|
|
eq Outer.name(), 'Outer'
|
|
|
|
|
eq Outer.Inner.name(), 'Inner'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test "mixed constructors with inheritance and ES6 super", ->
|
|
|
|
|
identity = (f) -> f
|
|
|
|
|
|
|
|
|
|
class TopClass
|
|
|
|
|
constructor: (arg) ->
|
|
|
|
|
@prop = 'top-' + arg
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
class SuperClass extends TopClass {
|
|
|
|
|
constructor (arg) {
|
|
|
|
|
identity(super('super-' + arg));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
class SubClass extends SuperClass
|
|
|
|
|
constructor: ->
|
|
|
|
|
identity super 'sub'
|
|
|
|
|
|
|
|
|
|
ok (new SubClass).prop is 'top-super-sub'
|
|
|
|
|
|
|
|
|
|
test "ES6 static class methods can be overriden", ->
|
|
|
|
|
class A
|
|
|
|
|
@name: -> 'A'
|
|
|
|
|
|
|
|
|
|
class B extends A
|
|
|
|
|
@name: -> 'B'
|
|
|
|
|
|
|
|
|
|
eq A.name(), 'A'
|
|
|
|
|
eq B.name(), 'B'
|
|
|
|
|
|
|
|
|
|
# If creating static by direct assignment rather than ES6 static keyword
|
|
|
|
|
test "ES6 Static methods should set `this` to undefined // ES6 ", ->
|
|
|
|
|
class A
|
|
|
|
|
@test: ->
|
|
|
|
|
eq this, undefined
|
|
|
|
|
|
|
|
|
|
# Ensure that our object prototypes work with ES6
|
|
|
|
|
test "ES6 prototypes can be overriden", ->
|
|
|
|
|
class A
|
|
|
|
|
className: 'classA'
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
class B {
|
|
|
|
|
test () {return "B";};
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
b = new B
|
|
|
|
|
a = new A
|
|
|
|
|
eq a.className, 'classA'
|
|
|
|
|
eq b.test(), 'B'
|
|
|
|
|
Object.setPrototypeOf(b, a)
|
|
|
|
|
eq b.className, 'classA'
|
|
|
|
|
# This shouldn't throw,
|
|
|
|
|
# as we only change inheritance not object construction
|
|
|
|
|
# This may be an issue with ES, rather than CS construction?
|
|
|
|
|
#eq b.test(), 'B'
|
|
|
|
|
|
|
|
|
|
class D extends B
|
|
|
|
|
B::test = () -> 'D'
|
|
|
|
|
eq (new D).test(), 'D'
|
|
|
|
|
|
|
|
|
|
# TODO: implement this error check
|
|
|
|
|
# test "ES6 conformance to extending non-classes", ->
|
|
|
|
|
# A = (@title) ->
|
|
|
|
|
# 'Title: ' + @
|
|
|
|
|
|
|
|
|
|
# class B extends A
|
|
|
|
|
# b = new B('caffeinated')
|
|
|
|
|
# eq b.title, 'caffeinated'
|
|
|
|
|
|
|
|
|
|
# # Check inheritance chain
|
|
|
|
|
# A::getTitle = () -> @title
|
|
|
|
|
# eq b.getTitle(), 'caffeinated'
|
|
|
|
|
|
|
|
|
|
# throwsC = """
|
|
|
|
|
# C = {title: 'invalid'}
|
|
|
|
|
# class D extends {}
|
|
|
|
|
# """
|
|
|
|
|
# # This should catch on compile and message should be "class can only extend classes and functions."
|
|
|
|
|
# throws -> CoffeeScript.run throwsC, bare: yes
|
|
|
|
|
|
|
|
|
|
# TODO: Evaluate future compliance with "strict mode";
|
|
|
|
|
# test "Class function environment should be in `strict mode`, ie as if 'use strict' was in use", ->
|
|
|
|
|
# class A
|
|
|
|
|
# # this might be a meaningless test, since these are likely to be runtime errors and different
|
|
|
|
|
# # for every browser. Thoughts?
|
|
|
|
|
# constructor: () ->
|
|
|
|
|
# # Ivalid: prop reassignment
|
|
|
|
|
# @state = {prop: [1], prop: {a: 'a'}}
|
|
|
|
|
# # eval reassignment
|
|
|
|
|
# @badEval = eval;
|
|
|
|
|
|
|
|
|
|
# # Should throw, but doesn't
|
|
|
|
|
# a = new A
|
|
|
|
|
|
|
|
|
|
test "only one method named constructor allowed", ->
|
|
|
|
|
throwsA = """
|
|
|
|
|
class A
|
|
|
|
|
constructor: (@first) ->
|
|
|
|
|
constructor: (@last) ->
|
|
|
|
|
"""
|
2019-12-16 00:16:55 -05:00
|
|
|
|
throwsCompileError throwsA, bare: yes
|
[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 00:55:30 -05:00
|
|
|
|
|
|
|
|
|
test "If the constructor of a child class does not call super,it should return an object.", ->
|
|
|
|
|
nonce = {}
|
|
|
|
|
|
|
|
|
|
class A
|
|
|
|
|
class B extends A
|
|
|
|
|
constructor: ->
|
|
|
|
|
return nonce
|
|
|
|
|
|
|
|
|
|
eq nonce, new B
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test "super can only exist in extended classes", ->
|
|
|
|
|
throwsA = """
|
|
|
|
|
class A
|
|
|
|
|
constructor: (@name) ->
|
|
|
|
|
super()
|
|
|
|
|
"""
|
2019-12-16 00:16:55 -05:00
|
|
|
|
throwsCompileError throwsA, bare: yes
|
[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 00:55:30 -05:00
|
|
|
|
|
|
|
|
|
# --- CS1 classes compatability breaks ---
|
|
|
|
|
test "CS6 Class extends a CS1 compiled class", ->
|
|
|
|
|
```
|
|
|
|
|
// Generated by CoffeeScript 1.11.1
|
|
|
|
|
var BaseCS1, ExtendedCS1,
|
|
|
|
|
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
|
|
|
|
|
hasProp = {}.hasOwnProperty;
|
|
|
|
|
|
|
|
|
|
BaseCS1 = (function() {
|
|
|
|
|
function BaseCS1(drink) {
|
|
|
|
|
this.drink = drink;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
BaseCS1.prototype.make = function() {
|
|
|
|
|
return "making a " + this.drink;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
BaseCS1.className = function() {
|
|
|
|
|
return 'BaseCS1';
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return BaseCS1;
|
|
|
|
|
|
|
|
|
|
})();
|
|
|
|
|
|
|
|
|
|
ExtendedCS1 = (function(superClass) {
|
|
|
|
|
extend(ExtendedCS1, superClass);
|
|
|
|
|
|
|
|
|
|
function ExtendedCS1(flavor) {
|
|
|
|
|
this.flavor = flavor;
|
|
|
|
|
ExtendedCS1.__super__.constructor.call(this, 'cafe ole');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ExtendedCS1.prototype.make = function() {
|
|
|
|
|
return "making a " + this.drink + " with " + this.flavor;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
ExtendedCS1.className = function() {
|
|
|
|
|
return 'ExtendedCS1';
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return ExtendedCS1;
|
|
|
|
|
|
|
|
|
|
})(BaseCS1);
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
class B extends BaseCS1
|
|
|
|
|
eq B.className(), 'BaseCS1'
|
|
|
|
|
b = new B('machiato')
|
|
|
|
|
eq b.make(), "making a machiato"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test "CS6 Class extends an extended CS1 compiled class", ->
|
|
|
|
|
```
|
|
|
|
|
// Generated by CoffeeScript 1.11.1
|
|
|
|
|
var BaseCS1, ExtendedCS1,
|
|
|
|
|
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
|
|
|
|
|
hasProp = {}.hasOwnProperty;
|
|
|
|
|
|
|
|
|
|
BaseCS1 = (function() {
|
|
|
|
|
function BaseCS1(drink) {
|
|
|
|
|
this.drink = drink;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
BaseCS1.prototype.make = function() {
|
|
|
|
|
return "making a " + this.drink;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
BaseCS1.className = function() {
|
|
|
|
|
return 'BaseCS1';
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return BaseCS1;
|
|
|
|
|
|
|
|
|
|
})();
|
|
|
|
|
|
|
|
|
|
ExtendedCS1 = (function(superClass) {
|
|
|
|
|
extend(ExtendedCS1, superClass);
|
|
|
|
|
|
|
|
|
|
function ExtendedCS1(flavor) {
|
|
|
|
|
this.flavor = flavor;
|
|
|
|
|
ExtendedCS1.__super__.constructor.call(this, 'cafe ole');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ExtendedCS1.prototype.make = function() {
|
|
|
|
|
return "making a " + this.drink + " with " + this.flavor;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
ExtendedCS1.className = function() {
|
|
|
|
|
return 'ExtendedCS1';
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return ExtendedCS1;
|
|
|
|
|
|
|
|
|
|
})(BaseCS1);
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
class B extends ExtendedCS1
|
|
|
|
|
eq B.className(), 'ExtendedCS1'
|
|
|
|
|
b = new B('vanilla')
|
|
|
|
|
eq b.make(), "making a cafe ole with vanilla"
|
|
|
|
|
|
|
|
|
|
test "CS6 Class extends a CS1 compiled class with super()", ->
|
|
|
|
|
```
|
|
|
|
|
// Generated by CoffeeScript 1.11.1
|
|
|
|
|
var BaseCS1, ExtendedCS1,
|
|
|
|
|
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
|
|
|
|
|
hasProp = {}.hasOwnProperty;
|
|
|
|
|
|
|
|
|
|
BaseCS1 = (function() {
|
|
|
|
|
function BaseCS1(drink) {
|
|
|
|
|
this.drink = drink;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
BaseCS1.prototype.make = function() {
|
|
|
|
|
return "making a " + this.drink;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
BaseCS1.className = function() {
|
|
|
|
|
return 'BaseCS1';
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return BaseCS1;
|
|
|
|
|
|
|
|
|
|
})();
|
|
|
|
|
|
|
|
|
|
ExtendedCS1 = (function(superClass) {
|
|
|
|
|
extend(ExtendedCS1, superClass);
|
|
|
|
|
|
|
|
|
|
function ExtendedCS1(flavor) {
|
|
|
|
|
this.flavor = flavor;
|
|
|
|
|
ExtendedCS1.__super__.constructor.call(this, 'cafe ole');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ExtendedCS1.prototype.make = function() {
|
|
|
|
|
return "making a " + this.drink + " with " + this.flavor;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
ExtendedCS1.className = function() {
|
|
|
|
|
return 'ExtendedCS1';
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return ExtendedCS1;
|
|
|
|
|
|
|
|
|
|
})(BaseCS1);
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
class B extends ExtendedCS1
|
|
|
|
|
constructor: (@shots) ->
|
|
|
|
|
super('caramel')
|
|
|
|
|
make: () ->
|
[CS2] Compile all super calls to ES2015 super (#4424)
* Compile all super calls to ES2015 super
This breaks using `super` in non-methods, meaning several tests are
failing. Self-compilation still works.
* Use bound functions for IIFEs containing `super`
`super` can only be called directly in a method, or in an arrow
function.
* Fix handling of `class @A extends A`
This behaviour worked 'for free' when the parent reference was being
cached by the executable class body wrapper. There now needs to be
special handling in place to check if the parent name matches the class
name, and if so to cache the parent reference.
* Fix tests broken by compiling ES2015 `super`
* Disallow bare super
This removes syntax support for 'bare' super calls, e.g.:
class B extends A
constructor: -> super
`super` must now always be followed with arguments like a regular
function call. This also removes the capability of implicitly forwarding
arguments. The above can be equivalently be written as:
class B extends A
constructor: -> super arguments...
* Support super with accessors
`super` with following accessor(s) is now compiled to ES2015
equivalents. In particular, expressions such as `super.name`,
`super[name]`, and also `super.name.prop` are all now valid, and can be
used as expected as calls (i.e. `super.name()`) or in expressions (i.e.
`if super.name? ...`).
`super` without accessors is compiled to a constructor super call in a
constructor, and otherwise, as before, to a super call to the method of
the same name, i.e.
speak: -> super()
...is equivalent to
speak: -> super.speak()
A neat side-effect of the changes is that existential calls now work
properly with super, meaning `super?()` will only call if the super
property exists (and is a function). This is not valid for super in
constructors.
* Prevent calling `super` methods with `new`
This fixes a bug in the previous super handling whereby using the `new`
operator with a `super` call would silently drop the `new`. This is now
an explicit compiler error, as it is invalid JS at runtime.
* Clean up some old super handling code
This was mostly code for tracking the source classes and variables for
methods, which were needed to build the old lookups on `__super__`.
* Add TODO to improve bare super parse error
* Add some TODOs to improve some of the class tests
2017-02-04 15:03:17 -05:00
|
|
|
|
super() + " and #{@shots} shots of espresso"
|
[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 00:55:30 -05:00
|
|
|
|
|
|
|
|
|
eq B.className(), 'ExtendedCS1'
|
|
|
|
|
b = new B('three')
|
|
|
|
|
eq b.make(), "making a cafe ole with caramel and three shots of espresso"
|
2017-06-14 18:11:53 -04:00
|
|
|
|
|
|
|
|
|
test 'Bound method called normally before binding is ok', ->
|
|
|
|
|
class Base
|
|
|
|
|
constructor: ->
|
|
|
|
|
@setProp()
|
|
|
|
|
eq @derivedBound(), 3
|
|
|
|
|
|
|
|
|
|
class Derived extends Base
|
|
|
|
|
setProp: ->
|
|
|
|
|
@prop = 3
|
|
|
|
|
|
|
|
|
|
derivedBound: =>
|
|
|
|
|
@prop
|
|
|
|
|
|
|
|
|
|
d = new Derived
|
|
|
|
|
|
|
|
|
|
test 'Bound method called as callback after super() is ok', ->
|
|
|
|
|
class Base
|
|
|
|
|
|
|
|
|
|
class Derived extends Base
|
|
|
|
|
constructor: (@prop = 3) ->
|
|
|
|
|
super()
|
|
|
|
|
f = @derivedBound
|
|
|
|
|
eq f(), 3
|
|
|
|
|
|
|
|
|
|
derivedBound: =>
|
|
|
|
|
@prop
|
|
|
|
|
|
|
|
|
|
d = new Derived
|
|
|
|
|
{derivedBound} = d
|
|
|
|
|
eq derivedBound(), 3
|
|
|
|
|
|
|
|
|
|
test 'Bound method of base class called as callback is ok', ->
|
|
|
|
|
class Base
|
|
|
|
|
constructor: (@prop = 3) ->
|
|
|
|
|
f = @baseBound
|
|
|
|
|
eq f(), 3
|
|
|
|
|
|
|
|
|
|
baseBound: =>
|
|
|
|
|
@prop
|
|
|
|
|
|
|
|
|
|
b = new Base
|
|
|
|
|
{baseBound} = b
|
|
|
|
|
eq baseBound(), 3
|
|
|
|
|
|
|
|
|
|
test 'Bound method of prop-named class called as callback is ok', ->
|
|
|
|
|
Hive = {}
|
|
|
|
|
class Hive.Bee
|
|
|
|
|
constructor: (@prop = 3) ->
|
|
|
|
|
f = @baseBound
|
|
|
|
|
eq f(), 3
|
|
|
|
|
|
|
|
|
|
baseBound: =>
|
|
|
|
|
@prop
|
|
|
|
|
|
|
|
|
|
b = new Hive.Bee
|
|
|
|
|
{baseBound} = b
|
|
|
|
|
eq baseBound(), 3
|
|
|
|
|
|
|
|
|
|
test 'Bound method of class with expression base class called as callback is ok', ->
|
|
|
|
|
calledB = no
|
|
|
|
|
B = ->
|
|
|
|
|
throw new Error if calledB
|
|
|
|
|
calledB = yes
|
|
|
|
|
class
|
|
|
|
|
class A extends B()
|
|
|
|
|
constructor: (@prop = 3) ->
|
|
|
|
|
super()
|
|
|
|
|
f = @derivedBound
|
|
|
|
|
eq f(), 3
|
|
|
|
|
|
|
|
|
|
derivedBound: =>
|
|
|
|
|
@prop
|
|
|
|
|
|
|
|
|
|
b = new A
|
|
|
|
|
{derivedBound} = b
|
|
|
|
|
eq derivedBound(), 3
|
|
|
|
|
|
|
|
|
|
test 'Bound method of class with expression class name called as callback is ok', ->
|
|
|
|
|
calledF = no
|
|
|
|
|
obj = {}
|
|
|
|
|
B = class
|
|
|
|
|
f = ->
|
|
|
|
|
throw new Error if calledF
|
|
|
|
|
calledF = yes
|
|
|
|
|
obj
|
|
|
|
|
class f().A extends B
|
|
|
|
|
constructor: (@prop = 3) ->
|
|
|
|
|
super()
|
|
|
|
|
g = @derivedBound
|
|
|
|
|
eq g(), 3
|
|
|
|
|
|
|
|
|
|
derivedBound: =>
|
|
|
|
|
@prop
|
|
|
|
|
|
|
|
|
|
a = new obj.A
|
|
|
|
|
{derivedBound} = a
|
|
|
|
|
eq derivedBound(), 3
|
|
|
|
|
|
|
|
|
|
test 'Bound method of anonymous child class called as callback is ok', ->
|
|
|
|
|
f = ->
|
|
|
|
|
B = class
|
|
|
|
|
class extends B
|
|
|
|
|
constructor: (@prop = 3) ->
|
|
|
|
|
super()
|
|
|
|
|
g = @derivedBound
|
|
|
|
|
eq g(), 3
|
|
|
|
|
|
|
|
|
|
derivedBound: =>
|
|
|
|
|
@prop
|
|
|
|
|
|
|
|
|
|
a = new (f())
|
|
|
|
|
{derivedBound} = a
|
|
|
|
|
eq derivedBound(), 3
|
|
|
|
|
|
|
|
|
|
test 'Bound method of immediately instantiated class with expression base class called as callback is ok', ->
|
|
|
|
|
calledF = no
|
|
|
|
|
obj = {}
|
|
|
|
|
B = class
|
|
|
|
|
f = ->
|
|
|
|
|
throw new Error if calledF
|
|
|
|
|
calledF = yes
|
|
|
|
|
obj
|
|
|
|
|
a = new class f().A extends B
|
|
|
|
|
constructor: (@prop = 3) ->
|
|
|
|
|
super()
|
|
|
|
|
g = @derivedBound
|
|
|
|
|
eq g(), 3
|
|
|
|
|
|
|
|
|
|
derivedBound: =>
|
|
|
|
|
@prop
|
|
|
|
|
|
|
|
|
|
{derivedBound} = a
|
|
|
|
|
eq derivedBound(), 3
|
2017-07-13 16:15:18 -04:00
|
|
|
|
|
|
|
|
|
test "#4591: super.x.y, super['x'].y", ->
|
|
|
|
|
class A
|
|
|
|
|
x:
|
|
|
|
|
y: 1
|
|
|
|
|
z: -> 2
|
|
|
|
|
|
|
|
|
|
class B extends A
|
|
|
|
|
constructor: ->
|
|
|
|
|
super()
|
|
|
|
|
|
|
|
|
|
@w = super.x.y
|
|
|
|
|
@v = super['x'].y
|
|
|
|
|
@u = super.x['y']
|
|
|
|
|
@t = super.x.z()
|
|
|
|
|
@s = super['x'].z()
|
|
|
|
|
@r = super.x['z']()
|
|
|
|
|
|
|
|
|
|
b = new B
|
|
|
|
|
eq 1, b.w
|
|
|
|
|
eq 1, b.v
|
|
|
|
|
eq 1, b.u
|
|
|
|
|
eq 2, b.t
|
|
|
|
|
eq 2, b.s
|
|
|
|
|
eq 2, b.r
|
2017-09-20 22:11:05 -04:00
|
|
|
|
|
|
|
|
|
test "#4464: backticked expressions in class body", ->
|
|
|
|
|
class A
|
|
|
|
|
`get x() { return 42; }`
|
|
|
|
|
|
|
|
|
|
class B
|
|
|
|
|
`get x() { return 42; }`
|
|
|
|
|
constructor: ->
|
|
|
|
|
@y = 84
|
|
|
|
|
|
|
|
|
|
a = new A
|
|
|
|
|
eq 42, a.x
|
|
|
|
|
b = new B
|
|
|
|
|
eq 42, b.x
|
|
|
|
|
eq 84, b.y
|
2017-10-07 14:32:43 -04:00
|
|
|
|
|
|
|
|
|
test "#4724: backticked expression in a class body with hoisted member", ->
|
|
|
|
|
class A
|
|
|
|
|
`get x() { return 42; }`
|
|
|
|
|
hoisted: 84
|
|
|
|
|
|
|
|
|
|
a = new A
|
|
|
|
|
eq 42, a.x
|
|
|
|
|
eq 84, a.hoisted
|
2017-12-18 13:51:08 -05:00
|
|
|
|
|
2017-12-28 17:50:12 -05:00
|
|
|
|
test "#4822: nested anonymous classes use non-conflicting variable names", ->
|
|
|
|
|
Class = class
|
|
|
|
|
@a: class
|
|
|
|
|
@b: 1
|
|
|
|
|
|
|
|
|
|
eq Class.a.b, 1
|
|
|
|
|
|
2017-12-18 13:51:08 -05:00
|
|
|
|
test "#4827: executable class body wrappers have correct context", ->
|
|
|
|
|
test = ->
|
|
|
|
|
class @A
|
|
|
|
|
class @B extends @A
|
|
|
|
|
@property = 1
|
|
|
|
|
|
|
|
|
|
o = {}
|
|
|
|
|
test.call o
|
|
|
|
|
ok typeof o.A is typeof o.B is 'function'
|
2018-01-31 00:06:54 -05:00
|
|
|
|
|
|
|
|
|
test "#4868: Incorrect ‘Can’t call super with @params’ error", ->
|
|
|
|
|
class A
|
|
|
|
|
constructor: (@func = ->) ->
|
|
|
|
|
@x = 1
|
|
|
|
|
@func()
|
|
|
|
|
|
|
|
|
|
class B extends A
|
|
|
|
|
constructor: ->
|
|
|
|
|
super -> @x = 2
|
|
|
|
|
|
|
|
|
|
a = new A
|
|
|
|
|
b = new B
|
|
|
|
|
eq 1, a.x
|
|
|
|
|
eq 2, b.x
|
|
|
|
|
|
|
|
|
|
class C
|
|
|
|
|
constructor: (@c = class) -> @c
|
|
|
|
|
|
|
|
|
|
class D extends C
|
|
|
|
|
constructor: ->
|
|
|
|
|
super class then constructor: (@a) -> @a = 3
|
|
|
|
|
|
|
|
|
|
d = new (new D).c
|
2018-09-16 16:52:47 -04:00
|
|
|
|
eq 3, d.a
|
|
|
|
|
|
|
|
|
|
test "#4609: Support new.target", ->
|
|
|
|
|
class A
|
|
|
|
|
constructor: ->
|
|
|
|
|
@calledAs = new.target.name
|
|
|
|
|
|
|
|
|
|
class B extends A
|
|
|
|
|
|
|
|
|
|
b = new B
|
|
|
|
|
eq b.calledAs, 'B'
|
|
|
|
|
|
|
|
|
|
newTarget = null
|
|
|
|
|
Foo = ->
|
|
|
|
|
newTarget = !!new.target
|
|
|
|
|
|
|
|
|
|
Foo()
|
|
|
|
|
eq newTarget, no
|
|
|
|
|
|
|
|
|
|
newTarget = null
|
|
|
|
|
|
|
|
|
|
new Foo()
|
|
|
|
|
eq newTarget, yes
|
2019-02-11 10:28:04 -05:00
|
|
|
|
|
2020-06-03 00:00:40 -04:00
|
|
|
|
test "#5323: new.target can be the argument of a function", ->
|
|
|
|
|
fn = (arg) -> arg
|
|
|
|
|
fn new.target
|
|
|
|
|
|
2019-02-11 10:28:04 -05:00
|
|
|
|
test "#5085: Bug: @ reference to class not maintained in do block", ->
|
|
|
|
|
thisFoo = 'initial foo'
|
|
|
|
|
thisBar = 'initial bar'
|
|
|
|
|
fn = (o) -> o.bar()
|
|
|
|
|
|
|
|
|
|
class A
|
|
|
|
|
@foo = 'foo assigned in class'
|
|
|
|
|
do => thisFoo = @foo
|
|
|
|
|
fn bar: => thisBar = @foo
|
|
|
|
|
|
|
|
|
|
eq thisFoo, 'foo assigned in class'
|
|
|
|
|
eq thisBar, 'foo assigned in class'
|
2019-04-28 18:45:57 -04:00
|
|
|
|
|
|
|
|
|
test "#5204: Computed class property", ->
|
|
|
|
|
foo = 'bar'
|
|
|
|
|
class A
|
|
|
|
|
[foo]: 'baz'
|
|
|
|
|
a = new A()
|
|
|
|
|
eq a.bar, 'baz'
|
|
|
|
|
eq A::bar, 'baz'
|
|
|
|
|
|
|
|
|
|
test "#5204: Static computed class property", ->
|
|
|
|
|
foo = 'bar'
|
|
|
|
|
qux = 'quux'
|
|
|
|
|
class A
|
|
|
|
|
@[foo]: 'baz'
|
|
|
|
|
@[qux]: -> 3
|
|
|
|
|
eq A.bar, 'baz'
|
|
|
|
|
eq A.quux(), 3
|