2.0.0-beta3 (#4594)
* Don’t confuse the syntax highlighter
* Comment Assign::compilePatternMatch a bit
* Assignment expressions in conditionals are a bad practice
* Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[`
* Correct comment
* object destructuring
* Allow custom position of the rest element.
* Output simple array destructuring assignments to ES2015
* Output simple object destructured assignments to ES2015
* Compile shorthand object properties to ES2015 shorthand properties
This dramatically improves the appearance of destructured imports.
* Don’t confuse the syntax highlighter
* Comment Assign::compilePatternMatch a bit
* Assignment expressions in conditionals are a bad practice
* Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[`
* object destructuring
* Allow custom position of the rest element.
* rest element in object destructuring
* rest element in object destructuring
* fix string interpolation
* merging
* fixing splats in object literal
* Rest element in parameter destructuring
* merging with CS2
* merged with CS2
* Add support for the object spread initializer. https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md
* Fix misspellings, trailing whitespace, other minor details
* merging with beta2
* refactor object spread properties
* small fix
* - Fixed object spread function parameters.
- Clean up "Assign" and moved all logic for object rest properties in single method (compileObjectDestruct).
- Add helper function "objectWithoutKeys" to the "UTILITIES" for use with object rest properties,
e.g. {a, b, r...} = obj => {a, b} = obj, r = objectWithoutKeys(...)
- Clean up "Obj" and moved all logic for object spread properties in single method (compileSpread).
- Clean up "Code".
- Add method "hasSplat" to "Obj" and "Value" for checking if Obj contains the splat.
- Enable placing spread syntax triple dots on either right or left, per #85 (https://github.com/coffeescript6/discuss/issues/85)
* Fixed typos
* Remove unused code
* Removed dots (e.g. splat) on the left side from the grammar
* Initial release for deep spread properties, e.g. obj2 = {obj.b..., a: 1} or {obj[b][c]..., d: 7}
Tests need to be prepared!
* 1. Object literal spread properties
Object literals:
- obj = { {b:{c:{d:1}}}..., a:1 }
Parenthetical:
- obj = { ( body ), a:1 }
- obj = { ( body )..., a:1 }
Invocation:
- obj = { ( (args) -> ... )(params), a:1 }
- obj = { ( (args) -> ... )(params)..., a:1 }
- obj = { foo(), a:1 }
- obj = { foo()..., a:1 }
2. Refactor, cleanup & other optimizations.
* Merged with 2.0
* Cleanup
* Some more cleanup.
* Fixed error with freeVariable and object destructuring.
* Fixed errors with object spread properties.
* Improvements, fixed errors.
* Minor improvement.
* Minor improvements.
* Typo.
* Remove unnecessary whitespace.
* Remove unnecessary whitespace.
* Changed few "assertErrorFormat" tests since parentheses are now allowed in the Obj.
* Whitespace cleanup
* Comments cleanup
* fix destructured obj param declarations
* refine fix; add test
* Refactor function args ({a, b...})
* Additional tests for object destructuring in function argument.
* Minor improvement for object destructuring variable declaration.
* refactor function args ({a, b...}) and ({a, b...} = {}); Obj And Param cleanup
* fix comment
* Fix object destructuring variable declaration.
* more tests with default values
* fix typo
* Fixed default values in object destructuring.
* small fix
* Babel’s tests for object rest spread
* Style: spaces after colons in object declarations
* Cleanup comments
* Simplify Babel tests
* Fix comments
* Fix destructuring with splats in multiple objects
* Add test for default values in detsructuring assignment with splats
* Handle default values when assigning to object splats
* Rewrite traverseRest to fix handling of dynamic keys
* Fix double parens around destructuring with splats
* Update compileObjectDestruct comments
* Improve formatting of top-level destructures with splats and tidy parens
* Added a bigger destructuring-with-defaults test and fixed a bug
* Refactor destructuring grammar to allow additional forms
* Add a missing case to ObjSpreadExpr
* These tests shouldn’t run in the browser
* Fix test.html
* Fix docs scroll position getting screwed up by CodeMirror initialization
* Breaking change documentation about => (fixes #4593)
* Spread/rest syntax documentation
* Documentation about bound class methods
* 2.0.0-beta3 changelog
* Add note about ‘lib’
* Fix accidentally converting this to tabs
* Bump version to 2.0.0-beta3
* Update annotated source and test.html
2017-06-30 12:58:05 -04:00
|
|
|
// Generated by CoffeeScript 2.0.0-beta3
|
2010-07-24 11:31:43 -04:00
|
|
|
(function() {
|
2017-07-19 19:25:06 -04:00
|
|
|
var LONG_FLAG, MULTI_FLAG, OPTIONAL, OptionParser, SHORT_FLAG, buildRule, buildRules, normalizeArguments, repeat,
|
|
|
|
slice = [].slice;
|
2013-04-27 18:56:44 -04:00
|
|
|
|
2017-04-06 13:06:45 -04:00
|
|
|
({repeat} = require('./helpers'));
|
2011-09-18 18:16:39 -04: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
|
|
|
exports.OptionParser = OptionParser = class OptionParser {
|
2017-07-19 19:25:06 -04:00
|
|
|
constructor(ruleDeclarations, banner) {
|
2015-01-30 14:33:03 -05:00
|
|
|
this.banner = banner;
|
2017-07-19 19:25:06 -04:00
|
|
|
this.rules = buildRules(ruleDeclarations);
|
2010-11-11 21:48:08 -05:00
|
|
|
}
|
2011-09-18 18:16:39 -04: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
|
|
|
parse(args) {
|
2017-07-19 19:25:06 -04:00
|
|
|
var argument, hasArgument, i, isList, len, name, options, positional, rules;
|
|
|
|
({rules, positional} = normalizeArguments(args, this.rules.flagDict));
|
|
|
|
options = {};
|
|
|
|
for (i = 0, len = rules.length; i < len; i++) {
|
|
|
|
({hasArgument, argument, isList, name} = rules[i]);
|
|
|
|
if (hasArgument) {
|
|
|
|
if (isList) {
|
|
|
|
if (options[name] == null) {
|
|
|
|
options[name] = [];
|
2012-01-25 19:47:03 -05:00
|
|
|
}
|
2017-07-19 19:25:06 -04:00
|
|
|
options[name].push(argument);
|
|
|
|
} else {
|
|
|
|
options[name] = argument;
|
2012-01-25 19:47:03 -05:00
|
|
|
}
|
2017-07-19 19:25:06 -04:00
|
|
|
} else {
|
|
|
|
options[name] = true;
|
2012-04-10 14:57:45 -04:00
|
|
|
}
|
2010-02-14 15:16:33 -05:00
|
|
|
}
|
2017-07-19 19:25:06 -04:00
|
|
|
if (positional[0] === '--') {
|
|
|
|
options.doubleDashed = true;
|
|
|
|
positional = positional.slice(1);
|
|
|
|
}
|
|
|
|
options.arguments = positional;
|
2010-02-27 19:46:45 -05:00
|
|
|
return options;
|
[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
|
|
|
}
|
2011-09-18 18:16:39 -04: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
|
|
|
help() {
|
2017-07-19 19:25:06 -04:00
|
|
|
var i, len, letPart, lines, ref, rule, spaces;
|
2011-01-15 11:04:50 -05:00
|
|
|
lines = [];
|
2012-04-10 14:57:45 -04:00
|
|
|
if (this.banner) {
|
2016-11-28 09:05:51 -05:00
|
|
|
lines.unshift(`${this.banner}\n`);
|
2012-04-10 14:57:45 -04:00
|
|
|
}
|
2017-07-19 19:25:06 -04:00
|
|
|
ref = this.rules.ruleList;
|
|
|
|
for (i = 0, len = ref.length; i < len; i++) {
|
|
|
|
rule = ref[i];
|
2010-06-12 19:05:13 -04:00
|
|
|
spaces = 15 - rule.longFlag.length;
|
2013-04-27 18:56:44 -04:00
|
|
|
spaces = spaces > 0 ? repeat(' ', spaces) : '';
|
2010-06-12 19:05:13 -04:00
|
|
|
letPart = rule.shortFlag ? rule.shortFlag + ', ' : ' ';
|
2010-08-07 08:02:16 -04:00
|
|
|
lines.push(' ' + letPart + rule.longFlag + spaces + rule.description);
|
2010-02-14 15:16:33 -05:00
|
|
|
}
|
2016-11-28 09:05:51 -05:00
|
|
|
return `\n${lines.join('\n')}\n`;
|
[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
|
|
|
}
|
2011-12-14 10:39:20 -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
|
|
|
};
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2012-01-25 19:47:03 -05:00
|
|
|
LONG_FLAG = /^(--\w[\w\-]*)/;
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2012-01-25 19:47:03 -05:00
|
|
|
SHORT_FLAG = /^(-\w)$/;
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2010-02-25 19:06:08 -05:00
|
|
|
MULTI_FLAG = /^-(\w{2,})/;
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2010-08-07 23:33:35 -04:00
|
|
|
OPTIONAL = /\[(\w+(\*?))\]/;
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2017-07-19 19:25:06 -04:00
|
|
|
buildRules = function(ruleDeclarations) {
|
|
|
|
var flag, flagDict, i, j, len, len1, ref, rule, ruleList, tuple;
|
|
|
|
ruleList = (function() {
|
|
|
|
var i, len, results;
|
|
|
|
results = [];
|
|
|
|
for (i = 0, len = ruleDeclarations.length; i < len; i++) {
|
|
|
|
tuple = ruleDeclarations[i];
|
|
|
|
if (tuple.length < 3) {
|
|
|
|
tuple.unshift(null);
|
|
|
|
}
|
|
|
|
results.push(buildRule(...tuple));
|
|
|
|
}
|
|
|
|
return results;
|
|
|
|
})();
|
|
|
|
flagDict = {};
|
|
|
|
for (i = 0, len = ruleList.length; i < len; i++) {
|
|
|
|
rule = ruleList[i];
|
|
|
|
ref = [rule.shortFlag, rule.longFlag];
|
|
|
|
for (j = 0, len1 = ref.length; j < len1; j++) {
|
|
|
|
flag = ref[j];
|
|
|
|
if (!(flag != null)) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if (flagDict[flag] != null) {
|
|
|
|
throw new Error(`flag ${flag} for switch ${rule.name} was already declared for switch ${flagDict[flag].name}`);
|
|
|
|
}
|
|
|
|
flagDict[flag] = rule;
|
2012-04-10 14:57:45 -04:00
|
|
|
}
|
2010-02-14 15:16:33 -05:00
|
|
|
}
|
2017-07-19 19:25:06 -04:00
|
|
|
return {ruleList, flagDict};
|
2010-02-14 15:16:33 -05:00
|
|
|
};
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2017-07-19 19:25:06 -04:00
|
|
|
buildRule = function(shortFlag, longFlag, description) {
|
2010-02-14 15:16:33 -05:00
|
|
|
var match;
|
2010-06-12 19:05:13 -04:00
|
|
|
match = longFlag.match(OPTIONAL);
|
2017-07-19 19:25:06 -04:00
|
|
|
shortFlag = shortFlag != null ? shortFlag.match(SHORT_FLAG)[1] : void 0;
|
2010-06-12 19:05:13 -04:00
|
|
|
longFlag = longFlag.match(LONG_FLAG)[1];
|
2010-02-14 15:16:33 -05:00
|
|
|
return {
|
2017-07-19 19:25:06 -04:00
|
|
|
name: longFlag.replace(/^--/, ''),
|
2010-06-12 19:05:13 -04:00
|
|
|
shortFlag: shortFlag,
|
|
|
|
longFlag: longFlag,
|
2010-02-14 15:16:33 -05:00
|
|
|
description: description,
|
Add command-line compiler hooks. To invoke, pass a file after -r and listen for any of these events: 'compile', 'success' and 'exception'. Example:
coffee -e -r ./snarl 'Hello!'
Contents of 'snarl.coffee' in the working directory:
http = require 'http'
CoffeeScript.on 'exception', (err) ->
client = http.createClient 9889, 'localhost'
request = client.request 'GET', '/?d={"action":1,"applicationName":"CoffeeScript","title":' + JSON.stringify(err.message) + ',"description":' + JSON.stringify(err.stack) + ',"priority":3}'
request.end()
err.handled = yes
To examine arguments available for each event (for debugging and getting started), use `puts JSON.stringify arguments`.
See http://nodejs.org/api.html#modules-309 and NODE_PATH for more details on how -r looks for files.
2010-08-07 13:24:37 -04:00
|
|
|
hasArgument: !!(match && match[1]),
|
2010-08-07 23:33:35 -04:00
|
|
|
isList: !!(match && match[2])
|
2010-02-14 15:16:33 -05:00
|
|
|
};
|
|
|
|
};
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2017-07-19 19:25:06 -04:00
|
|
|
normalizeArguments = function(args, flagDict) {
|
|
|
|
var arg, argIndex, flag, i, innerOpts, j, k, lastOpt, len, len1, multiFlags, multiOpts, needsArgOpt, positional, ref, rule, rules, singleRule, withArg;
|
|
|
|
rules = [];
|
|
|
|
positional = [];
|
|
|
|
needsArgOpt = null;
|
|
|
|
for (argIndex = i = 0, len = args.length; i < len; argIndex = ++i) {
|
|
|
|
arg = args[argIndex];
|
|
|
|
if (needsArgOpt != null) {
|
|
|
|
withArg = Object.assign({}, needsArgOpt.rule, {
|
|
|
|
argument: arg
|
|
|
|
});
|
|
|
|
rules.push(withArg);
|
|
|
|
needsArgOpt = null;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
multiFlags = (ref = arg.match(MULTI_FLAG)) != null ? ref[1].split('').map(function(flagName) {
|
|
|
|
return `-${flagName}`;
|
|
|
|
}) : void 0;
|
|
|
|
if (multiFlags != null) {
|
|
|
|
multiOpts = multiFlags.map(function(flag) {
|
|
|
|
var rule;
|
|
|
|
rule = flagDict[flag];
|
|
|
|
if (rule == null) {
|
|
|
|
throw new Error(`unrecognized option ${flag} in multi-flag ${arg}`);
|
|
|
|
}
|
|
|
|
return {rule, flag};
|
|
|
|
});
|
|
|
|
innerOpts = 2 <= multiOpts.length ? slice.call(multiOpts, 0, j = multiOpts.length - 1) : (j = 0, []), lastOpt = multiOpts[j++];
|
|
|
|
for (k = 0, len1 = innerOpts.length; k < len1; k++) {
|
|
|
|
({rule, flag} = innerOpts[k]);
|
|
|
|
if (rule.hasArgument) {
|
|
|
|
throw new Error(`cannot use option ${flag} in multi-flag ${arg} except as the last option, because it needs an argument`);
|
|
|
|
}
|
|
|
|
rules.push(rule);
|
|
|
|
}
|
|
|
|
if (lastOpt.rule.hasArgument) {
|
|
|
|
needsArgOpt = lastOpt;
|
|
|
|
} else {
|
|
|
|
rules.push(lastOpt.rule);
|
|
|
|
}
|
|
|
|
} else if ([LONG_FLAG, SHORT_FLAG].some(function(pat) {
|
|
|
|
return arg.match(pat) != null;
|
|
|
|
})) {
|
|
|
|
singleRule = flagDict[arg];
|
|
|
|
if (singleRule == null) {
|
|
|
|
throw new Error(`unrecognized option ${arg}`);
|
|
|
|
}
|
|
|
|
if (singleRule.hasArgument) {
|
|
|
|
needsArgOpt = {
|
|
|
|
rule: singleRule,
|
|
|
|
flag: arg
|
|
|
|
};
|
|
|
|
} else {
|
|
|
|
rules.push(singleRule);
|
2010-02-25 19:06:08 -05:00
|
|
|
}
|
|
|
|
} else {
|
2017-07-19 19:25:06 -04:00
|
|
|
positional = args.slice(argIndex);
|
|
|
|
break;
|
2010-02-25 19:06:08 -05:00
|
|
|
}
|
|
|
|
}
|
2017-07-19 19:25:06 -04:00
|
|
|
if (needsArgOpt != null) {
|
|
|
|
throw new Error(`value required for ${needsArgOpt.flag}, but it was the last argument provided`);
|
|
|
|
}
|
|
|
|
return {rules, positional};
|
2010-02-25 19:06:08 -05:00
|
|
|
};
|
2011-12-14 10:39:20 -05:00
|
|
|
|
2010-09-21 03:53:58 -04:00
|
|
|
}).call(this);
|