2021-10-04 23:43:05 -04:00
|
|
|
// Generated by CoffeeScript 2.6.1
|
2010-07-24 11:31:43 -04:00
|
|
|
(function() {
|
[CS2] Comments (#4572)
* Make `addLocationDataFn` more DRY
* Style fixes
* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data
* Fix style.
* Fix style.
* Label test comments
* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing
* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).
* If a comment follows a class declaration, move the comment inside the class body
* Style
* Improve indentation of multiline comments
* Fix indentation for block comments, at least in the cases covered by the one failing test
* Don’t reverse the order of unshifted comments
* Simplify rewriter’s handling of comments, generalizing the special case
* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through
* Improve comments; fix multiline flag
* Prepare HereComments for processing line comments
* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit
* Updated compiler, now with line comments
* `process` doesn’t exist in the browser, so we should check for its existence first
* Update parser output
* Test that proves #4290 is fixed
* Indent line comments, first pass
* Compiled output with indented line comments
* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline
* Revised output
* Cleanup
* Split “multiline” line comment tokens, shifting them forward or back as appropriate
* Fix comments in module specifiers
* Abstract attaching comments to a node
* Line comments in interpolated strings
* Line comments can’t be multiline anymore
* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)
* Make comments compilation more object-oriented
* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment
* Improve eqJS helper
* Fix #4290 definitively, with improved output for arrays with interspersed block comments
* Add support for line comments output interspersed within arrays
* Fix mistake, don’t lose the variable we’re working on
* Remove redundant replacements
* Check for indentation only from the start of the string
* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces
* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset
* Don’t rely on `fragment.type`, which can break when the compiler is minified
* Updated generated docs and browser compiler
* Output block comments after function arguments
* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output
* Create new FuncGlyph node, to hold comments we want to output near the function parameters
* Block comments between `)` and `->`/`=>` get output between `)` and `{`.
* Fix indentation of comments that are the first line inside a bare mode block
* Updated output
* Full Flow example
* Updated browser compiler
* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`
* Abstract token insertion code
* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node
* Allow `SUPER` tokens to carry comments
* Rescue comments from `Existence` nodes and `If` nodes’ conditions
* Rescue comments after `\` line continuation tokens
* Updated compiled output
* Updated browser compiler
* Output block comments in the same `compileFragments` method as line comments, except for inline block comments
* Comments before splice
* Updated browser compiler
* Track compiledComments as a property of Base, to ensure that it’s not a global variable
* Docs: split up the Usage section
* Docs for type annotations via Flow; updated docs output
* Update regular comments documentation
* Updated browser compiler
* Comments before soak
* Comments before static methods, and probably before `@variable =` (this) assignments generally
* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods
* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call
* Fix missing comments before `if not` (i.e. before a UNARY token)
* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)
* Comments within heregexes
* Updated browser compiler
* Update description to reflect what’s now happening in compileCommentFragments
* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace
* Better future-proof comments tests
* Comments before object destructuring; abstract method for setting comments aside before compilation
* Handle more cases of comments before or after `for` loop declaration lines
* Fix indentation of comments preceding `for` loops
* Fix comment before splat function parameter
* Catch another RegexWithInterpolations comment edge case
* Updated browser compiler
* Change heregex example to one that’s more readable; update output
* Remove a few last references to the defunct HERECOMMENT token
* Abstract location hash creation into a function
* Improved clarity per code review notes
* Updated browser compiler
2017-08-02 22:34:34 -04:00
|
|
|
// The **Scope** class regulates lexical scoping within CoffeeScript. As you
|
|
|
|
// generate code, you create a tree of scopes in the same shape as the nested
|
|
|
|
// function bodies. Each scope knows about the variables declared within it,
|
|
|
|
// and has a reference to its parent enclosing scope. In this way, we know which
|
|
|
|
// variables are new and need to be declared with `var`, and which are shared
|
|
|
|
// with external scopes.
|
2015-02-07 15:50:41 -05:00
|
|
|
var Scope,
|
2017-04-25 10:10:42 -04:00
|
|
|
indexOf = [].indexOf;
|
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.Scope = Scope = class Scope {
|
[CS2] Comments (#4572)
* Make `addLocationDataFn` more DRY
* Style fixes
* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data
* Fix style.
* Fix style.
* Label test comments
* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing
* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).
* If a comment follows a class declaration, move the comment inside the class body
* Style
* Improve indentation of multiline comments
* Fix indentation for block comments, at least in the cases covered by the one failing test
* Don’t reverse the order of unshifted comments
* Simplify rewriter’s handling of comments, generalizing the special case
* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through
* Improve comments; fix multiline flag
* Prepare HereComments for processing line comments
* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit
* Updated compiler, now with line comments
* `process` doesn’t exist in the browser, so we should check for its existence first
* Update parser output
* Test that proves #4290 is fixed
* Indent line comments, first pass
* Compiled output with indented line comments
* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline
* Revised output
* Cleanup
* Split “multiline” line comment tokens, shifting them forward or back as appropriate
* Fix comments in module specifiers
* Abstract attaching comments to a node
* Line comments in interpolated strings
* Line comments can’t be multiline anymore
* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)
* Make comments compilation more object-oriented
* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment
* Improve eqJS helper
* Fix #4290 definitively, with improved output for arrays with interspersed block comments
* Add support for line comments output interspersed within arrays
* Fix mistake, don’t lose the variable we’re working on
* Remove redundant replacements
* Check for indentation only from the start of the string
* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces
* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset
* Don’t rely on `fragment.type`, which can break when the compiler is minified
* Updated generated docs and browser compiler
* Output block comments after function arguments
* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output
* Create new FuncGlyph node, to hold comments we want to output near the function parameters
* Block comments between `)` and `->`/`=>` get output between `)` and `{`.
* Fix indentation of comments that are the first line inside a bare mode block
* Updated output
* Full Flow example
* Updated browser compiler
* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`
* Abstract token insertion code
* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node
* Allow `SUPER` tokens to carry comments
* Rescue comments from `Existence` nodes and `If` nodes’ conditions
* Rescue comments after `\` line continuation tokens
* Updated compiled output
* Updated browser compiler
* Output block comments in the same `compileFragments` method as line comments, except for inline block comments
* Comments before splice
* Updated browser compiler
* Track compiledComments as a property of Base, to ensure that it’s not a global variable
* Docs: split up the Usage section
* Docs for type annotations via Flow; updated docs output
* Update regular comments documentation
* Updated browser compiler
* Comments before soak
* Comments before static methods, and probably before `@variable =` (this) assignments generally
* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods
* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call
* Fix missing comments before `if not` (i.e. before a UNARY token)
* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)
* Comments within heregexes
* Updated browser compiler
* Update description to reflect what’s now happening in compileCommentFragments
* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace
* Better future-proof comments tests
* Comments before object destructuring; abstract method for setting comments aside before compilation
* Handle more cases of comments before or after `for` loop declaration lines
* Fix indentation of comments preceding `for` loops
* Fix comment before splat function parameter
* Catch another RegexWithInterpolations comment edge case
* Updated browser compiler
* Change heregex example to one that’s more readable; update output
* Remove a few last references to the defunct HERECOMMENT token
* Abstract location hash creation into a function
* Improved clarity per code review notes
* Updated browser compiler
2017-08-02 22:34:34 -04:00
|
|
|
// Initialize a scope with its parent, for lookups up the chain,
|
|
|
|
// as well as a reference to the **Block** node it belongs to, which is
|
|
|
|
// where it should declare its variables, a reference to the function that
|
|
|
|
// it belongs to, and a list of variables referenced in the source code
|
2017-10-19 09:56:59 -04:00
|
|
|
// and therefore should be avoided when generating variables. Also track comments
|
|
|
|
// that should be output as part of variable declarations.
|
[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(parent, expressions, method, referencedVars) {
|
2015-02-07 15:50:41 -05:00
|
|
|
var ref, ref1;
|
2015-01-30 14:33:03 -05:00
|
|
|
this.parent = parent;
|
|
|
|
this.expressions = expressions;
|
|
|
|
this.method = method;
|
|
|
|
this.referencedVars = referencedVars;
|
2010-11-11 21:48:08 -05:00
|
|
|
this.variables = [
|
|
|
|
{
|
|
|
|
name: 'arguments',
|
|
|
|
type: 'arguments'
|
2010-10-04 23:21:16 -04:00
|
|
|
}
|
2010-11-11 21:48:08 -05:00
|
|
|
];
|
2017-10-19 09:56:59 -04:00
|
|
|
this.comments = {};
|
2010-11-11 21:48:08 -05:00
|
|
|
this.positions = {};
|
2012-04-10 14:57:45 -04:00
|
|
|
if (!this.parent) {
|
2015-01-11 06:12:40 -05:00
|
|
|
this.utilities = {};
|
2012-04-10 14:57:45 -04:00
|
|
|
}
|
[CS2] Comments (#4572)
* Make `addLocationDataFn` more DRY
* Style fixes
* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data
* Fix style.
* Fix style.
* Label test comments
* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing
* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).
* If a comment follows a class declaration, move the comment inside the class body
* Style
* Improve indentation of multiline comments
* Fix indentation for block comments, at least in the cases covered by the one failing test
* Don’t reverse the order of unshifted comments
* Simplify rewriter’s handling of comments, generalizing the special case
* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through
* Improve comments; fix multiline flag
* Prepare HereComments for processing line comments
* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit
* Updated compiler, now with line comments
* `process` doesn’t exist in the browser, so we should check for its existence first
* Update parser output
* Test that proves #4290 is fixed
* Indent line comments, first pass
* Compiled output with indented line comments
* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline
* Revised output
* Cleanup
* Split “multiline” line comment tokens, shifting them forward or back as appropriate
* Fix comments in module specifiers
* Abstract attaching comments to a node
* Line comments in interpolated strings
* Line comments can’t be multiline anymore
* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)
* Make comments compilation more object-oriented
* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment
* Improve eqJS helper
* Fix #4290 definitively, with improved output for arrays with interspersed block comments
* Add support for line comments output interspersed within arrays
* Fix mistake, don’t lose the variable we’re working on
* Remove redundant replacements
* Check for indentation only from the start of the string
* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces
* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset
* Don’t rely on `fragment.type`, which can break when the compiler is minified
* Updated generated docs and browser compiler
* Output block comments after function arguments
* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output
* Create new FuncGlyph node, to hold comments we want to output near the function parameters
* Block comments between `)` and `->`/`=>` get output between `)` and `{`.
* Fix indentation of comments that are the first line inside a bare mode block
* Updated output
* Full Flow example
* Updated browser compiler
* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`
* Abstract token insertion code
* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node
* Allow `SUPER` tokens to carry comments
* Rescue comments from `Existence` nodes and `If` nodes’ conditions
* Rescue comments after `\` line continuation tokens
* Updated compiled output
* Updated browser compiler
* Output block comments in the same `compileFragments` method as line comments, except for inline block comments
* Comments before splice
* Updated browser compiler
* Track compiledComments as a property of Base, to ensure that it’s not a global variable
* Docs: split up the Usage section
* Docs for type annotations via Flow; updated docs output
* Update regular comments documentation
* Updated browser compiler
* Comments before soak
* Comments before static methods, and probably before `@variable =` (this) assignments generally
* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods
* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call
* Fix missing comments before `if not` (i.e. before a UNARY token)
* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)
* Comments within heregexes
* Updated browser compiler
* Update description to reflect what’s now happening in compileCommentFragments
* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace
* Better future-proof comments tests
* Comments before object destructuring; abstract method for setting comments aside before compilation
* Handle more cases of comments before or after `for` loop declaration lines
* Fix indentation of comments preceding `for` loops
* Fix comment before splat function parameter
* Catch another RegexWithInterpolations comment edge case
* Updated browser compiler
* Change heregex example to one that’s more readable; update output
* Remove a few last references to the defunct HERECOMMENT token
* Abstract location hash creation into a function
* Improved clarity per code review notes
* Updated browser compiler
2017-08-02 22:34:34 -04:00
|
|
|
// The `@root` is the top-level **Scope** object for a given file.
|
2015-02-07 15:50:41 -05:00
|
|
|
this.root = (ref = (ref1 = this.parent) != null ? ref1.root : void 0) != null ? ref : this;
|
2010-11-11 21:48:08 -05:00
|
|
|
}
|
2011-09-18 18:16:39 -04:00
|
|
|
|
[CS2] Comments (#4572)
* Make `addLocationDataFn` more DRY
* Style fixes
* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data
* Fix style.
* Fix style.
* Label test comments
* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing
* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).
* If a comment follows a class declaration, move the comment inside the class body
* Style
* Improve indentation of multiline comments
* Fix indentation for block comments, at least in the cases covered by the one failing test
* Don’t reverse the order of unshifted comments
* Simplify rewriter’s handling of comments, generalizing the special case
* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through
* Improve comments; fix multiline flag
* Prepare HereComments for processing line comments
* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit
* Updated compiler, now with line comments
* `process` doesn’t exist in the browser, so we should check for its existence first
* Update parser output
* Test that proves #4290 is fixed
* Indent line comments, first pass
* Compiled output with indented line comments
* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline
* Revised output
* Cleanup
* Split “multiline” line comment tokens, shifting them forward or back as appropriate
* Fix comments in module specifiers
* Abstract attaching comments to a node
* Line comments in interpolated strings
* Line comments can’t be multiline anymore
* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)
* Make comments compilation more object-oriented
* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment
* Improve eqJS helper
* Fix #4290 definitively, with improved output for arrays with interspersed block comments
* Add support for line comments output interspersed within arrays
* Fix mistake, don’t lose the variable we’re working on
* Remove redundant replacements
* Check for indentation only from the start of the string
* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces
* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset
* Don’t rely on `fragment.type`, which can break when the compiler is minified
* Updated generated docs and browser compiler
* Output block comments after function arguments
* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output
* Create new FuncGlyph node, to hold comments we want to output near the function parameters
* Block comments between `)` and `->`/`=>` get output between `)` and `{`.
* Fix indentation of comments that are the first line inside a bare mode block
* Updated output
* Full Flow example
* Updated browser compiler
* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`
* Abstract token insertion code
* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node
* Allow `SUPER` tokens to carry comments
* Rescue comments from `Existence` nodes and `If` nodes’ conditions
* Rescue comments after `\` line continuation tokens
* Updated compiled output
* Updated browser compiler
* Output block comments in the same `compileFragments` method as line comments, except for inline block comments
* Comments before splice
* Updated browser compiler
* Track compiledComments as a property of Base, to ensure that it’s not a global variable
* Docs: split up the Usage section
* Docs for type annotations via Flow; updated docs output
* Update regular comments documentation
* Updated browser compiler
* Comments before soak
* Comments before static methods, and probably before `@variable =` (this) assignments generally
* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods
* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call
* Fix missing comments before `if not` (i.e. before a UNARY token)
* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)
* Comments within heregexes
* Updated browser compiler
* Update description to reflect what’s now happening in compileCommentFragments
* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace
* Better future-proof comments tests
* Comments before object destructuring; abstract method for setting comments aside before compilation
* Handle more cases of comments before or after `for` loop declaration lines
* Fix indentation of comments preceding `for` loops
* Fix comment before splat function parameter
* Catch another RegexWithInterpolations comment edge case
* Updated browser compiler
* Change heregex example to one that’s more readable; update output
* Remove a few last references to the defunct HERECOMMENT token
* Abstract location hash creation into a function
* Improved clarity per code review notes
* Updated browser compiler
2017-08-02 22:34:34 -04:00
|
|
|
// Adds a new variable or overrides an existing one.
|
[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
|
|
|
add(name, type, immediate) {
|
2012-04-10 14:57:45 -04:00
|
|
|
if (this.shared && !immediate) {
|
|
|
|
return this.parent.add(name, type, immediate);
|
|
|
|
}
|
2011-11-14 11:18:45 -05:00
|
|
|
if (Object.prototype.hasOwnProperty.call(this.positions, name)) {
|
2011-11-10 03:08:38 -05:00
|
|
|
return this.variables[this.positions[name]].type = type;
|
2010-11-08 23:07:51 -05:00
|
|
|
} else {
|
2017-04-06 13:06:45 -04:00
|
|
|
return this.positions[name] = this.variables.push({name, type}) - 1;
|
2010-11-08 23:07:51 -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
|
|
|
|
[CS2] Comments (#4572)
* Make `addLocationDataFn` more DRY
* Style fixes
* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data
* Fix style.
* Fix style.
* Label test comments
* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing
* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).
* If a comment follows a class declaration, move the comment inside the class body
* Style
* Improve indentation of multiline comments
* Fix indentation for block comments, at least in the cases covered by the one failing test
* Don’t reverse the order of unshifted comments
* Simplify rewriter’s handling of comments, generalizing the special case
* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through
* Improve comments; fix multiline flag
* Prepare HereComments for processing line comments
* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit
* Updated compiler, now with line comments
* `process` doesn’t exist in the browser, so we should check for its existence first
* Update parser output
* Test that proves #4290 is fixed
* Indent line comments, first pass
* Compiled output with indented line comments
* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline
* Revised output
* Cleanup
* Split “multiline” line comment tokens, shifting them forward or back as appropriate
* Fix comments in module specifiers
* Abstract attaching comments to a node
* Line comments in interpolated strings
* Line comments can’t be multiline anymore
* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)
* Make comments compilation more object-oriented
* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment
* Improve eqJS helper
* Fix #4290 definitively, with improved output for arrays with interspersed block comments
* Add support for line comments output interspersed within arrays
* Fix mistake, don’t lose the variable we’re working on
* Remove redundant replacements
* Check for indentation only from the start of the string
* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces
* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset
* Don’t rely on `fragment.type`, which can break when the compiler is minified
* Updated generated docs and browser compiler
* Output block comments after function arguments
* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output
* Create new FuncGlyph node, to hold comments we want to output near the function parameters
* Block comments between `)` and `->`/`=>` get output between `)` and `{`.
* Fix indentation of comments that are the first line inside a bare mode block
* Updated output
* Full Flow example
* Updated browser compiler
* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`
* Abstract token insertion code
* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node
* Allow `SUPER` tokens to carry comments
* Rescue comments from `Existence` nodes and `If` nodes’ conditions
* Rescue comments after `\` line continuation tokens
* Updated compiled output
* Updated browser compiler
* Output block comments in the same `compileFragments` method as line comments, except for inline block comments
* Comments before splice
* Updated browser compiler
* Track compiledComments as a property of Base, to ensure that it’s not a global variable
* Docs: split up the Usage section
* Docs for type annotations via Flow; updated docs output
* Update regular comments documentation
* Updated browser compiler
* Comments before soak
* Comments before static methods, and probably before `@variable =` (this) assignments generally
* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods
* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call
* Fix missing comments before `if not` (i.e. before a UNARY token)
* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)
* Comments within heregexes
* Updated browser compiler
* Update description to reflect what’s now happening in compileCommentFragments
* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace
* Better future-proof comments tests
* Comments before object destructuring; abstract method for setting comments aside before compilation
* Handle more cases of comments before or after `for` loop declaration lines
* Fix indentation of comments preceding `for` loops
* Fix comment before splat function parameter
* Catch another RegexWithInterpolations comment edge case
* Updated browser compiler
* Change heregex example to one that’s more readable; update output
* Remove a few last references to the defunct HERECOMMENT token
* Abstract location hash creation into a function
* Improved clarity per code review notes
* Updated browser compiler
2017-08-02 22:34:34 -04:00
|
|
|
// When `super` is called, we need to find the name of the current method we're
|
|
|
|
// in, so that we know how to invoke the same method of the parent class. This
|
|
|
|
// can get complicated if super is being called from an inner function.
|
|
|
|
// `namedMethod` will walk up the scope tree until it either finds the first
|
|
|
|
// function object that has a name filled in, or bottoms out.
|
[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
|
|
|
namedMethod() {
|
2015-02-07 15:50:41 -05:00
|
|
|
var ref;
|
|
|
|
if (((ref = this.method) != null ? ref.name : void 0) || !this.parent) {
|
2012-04-11 19:32:40 -04:00
|
|
|
return this.method;
|
2012-04-11 18:05:33 -04:00
|
|
|
}
|
2012-04-24 17:23:37 -04:00
|
|
|
return this.parent.namedMethod();
|
[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
|
|
|
}
|
2012-04-11 18:05:33 -04:00
|
|
|
|
[CS2] Comments (#4572)
* Make `addLocationDataFn` more DRY
* Style fixes
* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data
* Fix style.
* Fix style.
* Label test comments
* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing
* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).
* If a comment follows a class declaration, move the comment inside the class body
* Style
* Improve indentation of multiline comments
* Fix indentation for block comments, at least in the cases covered by the one failing test
* Don’t reverse the order of unshifted comments
* Simplify rewriter’s handling of comments, generalizing the special case
* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through
* Improve comments; fix multiline flag
* Prepare HereComments for processing line comments
* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit
* Updated compiler, now with line comments
* `process` doesn’t exist in the browser, so we should check for its existence first
* Update parser output
* Test that proves #4290 is fixed
* Indent line comments, first pass
* Compiled output with indented line comments
* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline
* Revised output
* Cleanup
* Split “multiline” line comment tokens, shifting them forward or back as appropriate
* Fix comments in module specifiers
* Abstract attaching comments to a node
* Line comments in interpolated strings
* Line comments can’t be multiline anymore
* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)
* Make comments compilation more object-oriented
* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment
* Improve eqJS helper
* Fix #4290 definitively, with improved output for arrays with interspersed block comments
* Add support for line comments output interspersed within arrays
* Fix mistake, don’t lose the variable we’re working on
* Remove redundant replacements
* Check for indentation only from the start of the string
* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces
* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset
* Don’t rely on `fragment.type`, which can break when the compiler is minified
* Updated generated docs and browser compiler
* Output block comments after function arguments
* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output
* Create new FuncGlyph node, to hold comments we want to output near the function parameters
* Block comments between `)` and `->`/`=>` get output between `)` and `{`.
* Fix indentation of comments that are the first line inside a bare mode block
* Updated output
* Full Flow example
* Updated browser compiler
* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`
* Abstract token insertion code
* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node
* Allow `SUPER` tokens to carry comments
* Rescue comments from `Existence` nodes and `If` nodes’ conditions
* Rescue comments after `\` line continuation tokens
* Updated compiled output
* Updated browser compiler
* Output block comments in the same `compileFragments` method as line comments, except for inline block comments
* Comments before splice
* Updated browser compiler
* Track compiledComments as a property of Base, to ensure that it’s not a global variable
* Docs: split up the Usage section
* Docs for type annotations via Flow; updated docs output
* Update regular comments documentation
* Updated browser compiler
* Comments before soak
* Comments before static methods, and probably before `@variable =` (this) assignments generally
* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods
* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call
* Fix missing comments before `if not` (i.e. before a UNARY token)
* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)
* Comments within heregexes
* Updated browser compiler
* Update description to reflect what’s now happening in compileCommentFragments
* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace
* Better future-proof comments tests
* Comments before object destructuring; abstract method for setting comments aside before compilation
* Handle more cases of comments before or after `for` loop declaration lines
* Fix indentation of comments preceding `for` loops
* Fix comment before splat function parameter
* Catch another RegexWithInterpolations comment edge case
* Updated browser compiler
* Change heregex example to one that’s more readable; update output
* Remove a few last references to the defunct HERECOMMENT token
* Abstract location hash creation into a function
* Improved clarity per code review notes
* Updated browser compiler
2017-08-02 22:34:34 -04:00
|
|
|
// Look up a variable name in lexical scope, and declare it if it does not
|
|
|
|
// already exist.
|
2017-02-04 15:36:49 -05:00
|
|
|
find(name, type = 'var') {
|
2012-04-24 15:37:26 -04:00
|
|
|
if (this.check(name)) {
|
2012-04-10 14:57:45 -04:00
|
|
|
return true;
|
|
|
|
}
|
2017-01-26 10:24:25 -05:00
|
|
|
this.add(name, type);
|
2010-03-30 09:02:51 -04:00
|
|
|
return false;
|
[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] Comments (#4572)
* Make `addLocationDataFn` more DRY
* Style fixes
* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data
* Fix style.
* Fix style.
* Label test comments
* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing
* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).
* If a comment follows a class declaration, move the comment inside the class body
* Style
* Improve indentation of multiline comments
* Fix indentation for block comments, at least in the cases covered by the one failing test
* Don’t reverse the order of unshifted comments
* Simplify rewriter’s handling of comments, generalizing the special case
* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through
* Improve comments; fix multiline flag
* Prepare HereComments for processing line comments
* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit
* Updated compiler, now with line comments
* `process` doesn’t exist in the browser, so we should check for its existence first
* Update parser output
* Test that proves #4290 is fixed
* Indent line comments, first pass
* Compiled output with indented line comments
* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline
* Revised output
* Cleanup
* Split “multiline” line comment tokens, shifting them forward or back as appropriate
* Fix comments in module specifiers
* Abstract attaching comments to a node
* Line comments in interpolated strings
* Line comments can’t be multiline anymore
* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)
* Make comments compilation more object-oriented
* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment
* Improve eqJS helper
* Fix #4290 definitively, with improved output for arrays with interspersed block comments
* Add support for line comments output interspersed within arrays
* Fix mistake, don’t lose the variable we’re working on
* Remove redundant replacements
* Check for indentation only from the start of the string
* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces
* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset
* Don’t rely on `fragment.type`, which can break when the compiler is minified
* Updated generated docs and browser compiler
* Output block comments after function arguments
* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output
* Create new FuncGlyph node, to hold comments we want to output near the function parameters
* Block comments between `)` and `->`/`=>` get output between `)` and `{`.
* Fix indentation of comments that are the first line inside a bare mode block
* Updated output
* Full Flow example
* Updated browser compiler
* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`
* Abstract token insertion code
* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node
* Allow `SUPER` tokens to carry comments
* Rescue comments from `Existence` nodes and `If` nodes’ conditions
* Rescue comments after `\` line continuation tokens
* Updated compiled output
* Updated browser compiler
* Output block comments in the same `compileFragments` method as line comments, except for inline block comments
* Comments before splice
* Updated browser compiler
* Track compiledComments as a property of Base, to ensure that it’s not a global variable
* Docs: split up the Usage section
* Docs for type annotations via Flow; updated docs output
* Update regular comments documentation
* Updated browser compiler
* Comments before soak
* Comments before static methods, and probably before `@variable =` (this) assignments generally
* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods
* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call
* Fix missing comments before `if not` (i.e. before a UNARY token)
* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)
* Comments within heregexes
* Updated browser compiler
* Update description to reflect what’s now happening in compileCommentFragments
* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace
* Better future-proof comments tests
* Comments before object destructuring; abstract method for setting comments aside before compilation
* Handle more cases of comments before or after `for` loop declaration lines
* Fix indentation of comments preceding `for` loops
* Fix comment before splat function parameter
* Catch another RegexWithInterpolations comment edge case
* Updated browser compiler
* Change heregex example to one that’s more readable; update output
* Remove a few last references to the defunct HERECOMMENT token
* Abstract location hash creation into a function
* Improved clarity per code review notes
* Updated browser compiler
2017-08-02 22:34:34 -04:00
|
|
|
// Reserve a variable name as originating from a function parameter for this
|
|
|
|
// scope. No `var` required for internal references.
|
[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
|
|
|
parameter(name) {
|
2012-04-10 14:57:45 -04:00
|
|
|
if (this.shared && this.parent.check(name, true)) {
|
|
|
|
return;
|
|
|
|
}
|
2010-10-20 23:09:06 -04:00
|
|
|
return this.add(name, 'param');
|
[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] Comments (#4572)
* Make `addLocationDataFn` more DRY
* Style fixes
* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data
* Fix style.
* Fix style.
* Label test comments
* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing
* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).
* If a comment follows a class declaration, move the comment inside the class body
* Style
* Improve indentation of multiline comments
* Fix indentation for block comments, at least in the cases covered by the one failing test
* Don’t reverse the order of unshifted comments
* Simplify rewriter’s handling of comments, generalizing the special case
* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through
* Improve comments; fix multiline flag
* Prepare HereComments for processing line comments
* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit
* Updated compiler, now with line comments
* `process` doesn’t exist in the browser, so we should check for its existence first
* Update parser output
* Test that proves #4290 is fixed
* Indent line comments, first pass
* Compiled output with indented line comments
* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline
* Revised output
* Cleanup
* Split “multiline” line comment tokens, shifting them forward or back as appropriate
* Fix comments in module specifiers
* Abstract attaching comments to a node
* Line comments in interpolated strings
* Line comments can’t be multiline anymore
* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)
* Make comments compilation more object-oriented
* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment
* Improve eqJS helper
* Fix #4290 definitively, with improved output for arrays with interspersed block comments
* Add support for line comments output interspersed within arrays
* Fix mistake, don’t lose the variable we’re working on
* Remove redundant replacements
* Check for indentation only from the start of the string
* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces
* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset
* Don’t rely on `fragment.type`, which can break when the compiler is minified
* Updated generated docs and browser compiler
* Output block comments after function arguments
* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output
* Create new FuncGlyph node, to hold comments we want to output near the function parameters
* Block comments between `)` and `->`/`=>` get output between `)` and `{`.
* Fix indentation of comments that are the first line inside a bare mode block
* Updated output
* Full Flow example
* Updated browser compiler
* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`
* Abstract token insertion code
* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node
* Allow `SUPER` tokens to carry comments
* Rescue comments from `Existence` nodes and `If` nodes’ conditions
* Rescue comments after `\` line continuation tokens
* Updated compiled output
* Updated browser compiler
* Output block comments in the same `compileFragments` method as line comments, except for inline block comments
* Comments before splice
* Updated browser compiler
* Track compiledComments as a property of Base, to ensure that it’s not a global variable
* Docs: split up the Usage section
* Docs for type annotations via Flow; updated docs output
* Update regular comments documentation
* Updated browser compiler
* Comments before soak
* Comments before static methods, and probably before `@variable =` (this) assignments generally
* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods
* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call
* Fix missing comments before `if not` (i.e. before a UNARY token)
* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)
* Comments within heregexes
* Updated browser compiler
* Update description to reflect what’s now happening in compileCommentFragments
* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace
* Better future-proof comments tests
* Comments before object destructuring; abstract method for setting comments aside before compilation
* Handle more cases of comments before or after `for` loop declaration lines
* Fix indentation of comments preceding `for` loops
* Fix comment before splat function parameter
* Catch another RegexWithInterpolations comment edge case
* Updated browser compiler
* Change heregex example to one that’s more readable; update output
* Remove a few last references to the defunct HERECOMMENT token
* Abstract location hash creation into a function
* Improved clarity per code review notes
* Updated browser compiler
2017-08-02 22:34:34 -04:00
|
|
|
// Just check to see if a variable has already been declared, without reserving,
|
|
|
|
// walks up to the root scope.
|
[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
|
|
|
check(name) {
|
2015-02-07 15:50:41 -05:00
|
|
|
var ref;
|
|
|
|
return !!(this.type(name) || ((ref = this.parent) != null ? ref.check(name) : void 0));
|
[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] Comments (#4572)
* Make `addLocationDataFn` more DRY
* Style fixes
* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data
* Fix style.
* Fix style.
* Label test comments
* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing
* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).
* If a comment follows a class declaration, move the comment inside the class body
* Style
* Improve indentation of multiline comments
* Fix indentation for block comments, at least in the cases covered by the one failing test
* Don’t reverse the order of unshifted comments
* Simplify rewriter’s handling of comments, generalizing the special case
* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through
* Improve comments; fix multiline flag
* Prepare HereComments for processing line comments
* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit
* Updated compiler, now with line comments
* `process` doesn’t exist in the browser, so we should check for its existence first
* Update parser output
* Test that proves #4290 is fixed
* Indent line comments, first pass
* Compiled output with indented line comments
* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline
* Revised output
* Cleanup
* Split “multiline” line comment tokens, shifting them forward or back as appropriate
* Fix comments in module specifiers
* Abstract attaching comments to a node
* Line comments in interpolated strings
* Line comments can’t be multiline anymore
* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)
* Make comments compilation more object-oriented
* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment
* Improve eqJS helper
* Fix #4290 definitively, with improved output for arrays with interspersed block comments
* Add support for line comments output interspersed within arrays
* Fix mistake, don’t lose the variable we’re working on
* Remove redundant replacements
* Check for indentation only from the start of the string
* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces
* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset
* Don’t rely on `fragment.type`, which can break when the compiler is minified
* Updated generated docs and browser compiler
* Output block comments after function arguments
* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output
* Create new FuncGlyph node, to hold comments we want to output near the function parameters
* Block comments between `)` and `->`/`=>` get output between `)` and `{`.
* Fix indentation of comments that are the first line inside a bare mode block
* Updated output
* Full Flow example
* Updated browser compiler
* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`
* Abstract token insertion code
* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node
* Allow `SUPER` tokens to carry comments
* Rescue comments from `Existence` nodes and `If` nodes’ conditions
* Rescue comments after `\` line continuation tokens
* Updated compiled output
* Updated browser compiler
* Output block comments in the same `compileFragments` method as line comments, except for inline block comments
* Comments before splice
* Updated browser compiler
* Track compiledComments as a property of Base, to ensure that it’s not a global variable
* Docs: split up the Usage section
* Docs for type annotations via Flow; updated docs output
* Update regular comments documentation
* Updated browser compiler
* Comments before soak
* Comments before static methods, and probably before `@variable =` (this) assignments generally
* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods
* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call
* Fix missing comments before `if not` (i.e. before a UNARY token)
* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)
* Comments within heregexes
* Updated browser compiler
* Update description to reflect what’s now happening in compileCommentFragments
* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace
* Better future-proof comments tests
* Comments before object destructuring; abstract method for setting comments aside before compilation
* Handle more cases of comments before or after `for` loop declaration lines
* Fix indentation of comments preceding `for` loops
* Fix comment before splat function parameter
* Catch another RegexWithInterpolations comment edge case
* Updated browser compiler
* Change heregex example to one that’s more readable; update output
* Remove a few last references to the defunct HERECOMMENT token
* Abstract location hash creation into a function
* Improved clarity per code review notes
* Updated browser compiler
2017-08-02 22:34:34 -04:00
|
|
|
// Generate a temporary variable name at the given index.
|
[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
|
|
|
temporary(name, index, single = false) {
|
Improve naming of generated 'i-variables'
In for example `for` loops, a variable called `i` is generated (for the
loop index). If that name is unavailable, `j` is used instead, then `k`,
`l`, etc. all the way to `z`. Then, `aa`, `ab`, `ac` etc. are used.
This meant that, eventually, `do` would be used, but that's not a valid
variable name since `do` is a JavaScript keyword.
This logic was also inefficiently implemented. For example, going from
`aa` to `ab` or from `az` to `ba` required lots of loop iterations.
This commit changes the variable naming convention. Now, `i`, `j`, `k`,
etc. to `z` are used like before. Then comes `i1`, `j1`, `k1`, etc. Then
`i2`, `j2`, `k2` and so on. This is simpler, efficient and easier to
understand. `i1` is more obvious to be a loop index than `aa`.
Fixes #4267.
2016-06-10 02:58:18 -04:00
|
|
|
var diff, endCode, letter, newCode, num, startCode;
|
2015-01-30 14:33:03 -05:00
|
|
|
if (single) {
|
Improve naming of generated 'i-variables'
In for example `for` loops, a variable called `i` is generated (for the
loop index). If that name is unavailable, `j` is used instead, then `k`,
`l`, etc. all the way to `z`. Then, `aa`, `ab`, `ac` etc. are used.
This meant that, eventually, `do` would be used, but that's not a valid
variable name since `do` is a JavaScript keyword.
This logic was also inefficiently implemented. For example, going from
`aa` to `ab` or from `az` to `ba` required lots of loop iterations.
This commit changes the variable naming convention. Now, `i`, `j`, `k`,
etc. to `z` are used like before. Then comes `i1`, `j1`, `k1`, etc. Then
`i2`, `j2`, `k2` and so on. This is simpler, efficient and easier to
understand. `i1` is more obvious to be a loop index than `aa`.
Fixes #4267.
2016-06-10 02:58:18 -04:00
|
|
|
startCode = name.charCodeAt(0);
|
|
|
|
endCode = 'z'.charCodeAt(0);
|
|
|
|
diff = endCode - startCode;
|
|
|
|
newCode = startCode + index % (diff + 1);
|
|
|
|
letter = String.fromCharCode(newCode);
|
|
|
|
num = Math.floor(index / (diff + 1));
|
2016-11-28 09:05:51 -05:00
|
|
|
return `${letter}${num || ''}`;
|
2015-01-29 16:24:30 -05:00
|
|
|
} else {
|
2016-11-28 09:05:51 -05:00
|
|
|
return `${name}${index || ''}`;
|
2010-11-28 12:28:46 -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
|
|
|
|
[CS2] Comments (#4572)
* Make `addLocationDataFn` more DRY
* Style fixes
* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data
* Fix style.
* Fix style.
* Label test comments
* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing
* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).
* If a comment follows a class declaration, move the comment inside the class body
* Style
* Improve indentation of multiline comments
* Fix indentation for block comments, at least in the cases covered by the one failing test
* Don’t reverse the order of unshifted comments
* Simplify rewriter’s handling of comments, generalizing the special case
* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through
* Improve comments; fix multiline flag
* Prepare HereComments for processing line comments
* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit
* Updated compiler, now with line comments
* `process` doesn’t exist in the browser, so we should check for its existence first
* Update parser output
* Test that proves #4290 is fixed
* Indent line comments, first pass
* Compiled output with indented line comments
* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline
* Revised output
* Cleanup
* Split “multiline” line comment tokens, shifting them forward or back as appropriate
* Fix comments in module specifiers
* Abstract attaching comments to a node
* Line comments in interpolated strings
* Line comments can’t be multiline anymore
* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)
* Make comments compilation more object-oriented
* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment
* Improve eqJS helper
* Fix #4290 definitively, with improved output for arrays with interspersed block comments
* Add support for line comments output interspersed within arrays
* Fix mistake, don’t lose the variable we’re working on
* Remove redundant replacements
* Check for indentation only from the start of the string
* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces
* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset
* Don’t rely on `fragment.type`, which can break when the compiler is minified
* Updated generated docs and browser compiler
* Output block comments after function arguments
* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output
* Create new FuncGlyph node, to hold comments we want to output near the function parameters
* Block comments between `)` and `->`/`=>` get output between `)` and `{`.
* Fix indentation of comments that are the first line inside a bare mode block
* Updated output
* Full Flow example
* Updated browser compiler
* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`
* Abstract token insertion code
* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node
* Allow `SUPER` tokens to carry comments
* Rescue comments from `Existence` nodes and `If` nodes’ conditions
* Rescue comments after `\` line continuation tokens
* Updated compiled output
* Updated browser compiler
* Output block comments in the same `compileFragments` method as line comments, except for inline block comments
* Comments before splice
* Updated browser compiler
* Track compiledComments as a property of Base, to ensure that it’s not a global variable
* Docs: split up the Usage section
* Docs for type annotations via Flow; updated docs output
* Update regular comments documentation
* Updated browser compiler
* Comments before soak
* Comments before static methods, and probably before `@variable =` (this) assignments generally
* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods
* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call
* Fix missing comments before `if not` (i.e. before a UNARY token)
* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)
* Comments within heregexes
* Updated browser compiler
* Update description to reflect what’s now happening in compileCommentFragments
* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace
* Better future-proof comments tests
* Comments before object destructuring; abstract method for setting comments aside before compilation
* Handle more cases of comments before or after `for` loop declaration lines
* Fix indentation of comments preceding `for` loops
* Fix comment before splat function parameter
* Catch another RegexWithInterpolations comment edge case
* Updated browser compiler
* Change heregex example to one that’s more readable; update output
* Remove a few last references to the defunct HERECOMMENT token
* Abstract location hash creation into a function
* Improved clarity per code review notes
* Updated browser compiler
2017-08-02 22:34:34 -04:00
|
|
|
// Gets the type of a variable.
|
[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
|
|
|
type(name) {
|
2015-02-07 15:50:41 -05:00
|
|
|
var i, len, ref, v;
|
|
|
|
ref = this.variables;
|
|
|
|
for (i = 0, len = ref.length; i < len; i++) {
|
|
|
|
v = ref[i];
|
2012-04-10 14:57:45 -04:00
|
|
|
if (v.name === name) {
|
|
|
|
return v.type;
|
|
|
|
}
|
2010-10-19 19:36:50 -04:00
|
|
|
}
|
|
|
|
return null;
|
[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] Comments (#4572)
* Make `addLocationDataFn` more DRY
* Style fixes
* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data
* Fix style.
* Fix style.
* Label test comments
* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing
* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).
* If a comment follows a class declaration, move the comment inside the class body
* Style
* Improve indentation of multiline comments
* Fix indentation for block comments, at least in the cases covered by the one failing test
* Don’t reverse the order of unshifted comments
* Simplify rewriter’s handling of comments, generalizing the special case
* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through
* Improve comments; fix multiline flag
* Prepare HereComments for processing line comments
* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit
* Updated compiler, now with line comments
* `process` doesn’t exist in the browser, so we should check for its existence first
* Update parser output
* Test that proves #4290 is fixed
* Indent line comments, first pass
* Compiled output with indented line comments
* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline
* Revised output
* Cleanup
* Split “multiline” line comment tokens, shifting them forward or back as appropriate
* Fix comments in module specifiers
* Abstract attaching comments to a node
* Line comments in interpolated strings
* Line comments can’t be multiline anymore
* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)
* Make comments compilation more object-oriented
* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment
* Improve eqJS helper
* Fix #4290 definitively, with improved output for arrays with interspersed block comments
* Add support for line comments output interspersed within arrays
* Fix mistake, don’t lose the variable we’re working on
* Remove redundant replacements
* Check for indentation only from the start of the string
* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces
* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset
* Don’t rely on `fragment.type`, which can break when the compiler is minified
* Updated generated docs and browser compiler
* Output block comments after function arguments
* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output
* Create new FuncGlyph node, to hold comments we want to output near the function parameters
* Block comments between `)` and `->`/`=>` get output between `)` and `{`.
* Fix indentation of comments that are the first line inside a bare mode block
* Updated output
* Full Flow example
* Updated browser compiler
* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`
* Abstract token insertion code
* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node
* Allow `SUPER` tokens to carry comments
* Rescue comments from `Existence` nodes and `If` nodes’ conditions
* Rescue comments after `\` line continuation tokens
* Updated compiled output
* Updated browser compiler
* Output block comments in the same `compileFragments` method as line comments, except for inline block comments
* Comments before splice
* Updated browser compiler
* Track compiledComments as a property of Base, to ensure that it’s not a global variable
* Docs: split up the Usage section
* Docs for type annotations via Flow; updated docs output
* Update regular comments documentation
* Updated browser compiler
* Comments before soak
* Comments before static methods, and probably before `@variable =` (this) assignments generally
* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods
* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call
* Fix missing comments before `if not` (i.e. before a UNARY token)
* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)
* Comments within heregexes
* Updated browser compiler
* Update description to reflect what’s now happening in compileCommentFragments
* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace
* Better future-proof comments tests
* Comments before object destructuring; abstract method for setting comments aside before compilation
* Handle more cases of comments before or after `for` loop declaration lines
* Fix indentation of comments preceding `for` loops
* Fix comment before splat function parameter
* Catch another RegexWithInterpolations comment edge case
* Updated browser compiler
* Change heregex example to one that’s more readable; update output
* Remove a few last references to the defunct HERECOMMENT token
* Abstract location hash creation into a function
* Improved clarity per code review notes
* Updated browser compiler
2017-08-02 22:34:34 -04:00
|
|
|
// If we need to store an intermediate result, find an available name for a
|
|
|
|
// compiler-generated variable. `_var`, `_var2`, and so on...
|
[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
|
|
|
freeVariable(name, options = {}) {
|
2015-02-07 15:50:41 -05:00
|
|
|
var index, ref, temp;
|
2010-09-19 10:03:45 -04:00
|
|
|
index = 0;
|
Fix #1500, #1574, #3318: Name generated vars uniquely
Any variables generated by CoffeeScript are now made sure to be named to
something not present in the source code being compiled. This way you can no
longer interfere with them, either on purpose or by mistake. (#1500, #1574)
For example, `({a}, _arg) ->` now compiles correctly. (#1574)
As opposed to the somewhat complex implementations discussed in #1500, this
commit takes a very simple approach by saving all used variables names using a
single pass over the token stream. Any generated variables are then made sure
not to exist in that list.
`(@a) -> a` used to be equivalent to `(@a) -> @a`, but now throws a runtime
`ReferenceError` instead (unless `a` exists in an upper scope of course). (#3318)
`(@a) ->` used to compile to `(function(a) { this.a = a; })`. Now it compiles to
`(function(_at_a) { this.a = _at_a; })`. (But you cannot access `_at_a` either,
of course.)
Because of the above, `(@a, a) ->` is now valid; `@a` and `a` are not duplicate
parameters.
Duplicate this-parameters with a reserved word, such as `(@case, @case) ->`,
used to compile but now throws, just like regular duplicate parameters.
2015-01-10 17:04:30 -05:00
|
|
|
while (true) {
|
2015-01-30 14:33:03 -05:00
|
|
|
temp = this.temporary(name, index, options.single);
|
|
|
|
if (!(this.check(temp) || indexOf.call(this.root.referencedVars, temp) >= 0)) {
|
Fix #1500, #1574, #3318: Name generated vars uniquely
Any variables generated by CoffeeScript are now made sure to be named to
something not present in the source code being compiled. This way you can no
longer interfere with them, either on purpose or by mistake. (#1500, #1574)
For example, `({a}, _arg) ->` now compiles correctly. (#1574)
As opposed to the somewhat complex implementations discussed in #1500, this
commit takes a very simple approach by saving all used variables names using a
single pass over the token stream. Any generated variables are then made sure
not to exist in that list.
`(@a) -> a` used to be equivalent to `(@a) -> @a`, but now throws a runtime
`ReferenceError` instead (unless `a` exists in an upper scope of course). (#3318)
`(@a) ->` used to compile to `(function(a) { this.a = a; })`. Now it compiles to
`(function(_at_a) { this.a = _at_a; })`. (But you cannot access `_at_a` either,
of course.)
Because of the above, `(@a, a) ->` is now valid; `@a` and `a` are not duplicate
parameters.
Duplicate this-parameters with a reserved word, such as `(@case, @case) ->`,
used to compile but now throws, just like regular duplicate parameters.
2015-01-10 17:04:30 -05:00
|
|
|
break;
|
|
|
|
}
|
2010-09-19 10:03:45 -04:00
|
|
|
index++;
|
2010-02-27 19:46:45 -05:00
|
|
|
}
|
2015-02-07 15:50:41 -05:00
|
|
|
if ((ref = options.reserve) != null ? ref : true) {
|
2012-04-10 14:57:45 -04:00
|
|
|
this.add(temp, 'var', true);
|
|
|
|
}
|
2010-09-19 08:50:17 -04:00
|
|
|
return temp;
|
[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] Comments (#4572)
* Make `addLocationDataFn` more DRY
* Style fixes
* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data
* Fix style.
* Fix style.
* Label test comments
* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing
* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).
* If a comment follows a class declaration, move the comment inside the class body
* Style
* Improve indentation of multiline comments
* Fix indentation for block comments, at least in the cases covered by the one failing test
* Don’t reverse the order of unshifted comments
* Simplify rewriter’s handling of comments, generalizing the special case
* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through
* Improve comments; fix multiline flag
* Prepare HereComments for processing line comments
* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit
* Updated compiler, now with line comments
* `process` doesn’t exist in the browser, so we should check for its existence first
* Update parser output
* Test that proves #4290 is fixed
* Indent line comments, first pass
* Compiled output with indented line comments
* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline
* Revised output
* Cleanup
* Split “multiline” line comment tokens, shifting them forward or back as appropriate
* Fix comments in module specifiers
* Abstract attaching comments to a node
* Line comments in interpolated strings
* Line comments can’t be multiline anymore
* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)
* Make comments compilation more object-oriented
* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment
* Improve eqJS helper
* Fix #4290 definitively, with improved output for arrays with interspersed block comments
* Add support for line comments output interspersed within arrays
* Fix mistake, don’t lose the variable we’re working on
* Remove redundant replacements
* Check for indentation only from the start of the string
* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces
* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset
* Don’t rely on `fragment.type`, which can break when the compiler is minified
* Updated generated docs and browser compiler
* Output block comments after function arguments
* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output
* Create new FuncGlyph node, to hold comments we want to output near the function parameters
* Block comments between `)` and `->`/`=>` get output between `)` and `{`.
* Fix indentation of comments that are the first line inside a bare mode block
* Updated output
* Full Flow example
* Updated browser compiler
* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`
* Abstract token insertion code
* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node
* Allow `SUPER` tokens to carry comments
* Rescue comments from `Existence` nodes and `If` nodes’ conditions
* Rescue comments after `\` line continuation tokens
* Updated compiled output
* Updated browser compiler
* Output block comments in the same `compileFragments` method as line comments, except for inline block comments
* Comments before splice
* Updated browser compiler
* Track compiledComments as a property of Base, to ensure that it’s not a global variable
* Docs: split up the Usage section
* Docs for type annotations via Flow; updated docs output
* Update regular comments documentation
* Updated browser compiler
* Comments before soak
* Comments before static methods, and probably before `@variable =` (this) assignments generally
* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods
* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call
* Fix missing comments before `if not` (i.e. before a UNARY token)
* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)
* Comments within heregexes
* Updated browser compiler
* Update description to reflect what’s now happening in compileCommentFragments
* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace
* Better future-proof comments tests
* Comments before object destructuring; abstract method for setting comments aside before compilation
* Handle more cases of comments before or after `for` loop declaration lines
* Fix indentation of comments preceding `for` loops
* Fix comment before splat function parameter
* Catch another RegexWithInterpolations comment edge case
* Updated browser compiler
* Change heregex example to one that’s more readable; update output
* Remove a few last references to the defunct HERECOMMENT token
* Abstract location hash creation into a function
* Improved clarity per code review notes
* Updated browser compiler
2017-08-02 22:34:34 -04:00
|
|
|
// Ensure that an assignment is made at the top of this scope
|
|
|
|
// (or at the top-level scope, if requested).
|
[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
|
|
|
assign(name, value) {
|
2010-12-06 23:32:32 -05:00
|
|
|
this.add(name, {
|
2017-04-06 13:06:45 -04:00
|
|
|
value,
|
2010-10-19 19:51:34 -04:00
|
|
|
assigned: true
|
2011-11-10 03:08:38 -05:00
|
|
|
}, true);
|
2010-12-06 23:32:32 -05:00
|
|
|
return this.hasAssignments = true;
|
[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] Comments (#4572)
* Make `addLocationDataFn` more DRY
* Style fixes
* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data
* Fix style.
* Fix style.
* Label test comments
* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing
* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).
* If a comment follows a class declaration, move the comment inside the class body
* Style
* Improve indentation of multiline comments
* Fix indentation for block comments, at least in the cases covered by the one failing test
* Don’t reverse the order of unshifted comments
* Simplify rewriter’s handling of comments, generalizing the special case
* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through
* Improve comments; fix multiline flag
* Prepare HereComments for processing line comments
* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit
* Updated compiler, now with line comments
* `process` doesn’t exist in the browser, so we should check for its existence first
* Update parser output
* Test that proves #4290 is fixed
* Indent line comments, first pass
* Compiled output with indented line comments
* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline
* Revised output
* Cleanup
* Split “multiline” line comment tokens, shifting them forward or back as appropriate
* Fix comments in module specifiers
* Abstract attaching comments to a node
* Line comments in interpolated strings
* Line comments can’t be multiline anymore
* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)
* Make comments compilation more object-oriented
* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment
* Improve eqJS helper
* Fix #4290 definitively, with improved output for arrays with interspersed block comments
* Add support for line comments output interspersed within arrays
* Fix mistake, don’t lose the variable we’re working on
* Remove redundant replacements
* Check for indentation only from the start of the string
* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces
* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset
* Don’t rely on `fragment.type`, which can break when the compiler is minified
* Updated generated docs and browser compiler
* Output block comments after function arguments
* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output
* Create new FuncGlyph node, to hold comments we want to output near the function parameters
* Block comments between `)` and `->`/`=>` get output between `)` and `{`.
* Fix indentation of comments that are the first line inside a bare mode block
* Updated output
* Full Flow example
* Updated browser compiler
* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`
* Abstract token insertion code
* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node
* Allow `SUPER` tokens to carry comments
* Rescue comments from `Existence` nodes and `If` nodes’ conditions
* Rescue comments after `\` line continuation tokens
* Updated compiled output
* Updated browser compiler
* Output block comments in the same `compileFragments` method as line comments, except for inline block comments
* Comments before splice
* Updated browser compiler
* Track compiledComments as a property of Base, to ensure that it’s not a global variable
* Docs: split up the Usage section
* Docs for type annotations via Flow; updated docs output
* Update regular comments documentation
* Updated browser compiler
* Comments before soak
* Comments before static methods, and probably before `@variable =` (this) assignments generally
* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods
* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call
* Fix missing comments before `if not` (i.e. before a UNARY token)
* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)
* Comments within heregexes
* Updated browser compiler
* Update description to reflect what’s now happening in compileCommentFragments
* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace
* Better future-proof comments tests
* Comments before object destructuring; abstract method for setting comments aside before compilation
* Handle more cases of comments before or after `for` loop declaration lines
* Fix indentation of comments preceding `for` loops
* Fix comment before splat function parameter
* Catch another RegexWithInterpolations comment edge case
* Updated browser compiler
* Change heregex example to one that’s more readable; update output
* Remove a few last references to the defunct HERECOMMENT token
* Abstract location hash creation into a function
* Improved clarity per code review notes
* Updated browser compiler
2017-08-02 22:34:34 -04:00
|
|
|
// Does this scope have any declared variables?
|
[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
|
|
|
hasDeclarations() {
|
2010-12-12 12:16:27 -05:00
|
|
|
return !!this.declaredVariables().length;
|
[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] Comments (#4572)
* Make `addLocationDataFn` more DRY
* Style fixes
* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data
* Fix style.
* Fix style.
* Label test comments
* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing
* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).
* If a comment follows a class declaration, move the comment inside the class body
* Style
* Improve indentation of multiline comments
* Fix indentation for block comments, at least in the cases covered by the one failing test
* Don’t reverse the order of unshifted comments
* Simplify rewriter’s handling of comments, generalizing the special case
* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through
* Improve comments; fix multiline flag
* Prepare HereComments for processing line comments
* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit
* Updated compiler, now with line comments
* `process` doesn’t exist in the browser, so we should check for its existence first
* Update parser output
* Test that proves #4290 is fixed
* Indent line comments, first pass
* Compiled output with indented line comments
* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline
* Revised output
* Cleanup
* Split “multiline” line comment tokens, shifting them forward or back as appropriate
* Fix comments in module specifiers
* Abstract attaching comments to a node
* Line comments in interpolated strings
* Line comments can’t be multiline anymore
* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)
* Make comments compilation more object-oriented
* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment
* Improve eqJS helper
* Fix #4290 definitively, with improved output for arrays with interspersed block comments
* Add support for line comments output interspersed within arrays
* Fix mistake, don’t lose the variable we’re working on
* Remove redundant replacements
* Check for indentation only from the start of the string
* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces
* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset
* Don’t rely on `fragment.type`, which can break when the compiler is minified
* Updated generated docs and browser compiler
* Output block comments after function arguments
* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output
* Create new FuncGlyph node, to hold comments we want to output near the function parameters
* Block comments between `)` and `->`/`=>` get output between `)` and `{`.
* Fix indentation of comments that are the first line inside a bare mode block
* Updated output
* Full Flow example
* Updated browser compiler
* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`
* Abstract token insertion code
* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node
* Allow `SUPER` tokens to carry comments
* Rescue comments from `Existence` nodes and `If` nodes’ conditions
* Rescue comments after `\` line continuation tokens
* Updated compiled output
* Updated browser compiler
* Output block comments in the same `compileFragments` method as line comments, except for inline block comments
* Comments before splice
* Updated browser compiler
* Track compiledComments as a property of Base, to ensure that it’s not a global variable
* Docs: split up the Usage section
* Docs for type annotations via Flow; updated docs output
* Update regular comments documentation
* Updated browser compiler
* Comments before soak
* Comments before static methods, and probably before `@variable =` (this) assignments generally
* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods
* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call
* Fix missing comments before `if not` (i.e. before a UNARY token)
* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)
* Comments within heregexes
* Updated browser compiler
* Update description to reflect what’s now happening in compileCommentFragments
* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace
* Better future-proof comments tests
* Comments before object destructuring; abstract method for setting comments aside before compilation
* Handle more cases of comments before or after `for` loop declaration lines
* Fix indentation of comments preceding `for` loops
* Fix comment before splat function parameter
* Catch another RegexWithInterpolations comment edge case
* Updated browser compiler
* Change heregex example to one that’s more readable; update output
* Remove a few last references to the defunct HERECOMMENT token
* Abstract location hash creation into a function
* Improved clarity per code review notes
* Updated browser compiler
2017-08-02 22:34:34 -04:00
|
|
|
// Return the list of variables first declared in this scope.
|
[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
|
|
|
declaredVariables() {
|
2015-01-30 14:33:03 -05:00
|
|
|
var v;
|
|
|
|
return ((function() {
|
2015-02-07 15:50:41 -05:00
|
|
|
var i, len, ref, results;
|
|
|
|
ref = this.variables;
|
2015-01-30 14:33:03 -05:00
|
|
|
results = [];
|
2015-02-07 15:50:41 -05:00
|
|
|
for (i = 0, len = ref.length; i < len; i++) {
|
|
|
|
v = ref[i];
|
2015-01-30 14:33:03 -05:00
|
|
|
if (v.type === 'var') {
|
|
|
|
results.push(v.name);
|
|
|
|
}
|
2011-08-08 12:55:22 -04:00
|
|
|
}
|
2015-01-30 14:33:03 -05:00
|
|
|
return results;
|
|
|
|
}).call(this)).sort();
|
[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] Comments (#4572)
* Make `addLocationDataFn` more DRY
* Style fixes
* Provide access to full parser inside our custom function running in parser.js; rename the function to lay the groundwork for adding data aside from location data
* Fix style.
* Fix style.
* Label test comments
* Update grammar to remove comment tokens; update DSL to call new helper function that preserves comments through parsing
* New implementation of compiling block comments: the lexer pulls them out of the token stream, attaching them as a property to a token; the rewriter moves the attachment around so it lives on a token that is destined to make it through to compilation (and in a good placement); and the nodes render the block comment. All tests but one pass (commented out).
* If a comment follows a class declaration, move the comment inside the class body
* Style
* Improve indentation of multiline comments
* Fix indentation for block comments, at least in the cases covered by the one failing test
* Don’t reverse the order of unshifted comments
* Simplify rewriter’s handling of comments, generalizing the special case
* Expand the list of tokens we need to avoid for passing comments through the parser; get some literal tokens to have nodes created for them so that the comments pass through
* Improve comments; fix multiline flag
* Prepare HereComments for processing line comments
* Line comments, first draft: the tests pass, but the line comments aren’t indented and sometimes trail previous lines when they shouldn’t; updated compiler output in following commit
* Updated compiler, now with line comments
* `process` doesn’t exist in the browser, so we should check for its existence first
* Update parser output
* Test that proves #4290 is fixed
* Indent line comments, first pass
* Compiled output with indented line comments
* Comments that start a new line shouldn’t trail; don’t skip comments attached to generated tokens; stop looking for indentation once we hit a newline
* Revised output
* Cleanup
* Split “multiline” line comment tokens, shifting them forward or back as appropriate
* Fix comments in module specifiers
* Abstract attaching comments to a node
* Line comments in interpolated strings
* Line comments can’t be multiline anymore
* Improve handling of blank lines and indentation of following comments that start a new line (i.e. don’t trail)
* Make comments compilation more object-oriented
* Remove lots of dead code that we don’t need anymore because a comment is never a node, only a fragment
* Improve eqJS helper
* Fix #4290 definitively, with improved output for arrays with interspersed block comments
* Add support for line comments output interspersed within arrays
* Fix mistake, don’t lose the variable we’re working on
* Remove redundant replacements
* Check for indentation only from the start of the string
* Indentations in generated JS are always multiples of two spaces (never tabs) so just look for 2+ spaces
* Update package versions; run Babel twice, once for each preset, temporarily until a Babili bug is fixed that prevents it from running with the env preset
* Don’t rely on `fragment.type`, which can break when the compiler is minified
* Updated generated docs and browser compiler
* Output block comments after function arguments
* Comments appear above scope `var` declarations; better tracking of generated `JS` tokens created only to shepherd comments through to the output
* Create new FuncGlyph node, to hold comments we want to output near the function parameters
* Block comments between `)` and `->`/`=>` get output between `)` and `{`.
* Fix indentation of comments that are the first line inside a bare mode block
* Updated output
* Full Flow example
* Updated browser compiler
* Abstract and organize comment fragment generation code; store more properties on the comment fragment objects; make `throw` behave like `return`
* Abstract token insertion code
* Add missing locationData to STRING_START token, giving it the locationData of the overall StringWithInterpolations token so that comments attached to STRING_START end up on the StringWithInterpolations node
* Allow `SUPER` tokens to carry comments
* Rescue comments from `Existence` nodes and `If` nodes’ conditions
* Rescue comments after `\` line continuation tokens
* Updated compiled output
* Updated browser compiler
* Output block comments in the same `compileFragments` method as line comments, except for inline block comments
* Comments before splice
* Updated browser compiler
* Track compiledComments as a property of Base, to ensure that it’s not a global variable
* Docs: split up the Usage section
* Docs for type annotations via Flow; updated docs output
* Update regular comments documentation
* Updated browser compiler
* Comments before soak
* Comments before static methods, and probably before `@variable =` (this) assignments generally
* Comments before ‘if exists?’, refactor comment before ‘if this.var’ to be more precise, improve helper methods
* Comments before a method that contains ‘super()’ should output above the method property, not above the ‘super.method()’ call
* Fix missing comments before `if not` (i.e. before a UNARY token)
* Fix comments before ‘for’; add test for comment before assignment if (fixed in earlier commit)
* Comments within heregexes
* Updated browser compiler
* Update description to reflect what’s now happening in compileCommentFragments
* Preserve blank lines between line comments; output “whitespace-only” line comments as blank lines, rather than `//` following by whitespace
* Better future-proof comments tests
* Comments before object destructuring; abstract method for setting comments aside before compilation
* Handle more cases of comments before or after `for` loop declaration lines
* Fix indentation of comments preceding `for` loops
* Fix comment before splat function parameter
* Catch another RegexWithInterpolations comment edge case
* Updated browser compiler
* Change heregex example to one that’s more readable; update output
* Remove a few last references to the defunct HERECOMMENT token
* Abstract location hash creation into a function
* Improved clarity per code review notes
* Updated browser compiler
2017-08-02 22:34:34 -04:00
|
|
|
// Return the list of assignments that are supposed to be made at the top
|
|
|
|
// of this scope.
|
[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
|
|
|
assignedVariables() {
|
2015-02-07 15:50:41 -05:00
|
|
|
var i, len, ref, results, v;
|
|
|
|
ref = this.variables;
|
2015-01-30 14:33:03 -05:00
|
|
|
results = [];
|
2015-02-07 15:50:41 -05:00
|
|
|
for (i = 0, len = ref.length; i < len; i++) {
|
|
|
|
v = ref[i];
|
2012-04-10 14:57:45 -04:00
|
|
|
if (v.type.assigned) {
|
2016-11-28 09:05:51 -05:00
|
|
|
results.push(`${v.name} = ${v.type.value}`);
|
2012-04-10 14:57:45 -04:00
|
|
|
}
|
2010-07-16 22:31:36 -04:00
|
|
|
}
|
2015-01-30 14:33:03 -05:00
|
|
|
return results;
|
[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-12-14 10:39:20 -05:00
|
|
|
|
2010-09-21 03:53:58 -04:00
|
|
|
}).call(this);
|