jashkenas--coffeescript/lib/coffeescript/lexer.js

1944 lines
74 KiB
JavaScript
Raw Normal View History

2022-04-24 02:19:19 +00:00
// Generated by CoffeeScript 2.7.0
2010-07-25 07:15:12 +00: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-03 02:34:34 +00:00
// The CoffeeScript Lexer. Uses a series of token-matching regexes to attempt
// matches against the beginning of the source code. When a match is found,
// a token is produced, we consume the match, and start again. Tokens are in the
// form:
// [tag, value, locationData]
// where locationData is {first_line, first_column, last_line, last_column, last_line_exclusive, last_column_exclusive}, which is a
[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-03 02:34:34 +00:00
// format that can be fed directly into [Jison](https://github.com/zaach/jison). These
// are read by jison in the `parser.lexer` function defined in coffeescript.coffee.
AST: numeric separators, BigInt (#5272) * Revert to more complicated lexing of numbers, as the Number constructor can't handle BigInts or numbers with numeric separators * Add debugging information to error message test (#5239) One of the test cases in test/error_messages.coffee fails intermittently in the Node.js ecosystem-testing tool CITGM. In an effort to help debug what's going on when this occurs, this adds more information to the AssertionError message in question. * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Numeric literal separators (#5215) * implement numeric literal separators * add tests * Revert changes to package-lock.json * small regex adjustment * split tests * add comment * Add Node versions to CI * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Update output * Fix style * support bigint literal with separators * un-disallow property access on number literal * Update output * Refactor numeric literal separator tests to be more like the rest of the tests * Add test for numeric property with underscore Co-authored-by: Geoffrey Booth <GeoffreyBooth@users.noreply.github.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> * Update test style and output * numeric separator parsed value * BigInt AST; parseNumber() Co-authored-by: Geoffrey Booth <GeoffreyBooth@users.noreply.github.com> Co-authored-by: Rich Trott <rtrott@gmail.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> Co-authored-by: square <Inve1951@users.noreply.github.com>
2019-12-30 00:20:43 +00:00
var BOM, BOOL, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_ALIAS_MAP, COFFEE_KEYWORDS, COMMENT, COMPARABLE_LEFT_SIDE, COMPARE, COMPOUND_ASSIGN, HERECOMMENT_ILLEGAL, HEREDOC_DOUBLE, HEREDOC_INDENT, HEREDOC_SINGLE, HEREGEX, HEREGEX_COMMENT, HERE_JSTOKEN, IDENTIFIER, INDENTABLE_CLOSERS, INDEXABLE, INSIDE_JSX, INVERSES, JSTOKEN, JSX_ATTRIBUTE, JSX_FRAGMENT_IDENTIFIER, JSX_IDENTIFIER, JSX_IDENTIFIER_PART, JSX_INTERPOLATION, JS_KEYWORDS, LINE_BREAK, LINE_CONTINUER, Lexer, MATH, MULTI_DENT, NOT_REGEX, NUMBER, OPERATOR, POSSIBLY_DIVISION, REGEX, REGEX_FLAGS, REGEX_ILLEGAL, REGEX_INVALID_ESCAPE, RELATION, RESERVED, Rewriter, SHIFT, STRICT_PROSCRIBED, STRING_DOUBLE, STRING_INVALID_ESCAPE, STRING_SINGLE, STRING_START, TRAILING_SPACES, UNARY, UNARY_MATH, UNFINISHED, VALID_FLAGS, WHITESPACE, addTokenData, attachCommentsToNode, compact, count, flatten, invertLiterate, isForFrom, isUnassignable, key, locationDataToString, merge, parseNumber, repeat, replaceUnicodeCodePointEscapes, starts, throwSyntaxError,
indexOf = [].indexOf,
slice = [].slice;
({Rewriter, INVERSES, UNFINISHED} = require('./rewriter'));
[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-03 02:34:34 +00:00
// Import the helpers we need.
AST: numeric separators, BigInt (#5272) * Revert to more complicated lexing of numbers, as the Number constructor can't handle BigInts or numbers with numeric separators * Add debugging information to error message test (#5239) One of the test cases in test/error_messages.coffee fails intermittently in the Node.js ecosystem-testing tool CITGM. In an effort to help debug what's going on when this occurs, this adds more information to the AssertionError message in question. * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Numeric literal separators (#5215) * implement numeric literal separators * add tests * Revert changes to package-lock.json * small regex adjustment * split tests * add comment * Add Node versions to CI * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Update output * Fix style * support bigint literal with separators * un-disallow property access on number literal * Update output * Refactor numeric literal separator tests to be more like the rest of the tests * Add test for numeric property with underscore Co-authored-by: Geoffrey Booth <GeoffreyBooth@users.noreply.github.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> * Update test style and output * numeric separator parsed value * BigInt AST; parseNumber() Co-authored-by: Geoffrey Booth <GeoffreyBooth@users.noreply.github.com> Co-authored-by: Rich Trott <rtrott@gmail.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> Co-authored-by: square <Inve1951@users.noreply.github.com>
2019-12-30 00:20:43 +00:00
({count, starts, compact, repeat, invertLiterate, merge, attachCommentsToNode, locationDataToString, throwSyntaxError, replaceUnicodeCodePointEscapes, flatten, parseNumber} = require('./helpers'));
2013-02-25 17:41:34 +00: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-03 02:34:34 +00:00
// The Lexer Class
// ---------------
// The Lexer class reads a stream of CoffeeScript and divvies it up into tagged
// tokens. Some potential ambiguity in the grammar has been avoided by
// pushing some extra smarts into the Lexer.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
exports.Lexer = Lexer = class Lexer {
constructor() {
// Throws an error at either a given offset from the current chunk or at the
// location of a token (`token[2]`).
this.error = this.error.bind(this);
}
[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-03 02:34:34 +00:00
// **tokenize** is the Lexer's main method. Scan by attempting to match tokens
// one at a time, using a regular expression anchored at the start of the
// remaining code, or a custom recursive token-matching method
// (for interpolations). When the next token has been recorded, we move forward
// within the code past the token, and begin again.
// Each tokenizing method is responsible for returning the number of characters
// it has consumed.
// Before returning the token stream, run it through the [Rewriter](rewriter.html).
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
tokenize(code, opts = {}) {
var consumed, end, i, ref;
[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-03 02:34:34 +00:00
this.literate = opts.literate; // Are we lexing literate CoffeeScript?
this.indent = 0; // The current indentation level.
this.baseIndent = 0; // The overall minimum indentation level.
this.continuationLineAdditionalIndent = 0; // The over-indentation at the current level.
[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-03 02:34:34 +00:00
this.outdebt = 0; // The under-outdentation at the current level.
this.indents = []; // The stack of all current indentation levels.
this.indentLiteral = ''; // The indentation.
this.ends = []; // The stack for pairing up tokens.
this.tokens = []; // Stream of parsed tokens in the form `['TYPE', value, location data]`.
this.seenFor = false; // Used to recognize `FORIN`, `FOROF` and `FORFROM` tokens.
this.seenImport = false; // Used to recognize `IMPORT FROM? AS?` tokens.
this.seenExport = false; // Used to recognize `EXPORT FROM? AS?` tokens.
this.importSpecifierList = false; // Used to identify when in an `IMPORT {...} FROM? ...`.
this.exportSpecifierList = false; // Used to identify when in an `EXPORT {...} FROM? ...`.
this.jsxDepth = 0; // Used to optimize JSX checks, how deep in JSX we are.
this.jsxObjAttribute = {}; // Used to detect if JSX attributes is wrapped in {} (<div {props...} />).
[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-03 02:34:34 +00:00
this.chunkLine = opts.line || 0; // The start line for the current @chunk.
this.chunkColumn = opts.column || 0; // The start column of the current @chunk.
2018-08-21 23:57:00 +00:00
this.chunkOffset = opts.offset || 0; // The start offset for the current @chunk.
this.locationDataCompensations = opts.locationDataCompensations || {};
[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-03 02:34:34 +00:00
code = this.clean(code); // The stripped, cleaned original source code.
// At every position, run through this list of attempted matches,
// short-circuiting if any of them succeed. Their order determines precedence:
// `@literalToken` is the fallback catch-all.
i = 0;
while (this.chunk = code.slice(i)) {
consumed = this.identifierToken() || this.commentToken() || this.whitespaceToken() || this.lineToken() || this.stringToken() || this.numberToken() || this.jsxToken() || this.regexToken() || this.jsToken() || this.literalToken();
[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-03 02:34:34 +00:00
// Update position.
2018-08-21 23:57:00 +00:00
[this.chunkLine, this.chunkColumn, this.chunkOffset] = this.getLineAndColumnFromChunk(consumed);
i += consumed;
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
if (opts.untilBalanced && this.ends.length === 0) {
return {
tokens: this.tokens,
index: i
};
}
}
this.closeIndentation();
if (end = this.ends.pop()) {
this.error(`missing ${end.tag}`, ((ref = end.origin) != null ? ref : end)[2]);
2012-04-10 18:57:45 +00:00
}
if (opts.rewrite === false) {
return this.tokens;
}
return (new Rewriter()).rewrite(this.tokens);
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
}
[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-03 02:34:34 +00:00
// Preprocess the code to remove leading and trailing whitespace, carriage
// returns, etc. If were lexing literate CoffeeScript, strip external Markdown
// by removing all lines that arent indented by at least four spaces or a tab.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
clean(code) {
AST: Update with latest changes from master (#5270) * Fix #5213: Update Babel options to restore MINIFY=false (#5214) * CSX namespaced tags and attributes (#5218) * Support namespaces in attributes * Support namespaces in tag names * Support reserved words in CSX boolean properties (fix #5125) * Implement review comments * Build * Revert parser.js * Add debugging information to error message test (#5239) One of the test cases in test/error_messages.coffee fails intermittently in the Node.js ecosystem-testing tool CITGM. In an effort to help debug what's going on when this occurs, this adds more information to the AssertionError message in question. * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Numeric literal separators (#5215) * implement numeric literal separators * add tests * Revert changes to package-lock.json * small regex adjustment * split tests * add comment * Add Node versions to CI * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Update output * Fix style * support bigint literal with separators * un-disallow property access on number literal * Update output * Refactor numeric literal separator tests to be more like the rest of the tests * Add test for numeric property with underscore Co-authored-by: Geoffrey Booth <GeoffreyBooth@users.noreply.github.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> Co-authored-by: Erik Demaine <edemaine@mit.edu> Co-authored-by: Rich Trott <rtrott@gmail.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> Co-authored-by: square <Inve1951@users.noreply.github.com>
2019-12-30 00:55:33 +00:00
var base, thusFar;
thusFar = 0;
if (code.charCodeAt(0) === BOM) {
code = code.slice(1);
this.locationDataCompensations[0] = 1;
thusFar += 1;
}
if (WHITESPACE.test(code)) {
code = `\n${code}`;
this.chunkLine--;
AST: Update with latest changes from master (#5270) * Fix #5213: Update Babel options to restore MINIFY=false (#5214) * CSX namespaced tags and attributes (#5218) * Support namespaces in attributes * Support namespaces in tag names * Support reserved words in CSX boolean properties (fix #5125) * Implement review comments * Build * Revert parser.js * Add debugging information to error message test (#5239) One of the test cases in test/error_messages.coffee fails intermittently in the Node.js ecosystem-testing tool CITGM. In an effort to help debug what's going on when this occurs, this adds more information to the AssertionError message in question. * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Numeric literal separators (#5215) * implement numeric literal separators * add tests * Revert changes to package-lock.json * small regex adjustment * split tests * add comment * Add Node versions to CI * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Update output * Fix style * support bigint literal with separators * un-disallow property access on number literal * Update output * Refactor numeric literal separator tests to be more like the rest of the tests * Add test for numeric property with underscore Co-authored-by: Geoffrey Booth <GeoffreyBooth@users.noreply.github.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> Co-authored-by: Erik Demaine <edemaine@mit.edu> Co-authored-by: Rich Trott <rtrott@gmail.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> Co-authored-by: square <Inve1951@users.noreply.github.com>
2019-12-30 00:55:33 +00:00
if ((base = this.locationDataCompensations)[0] == null) {
base[0] = 0;
}
this.locationDataCompensations[0] -= 1;
}
code = code.replace(/\r/g, (match, offset) => {
this.locationDataCompensations[thusFar + offset] = 1;
return '';
}).replace(TRAILING_SPACES, '');
if (this.literate) {
code = invertLiterate(code);
}
return code;
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
}
[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-03 02:34:34 +00:00
// Tokenizers
// ----------
// Matches identifying literals: variables, keywords, method names, etc.
[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-03 02:34:34 +00:00
// Check to ensure that JavaScript reserved words arent being used as
// identifiers. Because CoffeeScript reserves a handful of keywords that are
// allowed in JavaScript, were careful not to tag them as keywords when
// referenced as property names here, so you can still do `jQuery.is()` even
// though `is` means `===` otherwise.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
identifierToken() {
var alias, colon, colonOffset, colonToken, id, idLength, inJSXTag, input, match, poppedToken, prev, prevprev, ref, ref1, ref10, ref11, ref12, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, regExSuper, regex, sup, tag, tagToken, tokenData;
inJSXTag = this.atJSXTag();
regex = inJSXTag ? JSX_ATTRIBUTE : IDENTIFIER;
if (!(match = regex.exec(this.chunk))) {
2012-04-10 18:57:45 +00:00
return 0;
}
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
[input, id, colon] = match;
[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-03 02:34:34 +00:00
// Preserve length of id for location data
idLength = id.length;
poppedToken = void 0;
2010-11-28 23:33:43 +00:00
if (id === 'own' && this.tag() === 'FOR') {
this.token('OWN', id);
return id.length;
}
2014-09-06 11:53:21 +00:00
if (id === 'from' && this.tag() === 'YIELD') {
this.token('FROM', id);
return id.length;
}
if (id === 'as' && this.seenImport) {
if (this.value() === '*') {
this.tokens[this.tokens.length - 1][0] = 'IMPORT_ALL';
2018-01-31 14:33:17 +00:00
} else if (ref = this.value(true), indexOf.call(COFFEE_KEYWORDS, ref) >= 0) {
prev = this.prev();
[prev[0], prev[1]] = ['IDENTIFIER', this.value(true)];
}
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
if ((ref1 = this.tag()) === 'DEFAULT' || ref1 === 'IMPORT_ALL' || ref1 === 'IDENTIFIER') {
this.token('AS', id);
return id.length;
}
}
if (id === 'as' && this.seenExport) {
if ((ref2 = this.tag()) === 'IDENTIFIER' || ref2 === 'DEFAULT') {
this.token('AS', id);
return id.length;
}
if (ref3 = this.value(true), indexOf.call(COFFEE_KEYWORDS, ref3) >= 0) {
prev = this.prev();
[prev[0], prev[1]] = ['IDENTIFIER', this.value(true)];
this.token('AS', id);
return id.length;
}
Support import and export of ES2015 modules (#4300) This pull request adds support for ES2015 modules, by recognizing `import` and `export` statements. The following syntaxes are supported, based on the MDN [import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) and [export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) pages: ```js import "module-name" import defaultMember from "module-name" import * as name from "module-name" import { } from "module-name" import { member } from "module-name" import { member as alias } from "module-name" import { member1, member2 as alias2, … } from "module-name" import defaultMember, * as name from "module-name" import defaultMember, { … } from "module-name" export default expression export class name export { } export { name } export { name as exportedName } export { name as default } export { name1, name2 as exportedName2, name3 as default, … } export * from "module-name" export { … } from "module-name" ``` As a subsitute for ECMAScript’s `export var name = …` and `export function name {}`, CoffeeScript also supports: ```js export name = … ``` CoffeeScript also supports optional commas within `{ … }`. This PR converts the supported `import` and `export` statements into ES2015 `import` and `export` statements; it **does not resolve the modules**. So any CoffeeScript with `import` or `export` statements will be output as ES2015, and will need to be transpiled by another tool such as Babel before it can be used in a browser. We will need to add a warning to the documentation explaining this. This should be fully backwards-compatible, as `import` and `export` were previously reserved keywords. No flags are used. There are extensive tests included, though because no current JavaScript runtime supports `import` or `export`, the tests compare strings of what the compiled CoffeeScript output is against what the expected ES2015 should be. I also conducted two more elaborate tests: * I forked the [ember-piqu](https://github.com/pauc/piqu-ember) project, which was an Ember CLI app that used ember-cli-coffeescript and [ember-cli-coffees6](https://github.com/alexspeller/ember-cli-coffees6) (which adds “support” for `import`/`export` by wrapping such statements in backticks before passing the result to the CoffeeScript compiler). I removed `ember-cli-coffees6` and replaced the CoffeeScript compiler used in the build chain with this code, and the app built without errors. [Demo here.](https://github.com/GeoffreyBooth/coffeescript-modules-test-piqu) * I also forked the [CoffeeScript version of Meteor’s Todos example app](https://github.com/meteor/todos/tree/coffeescript), and replaced all of its `require` statements with the `import` and `export` statements from the original ES2015 version of the app on its `master` branch. I then updated the `coffeescript` Meteor package in the app to use this new code, and again the app builds without errors. [Demo here.](https://github.com/GeoffreyBooth/coffeescript-modules-test-meteor-todos) The discussion history for this work started [here](https://github.com/jashkenas/coffeescript/pull/4160) and continued [here](https://github.com/GeoffreyBooth/coffeescript/pull/2). @lydell provided guidance, and @JimPanic and @rattrayalex contributed essential code.
2016-09-14 18:46:05 +00:00
}
if (id === 'default' && this.seenExport && ((ref4 = this.tag()) === 'EXPORT' || ref4 === 'AS')) {
Support import and export of ES2015 modules (#4300) This pull request adds support for ES2015 modules, by recognizing `import` and `export` statements. The following syntaxes are supported, based on the MDN [import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) and [export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) pages: ```js import "module-name" import defaultMember from "module-name" import * as name from "module-name" import { } from "module-name" import { member } from "module-name" import { member as alias } from "module-name" import { member1, member2 as alias2, … } from "module-name" import defaultMember, * as name from "module-name" import defaultMember, { … } from "module-name" export default expression export class name export { } export { name } export { name as exportedName } export { name as default } export { name1, name2 as exportedName2, name3 as default, … } export * from "module-name" export { … } from "module-name" ``` As a subsitute for ECMAScript’s `export var name = …` and `export function name {}`, CoffeeScript also supports: ```js export name = … ``` CoffeeScript also supports optional commas within `{ … }`. This PR converts the supported `import` and `export` statements into ES2015 `import` and `export` statements; it **does not resolve the modules**. So any CoffeeScript with `import` or `export` statements will be output as ES2015, and will need to be transpiled by another tool such as Babel before it can be used in a browser. We will need to add a warning to the documentation explaining this. This should be fully backwards-compatible, as `import` and `export` were previously reserved keywords. No flags are used. There are extensive tests included, though because no current JavaScript runtime supports `import` or `export`, the tests compare strings of what the compiled CoffeeScript output is against what the expected ES2015 should be. I also conducted two more elaborate tests: * I forked the [ember-piqu](https://github.com/pauc/piqu-ember) project, which was an Ember CLI app that used ember-cli-coffeescript and [ember-cli-coffees6](https://github.com/alexspeller/ember-cli-coffees6) (which adds “support” for `import`/`export` by wrapping such statements in backticks before passing the result to the CoffeeScript compiler). I removed `ember-cli-coffees6` and replaced the CoffeeScript compiler used in the build chain with this code, and the app built without errors. [Demo here.](https://github.com/GeoffreyBooth/coffeescript-modules-test-piqu) * I also forked the [CoffeeScript version of Meteor’s Todos example app](https://github.com/meteor/todos/tree/coffeescript), and replaced all of its `require` statements with the `import` and `export` statements from the original ES2015 version of the app on its `master` branch. I then updated the `coffeescript` Meteor package in the app to use this new code, and again the app builds without errors. [Demo here.](https://github.com/GeoffreyBooth/coffeescript-modules-test-meteor-todos) The discussion history for this work started [here](https://github.com/jashkenas/coffeescript/pull/4160) and continued [here](https://github.com/GeoffreyBooth/coffeescript/pull/2). @lydell provided guidance, and @JimPanic and @rattrayalex contributed essential code.
2016-09-14 18:46:05 +00:00
this.token('DEFAULT', id);
return id.length;
}
2022-01-20 19:40:13 +00:00
if (id === 'assert' && (this.seenImport || this.seenExport) && this.tag() === 'STRING') {
this.token('ASSERT', id);
return id.length;
}
if (id === 'do' && (regExSuper = /^(\s*super)(?!\(\))/.exec(this.chunk.slice(3)))) {
this.token('SUPER', 'super');
this.token('CALL_START', '(');
this.token('CALL_END', ')');
[input, sup] = regExSuper;
return sup.length + 3;
}
prev = this.prev();
tag = colon || (prev != null) && (((ref5 = prev[0]) === '.' || ref5 === '?.' || ref5 === '::' || ref5 === '?::') || !prev.spaced && prev[0] === '@') ? 'PROPERTY' : 'IDENTIFIER';
tokenData = {};
if (tag === 'IDENTIFIER' && (indexOf.call(JS_KEYWORDS, id) >= 0 || indexOf.call(COFFEE_KEYWORDS, id) >= 0) && !(this.exportSpecifierList && indexOf.call(COFFEE_KEYWORDS, id) >= 0)) {
tag = id.toUpperCase();
if (tag === 'WHEN' && (ref6 = this.tag(), indexOf.call(LINE_BREAK, ref6) >= 0)) {
2010-09-23 05:14:18 +00:00
tag = 'LEADING_WHEN';
2018-01-31 14:33:17 +00:00
} else if (tag === 'FOR') {
this.seenFor = {
endsLength: this.ends.length
};
2018-01-31 14:33:17 +00:00
} else if (tag === 'UNLESS') {
tag = 'IF';
} else if (tag === 'IMPORT') {
this.seenImport = true;
} else if (tag === 'EXPORT') {
this.seenExport = true;
} else if (indexOf.call(UNARY, tag) >= 0) {
tag = 'UNARY';
} else if (indexOf.call(RELATION, tag) >= 0) {
if (tag !== 'INSTANCEOF' && this.seenFor) {
tag = 'FOR' + tag;
this.seenFor = false;
} else {
2018-01-31 14:33:17 +00:00
tag = 'RELATION';
if (this.value() === '!') {
poppedToken = this.tokens.pop();
tokenData.invert = (ref7 = (ref8 = poppedToken.data) != null ? ref8.original : void 0) != null ? ref7 : poppedToken[1];
}
}
2010-09-23 05:14:18 +00:00
}
2018-01-31 14:33:17 +00:00
} else if (tag === 'IDENTIFIER' && this.seenFor && id === 'from' && isForFrom(prev)) {
tag = 'FORFROM';
this.seenFor = false;
// Throw an error on attempts to use `get` or `set` as keywords, or
// what CoffeeScript would normally interpret as calls to functions named
// `get` or `set`, i.e. `get({foo: function () {}})`.
} else if (tag === 'PROPERTY' && prev) {
if (prev.spaced && (ref9 = prev[0], indexOf.call(CALLABLE, ref9) >= 0) && /^[gs]et$/.test(prev[1]) && this.tokens.length > 1 && ((ref10 = this.tokens[this.tokens.length - 2][0]) !== '.' && ref10 !== '?.' && ref10 !== '@')) {
2018-01-31 14:33:17 +00:00
this.error(`'${prev[1]}' cannot be used as a keyword, or as a function call without parentheses`, prev[2]);
} else if (prev[0] === '.' && this.tokens.length > 1 && (prevprev = this.tokens[this.tokens.length - 2])[0] === 'UNARY' && prevprev[1] === 'new') {
prevprev[0] = 'NEW_TARGET';
} else if (prev[0] === '.' && this.tokens.length > 1 && (prevprev = this.tokens[this.tokens.length - 2])[0] === 'IMPORT' && prevprev[1] === 'import') {
this.seenImport = false;
prevprev[0] = 'IMPORT_META';
2018-01-31 14:33:17 +00:00
} else if (this.tokens.length > 2) {
prevprev = this.tokens[this.tokens.length - 2];
if (((ref11 = prev[0]) === '@' || ref11 === 'THIS') && prevprev && prevprev.spaced && /^[gs]et$/.test(prevprev[1]) && ((ref12 = this.tokens[this.tokens.length - 3][0]) !== '.' && ref12 !== '?.' && ref12 !== '@')) {
2018-01-31 14:33:17 +00:00
this.error(`'${prevprev[1]}' cannot be used as a keyword, or as a function call without parentheses`, prevprev[2]);
}
}
}
if (tag === 'IDENTIFIER' && indexOf.call(RESERVED, id) >= 0 && !inJSXTag) {
this.error(`reserved word '${id}'`, {
length: id.length
});
}
if (!(tag === 'PROPERTY' || this.exportSpecifierList || this.importSpecifierList)) {
if (indexOf.call(COFFEE_ALIASES, id) >= 0) {
alias = id;
2012-04-10 18:57:45 +00:00
id = COFFEE_ALIAS_MAP[id];
tokenData.original = alias;
2012-04-10 18:57:45 +00:00
}
2010-12-23 18:50:52 +00:00
tag = (function() {
2010-11-05 04:04:52 +00:00
switch (id) {
case '!':
return 'UNARY';
case '==':
case '!=':
return 'COMPARE';
case 'true':
case 'false':
return 'BOOL';
case 'break':
case 'continue':
Refactor `Literal` into several subtypes Previously, the parser created `Literal` nodes for many things. This resulted in information loss. Instead of being able to check the node type, we had to use regexes to tell the different types of `Literal`s apart. That was a bit like parsing literals twice: Once in the lexer, and once (or more) in the compiler. It also caused problems, such as `` `this` `` and `this` being indistinguishable (fixes #2009). Instead returning `new Literal` in the grammar, subtypes of it are now returned instead, such as `NumberLiteral`, `StringLiteral` and `IdentifierLiteral`. `new Literal` by itself is only used to represent code chunks that fit no category. (While mentioning `NumberLiteral`, there's also `InfinityLiteral` now, which is a subtype of `NumberLiteral`.) `StringWithInterpolations` has been added as a subtype of `Parens`, and `RegexWithInterpolations` as a subtype of `Call`. This makes it easier for other programs to make use of CoffeeScript's "AST" (nodes). For example, it is now possible to distinguish between `"a #{b} c"` and `"a " + b + " c"`. Fixes #4192. `SuperCall` has been added as a subtype of `Call`. Note, though, that some information is still lost, especially in the lexer. For example, there is no way to distinguish a heredoc from a regular string, or a heregex without interpolations from a regular regex. Binary and octal number literals are indistinguishable from hexadecimal literals. After the new subtypes were added, they were taken advantage of, removing most regexes in nodes.coffee. `SIMPLENUM` (which matches non-hex integers) had to be kept, though, because such numbers need special handling in JavaScript (for example in `1..toString()`). An especially nice hack to get rid of was using `new String()` for the token value for reserved identifiers (to be able to set a property on them which could survive through the parser). Now it's a good old regular string. In range literals, slices, splices and for loop steps when number literals are involved, CoffeeScript can do some optimizations, such as precomputing the value of, say, `5 - 3` (outputting `2` instead of `5 - 3` literally). As a side bonus, this now also works with hexadecimal number literals, such as `0x02`. Finally, this also improves the output of `coffee --nodes`: # Before: $ bin/coffee -ne 'while true "#{a}" break' Block While Value Bool Block Value Parens Block Op + Value """" Value Parens Block Value "a" "break" # After: $ bin/coffee -ne 'while true "#{a}" break' Block While Value BooleanLiteral: true Block Value StringWithInterpolations Block Op + Value StringLiteral: "" Value Parens Block Value IdentifierLiteral: a StatementLiteral: break
2016-01-31 19:24:31 +00:00
case 'debugger':
return 'STATEMENT';
case '&&':
case '||':
return id;
2010-11-05 04:04:52 +00:00
default:
return tag;
}
2010-12-23 18:50:52 +00:00
})();
2010-03-22 01:46:06 +00:00
}
tagToken = this.token(tag, id, {
length: idLength,
data: tokenData
});
if (alias) {
tagToken.origin = [tag, alias, tagToken[2]];
}
if (poppedToken) {
2018-08-21 23:57:00 +00:00
[tagToken[2].first_line, tagToken[2].first_column, tagToken[2].range[0]] = [poppedToken[2].first_line, poppedToken[2].first_column, poppedToken[2].range[0]];
}
2012-04-10 18:57:45 +00:00
if (colon) {
colonOffset = input.lastIndexOf(inJSXTag ? '=' : ':');
colonToken = this.token(':', ':', {
offset: colonOffset
});
if (inJSXTag) { // used by rewriter
colonToken.jsxColon = true;
}
}
if (inJSXTag && tag === 'IDENTIFIER' && prev[0] !== ':') {
this.token(',', ',', {
length: 0,
origin: tagToken,
generated: true
});
2012-04-10 18:57:45 +00:00
}
return input.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 05:55:30 +00: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-03 02:34:34 +00:00
// Matches numbers, including decimals, hex, and exponential notation.
// Be careful not to interfere with ranges in progress.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
numberToken() {
AST: Update with latest changes from master (#5270) * Fix #5213: Update Babel options to restore MINIFY=false (#5214) * CSX namespaced tags and attributes (#5218) * Support namespaces in attributes * Support namespaces in tag names * Support reserved words in CSX boolean properties (fix #5125) * Implement review comments * Build * Revert parser.js * Add debugging information to error message test (#5239) One of the test cases in test/error_messages.coffee fails intermittently in the Node.js ecosystem-testing tool CITGM. In an effort to help debug what's going on when this occurs, this adds more information to the AssertionError message in question. * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Numeric literal separators (#5215) * implement numeric literal separators * add tests * Revert changes to package-lock.json * small regex adjustment * split tests * add comment * Add Node versions to CI * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Update output * Fix style * support bigint literal with separators * un-disallow property access on number literal * Update output * Refactor numeric literal separator tests to be more like the rest of the tests * Add test for numeric property with underscore Co-authored-by: Geoffrey Booth <GeoffreyBooth@users.noreply.github.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> Co-authored-by: Erik Demaine <edemaine@mit.edu> Co-authored-by: Rich Trott <rtrott@gmail.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> Co-authored-by: square <Inve1951@users.noreply.github.com>
2019-12-30 00:55:33 +00:00
var lexedLength, match, number, parsedValue, tag, tokenData;
2012-04-10 18:57:45 +00:00
if (!(match = NUMBER.exec(this.chunk))) {
return 0;
}
number = match[0];
lexedLength = number.length;
switch (false) {
case !/^0[BOX]/.test(number):
this.error(`radix prefix in '${number}' must be lowercase`, {
offset: 1
});
break;
case !/^0\d*[89]/.test(number):
this.error(`decimal literal '${number}' must not be prefixed with '0'`, {
length: lexedLength
});
break;
case !/^0\d+/.test(number):
this.error(`octal literal '${number}' must be prefixed with '0o'`, {
length: lexedLength
});
}
AST: numeric separators, BigInt (#5272) * Revert to more complicated lexing of numbers, as the Number constructor can't handle BigInts or numbers with numeric separators * Add debugging information to error message test (#5239) One of the test cases in test/error_messages.coffee fails intermittently in the Node.js ecosystem-testing tool CITGM. In an effort to help debug what's going on when this occurs, this adds more information to the AssertionError message in question. * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Numeric literal separators (#5215) * implement numeric literal separators * add tests * Revert changes to package-lock.json * small regex adjustment * split tests * add comment * Add Node versions to CI * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Update output * Fix style * support bigint literal with separators * un-disallow property access on number literal * Update output * Refactor numeric literal separator tests to be more like the rest of the tests * Add test for numeric property with underscore Co-authored-by: Geoffrey Booth <GeoffreyBooth@users.noreply.github.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> * Update test style and output * numeric separator parsed value * BigInt AST; parseNumber() Co-authored-by: Geoffrey Booth <GeoffreyBooth@users.noreply.github.com> Co-authored-by: Rich Trott <rtrott@gmail.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> Co-authored-by: square <Inve1951@users.noreply.github.com>
2019-12-30 00:20:43 +00:00
parsedValue = parseNumber(number);
tokenData = {parsedValue};
tag = parsedValue === 2e308 ? 'INFINITY' : 'NUMBER';
if (tag === 'INFINITY') {
tokenData.original = number;
}
this.token(tag, number, {
length: lexedLength,
data: tokenData
});
2011-10-24 18:51:41 +00:00
return lexedLength;
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
}
[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-03 02:34:34 +00:00
// Matches strings, including multiline strings, as well as heredocs, with or without
// interpolation.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
stringToken() {
var attempt, delimiter, doc, end, heredoc, i, indent, match, prev, quote, ref, regex, token, tokens;
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
[quote] = STRING_START.exec(this.chunk) || [];
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
if (!quote) {
return 0;
}
[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-03 02:34:34 +00:00
// If the preceding token is `from` and this is an import or export statement,
// properly tag the `from`.
prev = this.prev();
if (prev && this.value() === 'from' && (this.seenImport || this.seenExport)) {
prev[0] = 'FROM';
Support import and export of ES2015 modules (#4300) This pull request adds support for ES2015 modules, by recognizing `import` and `export` statements. The following syntaxes are supported, based on the MDN [import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) and [export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) pages: ```js import "module-name" import defaultMember from "module-name" import * as name from "module-name" import { } from "module-name" import { member } from "module-name" import { member as alias } from "module-name" import { member1, member2 as alias2, … } from "module-name" import defaultMember, * as name from "module-name" import defaultMember, { … } from "module-name" export default expression export class name export { } export { name } export { name as exportedName } export { name as default } export { name1, name2 as exportedName2, name3 as default, … } export * from "module-name" export { … } from "module-name" ``` As a subsitute for ECMAScript’s `export var name = …` and `export function name {}`, CoffeeScript also supports: ```js export name = … ``` CoffeeScript also supports optional commas within `{ … }`. This PR converts the supported `import` and `export` statements into ES2015 `import` and `export` statements; it **does not resolve the modules**. So any CoffeeScript with `import` or `export` statements will be output as ES2015, and will need to be transpiled by another tool such as Babel before it can be used in a browser. We will need to add a warning to the documentation explaining this. This should be fully backwards-compatible, as `import` and `export` were previously reserved keywords. No flags are used. There are extensive tests included, though because no current JavaScript runtime supports `import` or `export`, the tests compare strings of what the compiled CoffeeScript output is against what the expected ES2015 should be. I also conducted two more elaborate tests: * I forked the [ember-piqu](https://github.com/pauc/piqu-ember) project, which was an Ember CLI app that used ember-cli-coffeescript and [ember-cli-coffees6](https://github.com/alexspeller/ember-cli-coffees6) (which adds “support” for `import`/`export` by wrapping such statements in backticks before passing the result to the CoffeeScript compiler). I removed `ember-cli-coffees6` and replaced the CoffeeScript compiler used in the build chain with this code, and the app built without errors. [Demo here.](https://github.com/GeoffreyBooth/coffeescript-modules-test-piqu) * I also forked the [CoffeeScript version of Meteor’s Todos example app](https://github.com/meteor/todos/tree/coffeescript), and replaced all of its `require` statements with the `import` and `export` statements from the original ES2015 version of the app on its `master` branch. I then updated the `coffeescript` Meteor package in the app to use this new code, and again the app builds without errors. [Demo here.](https://github.com/GeoffreyBooth/coffeescript-modules-test-meteor-todos) The discussion history for this work started [here](https://github.com/jashkenas/coffeescript/pull/4160) and continued [here](https://github.com/GeoffreyBooth/coffeescript/pull/2). @lydell provided guidance, and @JimPanic and @rattrayalex contributed essential code.
2016-09-14 18:46:05 +00:00
}
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
regex = (function() {
switch (quote) {
case "'":
return STRING_SINGLE;
case '"':
return STRING_DOUBLE;
case "'''":
return HEREDOC_SINGLE;
case '"""':
return HEREDOC_DOUBLE;
}
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
})();
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
({
tokens,
index: end
} = this.matchWithInterpolations(regex, quote));
heredoc = quote.length === 3;
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
if (heredoc) {
[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-03 02:34:34 +00:00
// Find the smallest indentation. It will be removed from all lines later.
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
indent = null;
doc = ((function() {
var j, len, results;
results = [];
for (i = j = 0, len = tokens.length; j < len; i = ++j) {
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
token = tokens[i];
if (token[0] === 'NEOSTRING') {
results.push(token[1]);
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
}
}
return results;
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
})()).join('#{}');
while (match = HEREDOC_INDENT.exec(doc)) {
attempt = match[1];
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
if (indent === null || (0 < (ref = attempt.length) && ref < indent.length)) {
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
indent = attempt;
}
}
}
delimiter = quote.charAt(0);
this.mergeInterpolationTokens(tokens, {
quote,
indent,
endOffset: end
}, (value) => {
return this.validateUnicodeCodePointEscapes(value, {
delimiter: quote
});
});
if (this.atJSXTag()) {
this.token(',', ',', {
length: 0,
origin: this.prev,
generated: true
});
}
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
return end;
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
}
[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-03 02:34:34 +00:00
// Matches and consumes comments. The comments are taken out of the token
// stream and saved for later, to be reinserted into the output after
// everything has been parsed and the JavaScript code generated.
commentToken(chunk = this.chunk, {heregex, returnCommentTokens = false, offsetInChunk = 0} = {}) {
var commentAttachment, commentAttachments, commentWithSurroundingWhitespace, content, contents, getIndentSize, hasSeenFirstCommentLine, hereComment, hereLeadingWhitespace, hereTrailingWhitespace, i, indentSize, leadingNewline, leadingNewlineOffset, leadingNewlines, leadingWhitespace, length, lineComment, match, matchIllegal, noIndent, nonInitial, placeholderToken, precededByBlankLine, precedingNonCommentLines, prev;
[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-03 02:34:34 +00:00
if (!(match = chunk.match(COMMENT))) {
2012-04-10 18:57:45 +00:00
return 0;
}
[commentWithSurroundingWhitespace, hereLeadingWhitespace, hereComment, hereTrailingWhitespace, lineComment] = match;
[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-03 02:34:34 +00:00
contents = null;
// Does this comment follow code on the same line?
leadingNewline = /^\s*\n+\s*#/.test(commentWithSurroundingWhitespace);
if (hereComment) {
matchIllegal = HERECOMMENT_ILLEGAL.exec(hereComment);
[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-03 02:34:34 +00:00
if (matchIllegal) {
this.error(`block comments cannot contain ${matchIllegal[0]}`, {
offset: '###'.length + matchIllegal.index,
[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-03 02:34:34 +00:00
length: matchIllegal[0].length
});
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00: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-03 02:34:34 +00:00
// Parse indentation or outdentation as if this block comment didnt exist.
chunk = chunk.replace(`###${hereComment}###`, '');
[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-03 02:34:34 +00:00
// Remove leading newlines, like `Rewriter::removeLeadingNewlines`, to
// avoid the creation of unwanted `TERMINATOR` tokens.
chunk = chunk.replace(/^\n+/, '');
this.lineToken({chunk});
[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-03 02:34:34 +00:00
// Pull out the ###-style comments content, and format it.
content = hereComment;
contents = [
{
content,
length: commentWithSurroundingWhitespace.length - hereLeadingWhitespace.length - hereTrailingWhitespace.length,
leadingWhitespace: hereLeadingWhitespace
}
];
[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-03 02:34:34 +00:00
} else {
// The `COMMENT` regex captures successive line comments as one token.
// Remove any leading newlines before the first comment, but preserve
// blank lines between line comments.
leadingNewlines = '';
content = lineComment.replace(/^(\n*)/, function(leading) {
leadingNewlines = leading;
return '';
});
precedingNonCommentLines = '';
hasSeenFirstCommentLine = false;
contents = content.split('\n').map(function(line, index) {
var comment, leadingWhitespace;
if (!(line.indexOf('#') > -1)) {
precedingNonCommentLines += `\n${line}`;
return;
}
leadingWhitespace = '';
content = line.replace(/^([ |\t]*)#/, function(_, whitespace) {
leadingWhitespace = whitespace;
return '';
});
comment = {
content,
length: '#'.length + content.length,
leadingWhitespace: `${!hasSeenFirstCommentLine ? leadingNewlines : ''}${precedingNonCommentLines}${leadingWhitespace}`,
precededByBlankLine: !!precedingNonCommentLines
};
hasSeenFirstCommentLine = true;
precedingNonCommentLines = '';
return comment;
}).filter(function(comment) {
return comment;
});
[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-03 02:34:34 +00:00
}
getIndentSize = function({leadingWhitespace, nonInitial}) {
var lastNewlineIndex;
lastNewlineIndex = leadingWhitespace.lastIndexOf('\n');
if ((hereComment != null) || !nonInitial) {
if (!(lastNewlineIndex > -1)) {
return null;
}
} else {
if (lastNewlineIndex == null) {
lastNewlineIndex = -1;
}
}
return leadingWhitespace.length - 1 - lastNewlineIndex;
};
[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-03 02:34:34 +00:00
commentAttachments = (function() {
var j, len, results;
results = [];
for (i = j = 0, len = contents.length; j < len; i = ++j) {
({content, length, leadingWhitespace, precededByBlankLine} = contents[i]);
nonInitial = i !== 0;
leadingNewlineOffset = nonInitial ? 1 : 0;
offsetInChunk += leadingNewlineOffset + leadingWhitespace.length;
indentSize = getIndentSize({leadingWhitespace, nonInitial});
noIndent = (indentSize == null) || indentSize === -1;
commentAttachment = {
content,
here: hereComment != null,
newLine: leadingNewline || nonInitial, // Line comments after the first one start new lines, by definition.
locationData: this.makeLocationData({offsetInChunk, length}),
precededByBlankLine,
indentSize,
indented: !noIndent && indentSize > this.indent,
outdented: !noIndent && indentSize < this.indent
};
if (heregex) {
commentAttachment.heregex = true;
}
offsetInChunk += length;
results.push(commentAttachment);
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00: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-03 02:34:34 +00:00
return results;
}).call(this);
[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-03 02:34:34 +00:00
prev = this.prev();
if (!prev) {
// If theres no previous token, create a placeholder token to attach
// this comment to; and follow with a newline.
commentAttachments[0].newLine = true;
this.lineToken({
chunk: this.chunk.slice(commentWithSurroundingWhitespace.length),
offset: commentWithSurroundingWhitespace.length // Set the indent.
});
placeholderToken = this.makeToken('JS', '', {
offset: commentWithSurroundingWhitespace.length,
generated: true
});
[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-03 02:34:34 +00:00
placeholderToken.comments = commentAttachments;
this.tokens.push(placeholderToken);
this.newlineToken(commentWithSurroundingWhitespace.length);
[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-03 02:34:34 +00:00
} else {
attachCommentsToNode(commentAttachments, prev);
}
if (returnCommentTokens) {
return commentAttachments;
}
return commentWithSurroundingWhitespace.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 05:55:30 +00: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-03 02:34:34 +00:00
// Matches JavaScript interpolated directly into the source via backticks.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
jsToken() {
var length, match, matchedHere, script;
if (!(this.chunk.charAt(0) === '`' && (match = (matchedHere = HERE_JSTOKEN.exec(this.chunk)) || JSTOKEN.exec(this.chunk)))) {
return 0;
}
[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-03 02:34:34 +00:00
// Convert escaped backticks to backticks, and escaped backslashes
// just before escaped backticks to backslashes
script = match[1];
({length} = match[0]);
this.token('JS', script, {
length,
data: {
here: !!matchedHere
}
});
return 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 05:55:30 +00: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-03 02:34:34 +00:00
// Matches regular expression literals, as well as multiline extended ones.
// Lexing regular expressions is difficult to distinguish from division, so we
// borrow some basic heuristics from JavaScript and Ruby.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
regexToken() {
var body, closed, comment, commentIndex, commentOpts, commentTokens, comments, delimiter, end, flags, fullMatch, index, leadingWhitespace, match, matchedComment, origin, prev, ref, ref1, regex, tokens;
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
switch (false) {
case !(match = REGEX_ILLEGAL.exec(this.chunk)):
this.error(`regular expressions cannot begin with ${match[2]}`, {
offset: match.index + match[1].length
});
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
break;
case !(match = this.matchWithInterpolations(HEREGEX, '///')):
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
({tokens, index} = match);
comments = [];
while (matchedComment = HEREGEX_COMMENT.exec(this.chunk.slice(0, index))) {
({
index: commentIndex
} = matchedComment);
[fullMatch, leadingWhitespace, comment] = matchedComment;
comments.push({
comment,
offsetInChunk: commentIndex + leadingWhitespace.length
});
}
commentTokens = flatten((function() {
var j, len, results;
results = [];
[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-03 02:34:34 +00:00
for (j = 0, len = comments.length; j < len; j++) {
commentOpts = comments[j];
results.push(this.commentToken(commentOpts.comment, Object.assign(commentOpts, {
heregex: true,
returnCommentTokens: true
})));
[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-03 02:34:34 +00:00
}
return results;
}).call(this));
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
break;
case !(match = REGEX.exec(this.chunk)):
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
[regex, body, closed] = match;
this.validateEscapes(body, {
isRegex: true,
offsetInChunk: 1
});
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
index = regex.length;
prev = this.prev();
Fix #3410, #3182: Allow regex to start with space or = A regex may not follow a specific set of tokens. These were already known before in the `NOT_REGEX` and `NOT_SPACED_REGEX` arrays. (However, I've refactored them to be more correct and to add a few missing tokens). In all other cases (except after a spaced callable) a slash is the start of a regex, and may now start with a space or an equals sign. It’s really that simple! A slash after a spaced callable is the only ambigous case. We cannot know if that's division or function application with a regex as the argument. The spacing determines which is which: Space on both sides: - `a / b/i` -> `a / b / i` - `a /= b/i` -> `a /= b / i` No spaces: - `a/b/i` -> `a / b / i` - `a/=b/i` -> `a /= b / i` Space on the right side: - `a/ b/i` -> `a / b / i` - `a/= b/i` -> `a /= b / i` Space on the left side: - `a /b/i` -> `a(/b/i)` - `a /=b/i` -> `a(/=b/i)` The last case used to compile to `a /= b / i`, but that has been changed to be consistent with the `/` operator. The last case really looks like a regex, so it should be parsed as one. Moreover, you may now also space the `/` and `/=` operators with other whitespace characters than a space (such as tabs and non-breaking spaces) for consistency. Lastly, unclosed regexes are now reported as such, instead of generating some other confusing error message. It should perhaps also be noted that apart from escaping (such as `a /\ b/`) you may now also use parentheses to disambiguate division and regex: `a (/ b/)`. See https://github.com/jashkenas/coffeescript/issues/3182#issuecomment-26688427.
2015-01-10 00:48:00 +00:00
if (prev) {
if (prev.spaced && (ref = prev[0], indexOf.call(CALLABLE, ref) >= 0)) {
Fix #3410, #3182: Allow regex to start with space or = A regex may not follow a specific set of tokens. These were already known before in the `NOT_REGEX` and `NOT_SPACED_REGEX` arrays. (However, I've refactored them to be more correct and to add a few missing tokens). In all other cases (except after a spaced callable) a slash is the start of a regex, and may now start with a space or an equals sign. It’s really that simple! A slash after a spaced callable is the only ambigous case. We cannot know if that's division or function application with a regex as the argument. The spacing determines which is which: Space on both sides: - `a / b/i` -> `a / b / i` - `a /= b/i` -> `a /= b / i` No spaces: - `a/b/i` -> `a / b / i` - `a/=b/i` -> `a /= b / i` Space on the right side: - `a/ b/i` -> `a / b / i` - `a/= b/i` -> `a /= b / i` Space on the left side: - `a /b/i` -> `a(/b/i)` - `a /=b/i` -> `a(/=b/i)` The last case used to compile to `a /= b / i`, but that has been changed to be consistent with the `/` operator. The last case really looks like a regex, so it should be parsed as one. Moreover, you may now also space the `/` and `/=` operators with other whitespace characters than a space (such as tabs and non-breaking spaces) for consistency. Lastly, unclosed regexes are now reported as such, instead of generating some other confusing error message. It should perhaps also be noted that apart from escaping (such as `a /\ b/`) you may now also use parentheses to disambiguate division and regex: `a (/ b/)`. See https://github.com/jashkenas/coffeescript/issues/3182#issuecomment-26688427.
2015-01-10 00:48:00 +00:00
if (!closed || POSSIBLY_DIVISION.test(regex)) {
return 0;
}
2018-01-31 14:33:17 +00:00
} else if (ref1 = prev[0], indexOf.call(NOT_REGEX, ref1) >= 0) {
return 0;
Fix #3410, #3182: Allow regex to start with space or = A regex may not follow a specific set of tokens. These were already known before in the `NOT_REGEX` and `NOT_SPACED_REGEX` arrays. (However, I've refactored them to be more correct and to add a few missing tokens). In all other cases (except after a spaced callable) a slash is the start of a regex, and may now start with a space or an equals sign. It’s really that simple! A slash after a spaced callable is the only ambigous case. We cannot know if that's division or function application with a regex as the argument. The spacing determines which is which: Space on both sides: - `a / b/i` -> `a / b / i` - `a /= b/i` -> `a /= b / i` No spaces: - `a/b/i` -> `a / b / i` - `a/=b/i` -> `a /= b / i` Space on the right side: - `a/ b/i` -> `a / b / i` - `a/= b/i` -> `a /= b / i` Space on the left side: - `a /b/i` -> `a(/b/i)` - `a /=b/i` -> `a(/=b/i)` The last case used to compile to `a /= b / i`, but that has been changed to be consistent with the `/` operator. The last case really looks like a regex, so it should be parsed as one. Moreover, you may now also space the `/` and `/=` operators with other whitespace characters than a space (such as tabs and non-breaking spaces) for consistency. Lastly, unclosed regexes are now reported as such, instead of generating some other confusing error message. It should perhaps also be noted that apart from escaping (such as `a /\ b/`) you may now also use parentheses to disambiguate division and regex: `a (/ b/)`. See https://github.com/jashkenas/coffeescript/issues/3182#issuecomment-26688427.
2015-01-10 00:48:00 +00:00
}
}
if (!closed) {
this.error('missing / (unclosed regex)');
2012-04-10 18:57:45 +00:00
}
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
break;
default:
return 0;
}
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
[flags] = REGEX_FLAGS.exec(this.chunk.slice(index));
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
end = index + flags.length;
origin = this.makeToken('REGEX', null, {
length: end
});
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
switch (false) {
case !!VALID_FLAGS.test(flags):
this.error(`invalid regular expression flags ${flags}`, {
offset: index,
length: flags.length
});
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
break;
case !(regex || tokens.length === 1):
delimiter = body ? '/' : '///';
if (body == null) {
body = tokens[0][1];
}
this.validateUnicodeCodePointEscapes(body, {delimiter});
this.token('REGEX', `/${body}/${flags}`, {
length: end,
origin,
data: {delimiter}
});
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
break;
default:
this.token('REGEX_START', '(', {
length: 0,
origin,
generated: true
});
this.token('IDENTIFIER', 'RegExp', {
length: 0,
generated: true
});
this.token('CALL_START', '(', {
length: 0,
generated: true
});
this.mergeInterpolationTokens(tokens, {
double: true,
heregex: {flags},
endOffset: end - flags.length,
quote: '///'
}, (str) => {
return this.validateUnicodeCodePointEscapes(str, {delimiter});
});
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
if (flags) {
this.token(',', ',', {
offset: index - 1,
length: 0,
generated: true
});
this.token('STRING', '"' + flags + '"', {
offset: index,
length: flags.length
});
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
}
this.token(')', ')', {
offset: end,
length: 0,
generated: true
});
this.token('REGEX_END', ')', {
offset: end,
length: 0,
generated: true
});
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
}
// Explicitly attach any heregex comments to the REGEX/REGEX_END token.
if (commentTokens != null ? commentTokens.length : void 0) {
addTokenData(this.tokens[this.tokens.length - 1], {
heregexCommentTokens: commentTokens
});
}
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
return end;
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
}
[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-03 02:34:34 +00:00
// Matches newlines, indents, and outdents, and determines which is which.
// If we can detect that the current line is continued onto the next line,
// then the newline is suppressed:
// elements
// .each( ... )
// .map( ... )
// Keeps track of the level of indentation, because a single outdent token
// can close multiple indents, so we need to know how far in we happen to be.
lineToken({chunk = this.chunk, offset = 0} = {}) {
var backslash, diff, endsContinuationLineIndentation, indent, match, minLiteralLength, newIndentLiteral, noNewlines, prev, ref, size;
[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-03 02:34:34 +00:00
if (!(match = MULTI_DENT.exec(chunk))) {
2012-04-10 18:57:45 +00:00
return 0;
}
indent = match[0];
2018-01-28 10:38:39 +00:00
prev = this.prev();
2018-02-09 05:11:11 +00:00
backslash = (prev != null ? prev[0] : void 0) === '\\';
if (!((backslash || ((ref = this.seenFor) != null ? ref.endsLength : void 0) < this.ends.length) && this.seenFor)) {
2018-01-28 10:38:39 +00:00
this.seenFor = false;
}
2018-02-09 05:11:11 +00:00
if (!((backslash && this.seenImport) || this.importSpecifierList)) {
this.seenImport = false;
}
2018-02-09 05:11:11 +00:00
if (!((backslash && this.seenExport) || this.exportSpecifierList)) {
this.seenExport = false;
}
2010-09-23 05:14:18 +00:00
size = indent.length - 1 - indent.lastIndexOf('\n');
2010-10-25 18:56:02 +00:00
noNewlines = this.unfinished();
newIndentLiteral = size > 0 ? indent.slice(-size) : '';
if (!/^(.?)\1*$/.exec(newIndentLiteral)) {
this.error('mixed indentation', {
offset: indent.length
});
return indent.length;
}
minLiteralLength = Math.min(newIndentLiteral.length, this.indentLiteral.length);
if (newIndentLiteral.slice(0, minLiteralLength) !== this.indentLiteral.slice(0, minLiteralLength)) {
this.error('indentation mismatch', {
offset: indent.length
});
return indent.length;
}
if (size - this.continuationLineAdditionalIndent === this.indent) {
if (noNewlines) {
this.suppressNewlines();
} else {
this.newlineToken(offset);
}
return indent.length;
}
if (size > this.indent) {
if (noNewlines) {
2018-02-18 00:57:49 +00:00
if (!backslash) {
this.continuationLineAdditionalIndent = size - this.indent;
}
if (this.continuationLineAdditionalIndent) {
prev.continuationLineIndent = this.indent + this.continuationLineAdditionalIndent;
2018-02-18 00:57:49 +00:00
}
this.suppressNewlines();
return indent.length;
}
if (!this.tokens.length) {
this.baseIndent = this.indent = size;
this.indentLiteral = newIndentLiteral;
return indent.length;
}
diff = size - this.indent + this.outdebt;
this.token('INDENT', diff, {
offset: offset + indent.length - size,
length: size
});
this.indents.push(diff);
this.ends.push({
tag: 'OUTDENT'
});
this.outdebt = this.continuationLineAdditionalIndent = 0;
2014-01-22 18:30:13 +00:00
this.indent = size;
this.indentLiteral = newIndentLiteral;
2018-01-31 14:33:17 +00:00
} else if (size < this.baseIndent) {
this.error('missing indentation', {
offset: offset + indent.length
2018-01-31 14:33:17 +00:00
});
} else {
endsContinuationLineIndentation = this.continuationLineAdditionalIndent > 0;
this.continuationLineAdditionalIndent = 0;
this.outdentToken({
moveOut: this.indent - size,
noNewlines,
outdentLength: indent.length,
offset,
indentSize: size,
endsContinuationLineIndentation
});
}
return indent.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 05:55:30 +00: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-03 02:34:34 +00:00
// Record an outdent token or multiple tokens, if we happen to be moving back
// inwards past several recorded indents. Sets new @indent value.
outdentToken({moveOut, noNewlines, outdentLength = 0, offset = 0, indentSize, endsContinuationLineIndentation}) {
var decreasedIndent, dent, lastIndent, ref, terminatorToken;
2014-01-22 18:30:13 +00:00
decreasedIndent = this.indent - moveOut;
while (moveOut > 0) {
2014-01-22 18:30:13 +00:00
lastIndent = this.indents[this.indents.length - 1];
if (!lastIndent) {
this.outdebt = moveOut = 0;
2018-01-31 14:33:17 +00:00
} else if (this.outdebt && moveOut <= this.outdebt) {
this.outdebt -= moveOut;
moveOut = 0;
} else {
2018-01-31 14:33:17 +00:00
dent = this.indents.pop() + this.outdebt;
if (outdentLength && (ref = this.chunk[outdentLength], indexOf.call(INDENTABLE_CLOSERS, ref) >= 0)) {
decreasedIndent -= dent - moveOut;
moveOut = dent;
2014-01-22 18:30:13 +00:00
}
2018-01-31 14:33:17 +00:00
this.outdebt = 0;
// pair might call outdentToken, so preserve decreasedIndent
this.pair('OUTDENT');
this.token('OUTDENT', moveOut, {
length: outdentLength,
indentSize: indentSize + moveOut - dent
});
2018-01-31 14:33:17 +00:00
moveOut -= dent;
}
}
2012-04-10 18:57:45 +00:00
if (dent) {
this.outdebt -= moveOut;
}
this.suppressSemicolons();
if (!(this.tag() === 'TERMINATOR' || noNewlines)) {
terminatorToken = this.token('TERMINATOR', '\n', {
offset: offset + outdentLength,
length: 0
});
if (endsContinuationLineIndentation) {
terminatorToken.endsContinuationLineIndentation = {
preContinuationLineIndent: this.indent
};
}
}
this.indent = decreasedIndent;
this.indentLiteral = this.indentLiteral.slice(0, decreasedIndent);
return this;
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
}
[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-03 02:34:34 +00:00
// Matches and consumes non-meaningful whitespace. Tag the previous token
// as being “spaced”, because there are some cases where it makes a difference.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
whitespaceToken() {
var match, nline, prev;
if (!((match = WHITESPACE.exec(this.chunk)) || (nline = this.chunk.charAt(0) === '\n'))) {
return 0;
}
prev = this.prev();
2012-04-10 18:57:45 +00:00
if (prev) {
prev[match ? 'spaced' : 'newLine'] = true;
}
if (match) {
return match[0].length;
} else {
return 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 05:55:30 +00: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-03 02:34:34 +00:00
// Generate a newline token. Consecutive newlines get merged together.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
newlineToken(offset) {
this.suppressSemicolons();
2012-04-10 18:57:45 +00:00
if (this.tag() !== 'TERMINATOR') {
this.token('TERMINATOR', '\n', {
offset,
length: 0
});
2012-04-10 18:57:45 +00:00
}
return this;
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
}
[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-03 02:34:34 +00:00
// Use a `\` at a line-ending to suppress the newline.
// The slash is removed here once its job is done.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
suppressNewlines() {
[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-03 02:34:34 +00:00
var prev;
prev = this.prev();
if (prev[1] === '\\') {
if (prev.comments && this.tokens.length > 1) {
// `@tokens.length` should be at least 2 (some code, then `\`).
// If something puts a `\` after nothing, they deserve to lose any
// comments that trail it.
attachCommentsToNode(prev.comments, this.tokens[this.tokens.length - 2]);
}
2012-04-10 18:57:45 +00:00
this.tokens.pop();
}
return this;
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
}
jsxToken() {
var afterTag, end, endToken, firstChar, fullId, fullTagName, id, input, j, jsxTag, len, match, offset, openingTagToken, prev, prevChar, properties, property, ref, tagToken, token, tokens;
firstChar = this.chunk[0];
// Check the previous token to detect if attribute is spread.
prevChar = this.tokens.length > 0 ? this.tokens[this.tokens.length - 1][0] : '';
if (firstChar === '<') {
match = JSX_IDENTIFIER.exec(this.chunk.slice(1)) || JSX_FRAGMENT_IDENTIFIER.exec(this.chunk.slice(1));
[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-03 02:34:34 +00:00
// Not the right hand side of an unspaced comparison (i.e. `a<b`).
if (!(match && (this.jsxDepth > 0 || !(prev = this.prev()) || prev.spaced || (ref = prev[0], indexOf.call(COMPARABLE_LEFT_SIDE, ref) < 0)))) {
return 0;
}
[input, id] = match;
fullId = id;
if (indexOf.call(id, '.') >= 0) {
[id, ...properties] = id.split('.');
} else {
properties = [];
}
tagToken = this.token('JSX_TAG', id, {
length: id.length + 1,
data: {
openingBracketToken: this.makeToken('<', '<'),
tagNameToken: this.makeToken('IDENTIFIER', id, {
offset: 1
})
}
});
offset = id.length + 1;
for (j = 0, len = properties.length; j < len; j++) {
property = properties[j];
this.token('.', '.', {offset});
offset += 1;
this.token('PROPERTY', property, {offset});
offset += property.length;
}
this.token('CALL_START', '(', {
generated: true
});
this.token('[', '[', {
generated: true
});
this.ends.push({
tag: '/>',
origin: tagToken,
name: id,
properties
});
this.jsxDepth++;
return fullId.length + 1;
} else if (jsxTag = this.atJSXTag()) {
if (this.chunk.slice(0, 2) === '/>') { // Self-closing tag.
2018-01-31 14:33:17 +00:00
this.pair('/>');
this.token(']', ']', {
length: 2,
generated: true
});
this.token('CALL_END', ')', {
length: 2,
generated: true,
data: {
selfClosingSlashToken: this.makeToken('/', '/'),
closingBracketToken: this.makeToken('>', '>', {
offset: 1
})
}
});
this.jsxDepth--;
2018-01-31 14:33:17 +00:00
return 2;
} else if (firstChar === '{') {
if (prevChar === ':') {
// This token represents the start of a JSX attribute value
// thats an expression (e.g. the `{b}` in `<div a={b} />`).
// Our grammar represents the beginnings of expressions as `(`
// tokens, so make this into a `(` token that displays as `{`.
token = this.token('(', '{');
this.jsxObjAttribute[this.jsxDepth] = false;
// tag attribute name as JSX
addTokenData(this.tokens[this.tokens.length - 3], {
jsx: true
});
} else {
2018-01-31 14:33:17 +00:00
token = this.token('{', '{');
this.jsxObjAttribute[this.jsxDepth] = true;
}
2018-01-31 14:33:17 +00:00
this.ends.push({
tag: '}',
origin: token
});
return 1;
} else if (firstChar === '>') { // end of opening tag
({
// Ignore terminators inside a tag.
origin: openingTagToken
} = this.pair('/>')); // As if the current tag was self-closing.
this.token(']', ']', {
generated: true,
data: {
closingBracketToken: this.makeToken('>', '>')
}
});
this.token(',', 'JSX_COMMA', {
generated: true
});
2018-01-31 14:33:17 +00:00
({
tokens,
index: end
} = this.matchWithInterpolations(INSIDE_JSX, '>', '</', JSX_INTERPOLATION));
this.mergeInterpolationTokens(tokens, {
endOffset: end,
jsx: true
}, (value) => {
return this.validateUnicodeCodePointEscapes(value, {
2018-01-31 14:33:17 +00:00
delimiter: '>'
});
});
match = JSX_IDENTIFIER.exec(this.chunk.slice(end)) || JSX_FRAGMENT_IDENTIFIER.exec(this.chunk.slice(end));
if (!match || match[1] !== `${jsxTag.name}${((function() {
var k, len1, ref1, results;
ref1 = jsxTag.properties;
results = [];
for (k = 0, len1 = ref1.length; k < len1; k++) {
property = ref1[k];
results.push(`.${property}`);
}
return results;
})()).join('')}`) {
this.error(`expected corresponding JSX closing tag for ${jsxTag.name}`, jsxTag.origin.data.tagNameToken[2]);
2018-01-31 14:33:17 +00:00
}
[, fullTagName] = match;
afterTag = end + fullTagName.length;
2018-01-31 14:33:17 +00:00
if (this.chunk[afterTag] !== '>') {
this.error("missing closing > after tag name", {
offset: afterTag,
length: 1
});
}
// -2/+2 for the opening `</` and +1 for the closing `>`.
endToken = this.token('CALL_END', ')', {
offset: end - 2,
length: fullTagName.length + 3,
generated: true,
data: {
closingTagOpeningBracketToken: this.makeToken('<', '<', {
offset: end - 2
}),
closingTagSlashToken: this.makeToken('/', '/', {
offset: end - 1
}),
// TODO: individual tokens for complex tag name? eg < / A . B >
closingTagNameToken: this.makeToken('IDENTIFIER', fullTagName, {
offset: end
}),
closingTagClosingBracketToken: this.makeToken('>', '>', {
offset: end + fullTagName.length
})
}
});
// make the closing tag location data more easily accessible to the grammar
addTokenData(openingTagToken, endToken.data);
this.jsxDepth--;
2018-01-31 14:33:17 +00:00
return afterTag + 1;
} else {
2018-01-31 14:33:17 +00:00
return 0;
}
} else if (this.atJSXTag(1)) {
2018-01-31 14:33:17 +00:00
if (firstChar === '}') {
this.pair(firstChar);
if (this.jsxObjAttribute[this.jsxDepth]) {
2018-01-31 14:33:17 +00:00
this.token('}', '}');
this.jsxObjAttribute[this.jsxDepth] = false;
} else {
this.token(')', '}');
}
this.token(',', ',', {
generated: true
});
2018-01-31 14:33:17 +00:00
return 1;
} else {
return 0;
}
2018-01-31 14:33:17 +00:00
} else {
return 0;
}
}
atJSXTag(depth = 0) {
var i, last, ref;
if (this.jsxDepth === 0) {
return false;
}
i = this.ends.length - 1;
[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-03 02:34:34 +00:00
while (((ref = this.ends[i]) != null ? ref.tag : void 0) === 'OUTDENT' || depth-- > 0) { // Ignore indents.
i--;
}
last = this.ends[i];
return (last != null ? last.tag : void 0) === '/>' && last;
}
[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-03 02:34:34 +00:00
// We treat all other single characters as a token. E.g.: `( ) , . !`
// Multi-character operators are also literal tokens, so that Jison can assign
// the proper order of operations. There are some symbols that we tag specially
// here. `;` and newlines are both treated as a `TERMINATOR`, we distinguish
// parentheses that indicate a method call from regular parentheses, 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 05:55:30 +00:00
literalToken() {
var match, message, origin, prev, ref, ref1, ref2, ref3, ref4, ref5, skipToken, tag, token, value;
2010-10-05 14:31:48 +00:00
if (match = OPERATOR.exec(this.chunk)) {
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
[value] = match;
2012-04-10 18:57:45 +00:00
if (CODE.test(value)) {
this.tagParameters();
}
2010-09-23 05:14:18 +00:00
} else {
value = this.chunk.charAt(0);
}
tag = value;
prev = this.prev();
if (prev && indexOf.call(['=', ...COMPOUND_ASSIGN], value) >= 0) {
skipToken = false;
if (value === '=' && ((ref = prev[1]) === '||' || ref === '&&') && !prev.spaced) {
2010-10-05 14:31:48 +00:00
prev[0] = 'COMPOUND_ASSIGN';
prev[1] += '=';
if ((ref1 = prev.data) != null ? ref1.original : void 0) {
prev.data.original += '=';
}
prev[2].range = [prev[2].range[0], prev[2].range[1] + 1];
prev[2].last_column += 1;
prev[2].last_column_exclusive += 1;
prev = this.tokens[this.tokens.length - 2];
skipToken = true;
}
if (prev && prev[0] !== 'PROPERTY') {
origin = (ref2 = prev.origin) != null ? ref2 : prev;
message = isUnassignable(prev[1], origin[1]);
if (message) {
this.error(message, origin[2]);
}
}
if (skipToken) {
return value.length;
2010-07-25 05:36:50 +00:00
}
2010-07-25 05:23:37 +00:00
}
if (value === '(' && (prev != null ? prev[0] : void 0) === 'IMPORT') {
prev[0] = 'DYNAMIC_IMPORT';
}
if (value === '{' && this.seenImport) {
this.importSpecifierList = true;
2018-01-31 14:33:17 +00:00
} else if (this.importSpecifierList && value === '}') {
this.importSpecifierList = false;
} else if (value === '{' && (prev != null ? prev[0] : void 0) === 'EXPORT') {
this.exportSpecifierList = true;
} else if (this.exportSpecifierList && value === '}') {
this.exportSpecifierList = false;
}
if (value === ';') {
if (ref3 = prev != null ? prev[0] : void 0, indexOf.call(['=', ...UNFINISHED], ref3) >= 0) {
this.error('unexpected ;');
}
Support import and export of ES2015 modules (#4300) This pull request adds support for ES2015 modules, by recognizing `import` and `export` statements. The following syntaxes are supported, based on the MDN [import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) and [export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) pages: ```js import "module-name" import defaultMember from "module-name" import * as name from "module-name" import { } from "module-name" import { member } from "module-name" import { member as alias } from "module-name" import { member1, member2 as alias2, … } from "module-name" import defaultMember, * as name from "module-name" import defaultMember, { … } from "module-name" export default expression export class name export { } export { name } export { name as exportedName } export { name as default } export { name1, name2 as exportedName2, name3 as default, … } export * from "module-name" export { … } from "module-name" ``` As a subsitute for ECMAScript’s `export var name = …` and `export function name {}`, CoffeeScript also supports: ```js export name = … ``` CoffeeScript also supports optional commas within `{ … }`. This PR converts the supported `import` and `export` statements into ES2015 `import` and `export` statements; it **does not resolve the modules**. So any CoffeeScript with `import` or `export` statements will be output as ES2015, and will need to be transpiled by another tool such as Babel before it can be used in a browser. We will need to add a warning to the documentation explaining this. This should be fully backwards-compatible, as `import` and `export` were previously reserved keywords. No flags are used. There are extensive tests included, though because no current JavaScript runtime supports `import` or `export`, the tests compare strings of what the compiled CoffeeScript output is against what the expected ES2015 should be. I also conducted two more elaborate tests: * I forked the [ember-piqu](https://github.com/pauc/piqu-ember) project, which was an Ember CLI app that used ember-cli-coffeescript and [ember-cli-coffees6](https://github.com/alexspeller/ember-cli-coffees6) (which adds “support” for `import`/`export` by wrapping such statements in backticks before passing the result to the CoffeeScript compiler). I removed `ember-cli-coffees6` and replaced the CoffeeScript compiler used in the build chain with this code, and the app built without errors. [Demo here.](https://github.com/GeoffreyBooth/coffeescript-modules-test-piqu) * I also forked the [CoffeeScript version of Meteor’s Todos example app](https://github.com/meteor/todos/tree/coffeescript), and replaced all of its `require` statements with the `import` and `export` statements from the original ES2015 version of the app on its `master` branch. I then updated the `coffeescript` Meteor package in the app to use this new code, and again the app builds without errors. [Demo here.](https://github.com/GeoffreyBooth/coffeescript-modules-test-meteor-todos) The discussion history for this work started [here](https://github.com/jashkenas/coffeescript/pull/4160) and continued [here](https://github.com/GeoffreyBooth/coffeescript/pull/2). @lydell provided guidance, and @JimPanic and @rattrayalex contributed essential code.
2016-09-14 18:46:05 +00:00
this.seenFor = this.seenImport = this.seenExport = false;
tag = 'TERMINATOR';
2018-01-31 14:33:17 +00:00
} else if (value === '*' && (prev != null ? prev[0] : void 0) === 'EXPORT') {
tag = 'EXPORT_ALL';
} else if (indexOf.call(MATH, value) >= 0) {
tag = 'MATH';
} else if (indexOf.call(COMPARE, value) >= 0) {
tag = 'COMPARE';
} else if (indexOf.call(COMPOUND_ASSIGN, value) >= 0) {
tag = 'COMPOUND_ASSIGN';
} else if (indexOf.call(UNARY, value) >= 0) {
tag = 'UNARY';
} else if (indexOf.call(UNARY_MATH, value) >= 0) {
tag = 'UNARY_MATH';
} else if (indexOf.call(SHIFT, value) >= 0) {
tag = 'SHIFT';
} else if (value === '?' && (prev != null ? prev.spaced : void 0)) {
tag = 'BIN?';
} else if (prev) {
if (value === '(' && !prev.spaced && (ref4 = prev[0], indexOf.call(CALLABLE, ref4) >= 0)) {
2018-01-31 14:33:17 +00:00
if (prev[0] === '?') {
prev[0] = 'FUNC_EXIST';
}
tag = 'CALL_START';
} else if (value === '[' && (((ref5 = prev[0], indexOf.call(INDEXABLE, ref5) >= 0) && !prev.spaced) || (prev[0] === '::'))) { // `.prototype` cant be a method you can call.
2018-01-31 14:33:17 +00:00
tag = 'INDEX_START';
switch (prev[0]) {
case '?':
prev[0] = 'INDEX_SOAK';
}
}
}
token = this.makeToken(tag, value);
2011-09-16 23:26:04 +00:00
switch (value) {
case '(':
case '{':
case '[':
this.ends.push({
tag: INVERSES[value],
origin: token
});
2011-09-16 23:26:04 +00:00
break;
case ')':
case '}':
case ']':
this.pair(value);
}
this.tokens.push(this.makeToken(tag, value));
return value.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 05:55:30 +00: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-03 02:34:34 +00:00
// Token Manipulators
// ------------------
// A source of ambiguity in our grammar used to be parameter lists in 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-03 02:34:34 +00:00
// definitions versus argument lists in function calls. Walk backwards, tagging
// parameters specially in order to make things easier for the parser.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
tagParameters() {
var i, paramEndToken, stack, tok, tokens;
2012-04-10 18:57:45 +00:00
if (this.tag() !== ')') {
return this.tagDoIife();
2012-04-10 18:57:45 +00:00
}
2010-10-26 04:09:46 +00:00
stack = [];
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
({tokens} = this);
2010-10-26 04:09:46 +00:00
i = tokens.length;
paramEndToken = tokens[--i];
paramEndToken[0] = 'PARAM_END';
2010-10-26 04:09:46 +00:00
while (tok = tokens[--i]) {
switch (tok[0]) {
2010-09-22 03:58:05 +00:00
case ')':
2010-10-26 04:09:46 +00:00
stack.push(tok);
2010-09-22 03:58:05 +00:00
break;
case '(':
case 'CALL_START':
2010-10-26 04:09:46 +00:00
if (stack.length) {
stack.pop();
2018-01-31 14:33:17 +00:00
} else if (tok[0] === '(') {
tok[0] = 'PARAM_START';
return this.tagDoIife(i - 1);
} else {
2018-01-31 14:33:17 +00:00
paramEndToken[0] = 'CALL_END';
return this;
2010-10-26 04:09:46 +00:00
}
}
}
return this;
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
}
// Tag `do` followed by a function differently than `do` followed by eg an
// identifier to allow for different grammar precedence
tagDoIife(tokenIndex) {
var tok;
tok = this.tokens[tokenIndex != null ? tokenIndex : this.tokens.length - 1];
if ((tok != null ? tok[0] : void 0) !== 'DO') {
return this;
}
tok[0] = 'DO_IIFE';
return this;
}
[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-03 02:34:34 +00:00
// Close up all remaining open blocks at the end of the file.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
closeIndentation() {
return this.outdentToken({
moveOut: this.indent,
indentSize: 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 05:55:30 +00: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-03 02:34:34 +00:00
// Match the contents of a delimited token and expand variables and expressions
// inside it using Ruby-like notation for substitution of arbitrary
// expressions.
// "Hello #{name.capitalize()}."
// If it encounters an interpolation, this method will recursively create a new
// Lexer and tokenize until the `{` of `#{` is balanced with a `}`.
// - `regex` matches the contents of a token (but not `delimiter`, and not
// `#{` if interpolations are desired).
// - `delimiter` is the delimiter of the token. Examples are `'`, `"`, `'''`,
// `"""` and `///`.
// - `closingDelimiter` is different from `delimiter` only in JSX
// - `interpolators` matches the start of an interpolation, for JSX it's both
// `{` and `<` (i.e. nested JSX tag)
[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-03 02:34:34 +00:00
// This method allows us to have strings within interpolations within strings,
// ad infinitum.
matchWithInterpolations(regex, delimiter, closingDelimiter = delimiter, interpolators = /^#\{/) {
var braceInterpolator, close, column, index, interpolationOffset, interpolator, line, match, nested, offset, offsetInChunk, open, ref, ref1, rest, str, strPart, tokens;
tokens = [];
offsetInChunk = delimiter.length;
if (this.chunk.slice(0, offsetInChunk) !== delimiter) {
return null;
}
str = this.chunk.slice(offsetInChunk);
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
while (true) {
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
[strPart] = regex.exec(str);
this.validateEscapes(strPart, {
isRegex: delimiter.charAt(0) === '/',
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
offsetInChunk
});
[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-03 02:34:34 +00:00
// Push a fake `'NEOSTRING'` token, which will get turned into a real string later.
tokens.push(this.makeToken('NEOSTRING', strPart, {
offset: offsetInChunk
}));
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
str = str.slice(strPart.length);
offsetInChunk += strPart.length;
if (!(match = interpolators.exec(str))) {
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
break;
2012-04-10 18:57:45 +00:00
}
[interpolator] = match;
[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-03 02:34:34 +00:00
// To remove the `#` in `#{`.
interpolationOffset = interpolator.length - 1;
2018-08-21 23:57:00 +00:00
[line, column, offset] = this.getLineAndColumnFromChunk(offsetInChunk + interpolationOffset);
rest = str.slice(interpolationOffset);
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
({
tokens: nested,
index
} = new Lexer().tokenize(rest, {
2018-08-21 23:57:00 +00:00
line,
column,
offset,
untilBalanced: true,
locationDataCompensations: this.locationDataCompensations
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
}));
// Account for the `#` in `#{`.
index += interpolationOffset;
braceInterpolator = str[index - 1] === '}';
if (braceInterpolator) {
[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-03 02:34:34 +00:00
// Turn the leading and trailing `{` and `}` into parentheses. Unnecessary
// parentheses will be removed later.
[open] = nested, [close] = slice.call(nested, -1);
open[0] = 'INTERPOLATION_START';
open[1] = '(';
open[2].first_column -= interpolationOffset;
open[2].range = [open[2].range[0] - interpolationOffset, open[2].range[1]];
close[0] = 'INTERPOLATION_END';
close[1] = ')';
close.origin = ['', 'end of interpolation', close[2]];
}
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
if (((ref = nested[1]) != null ? ref[0] : void 0) === 'TERMINATOR') {
[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-03 02:34:34 +00:00
// Remove leading `'TERMINATOR'` (if any).
nested.splice(1, 1);
}
if (((ref1 = nested[nested.length - 3]) != null ? ref1[0] : void 0) === 'INDENT' && nested[nested.length - 2][0] === 'OUTDENT') {
// Remove trailing `'INDENT'/'OUTDENT'` pair (if any).
nested.splice(-3, 2);
}
if (!braceInterpolator) {
[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-03 02:34:34 +00:00
// We are not using `{` and `}`, so wrap the interpolated tokens instead.
open = this.makeToken('INTERPOLATION_START', '(', {
offset: offsetInChunk,
length: 0,
generated: true
});
close = this.makeToken('INTERPOLATION_END', ')', {
offset: offsetInChunk + index,
length: 0,
generated: true
});
nested = [open, ...nested, close];
}
[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-03 02:34:34 +00:00
// Push a fake `'TOKENS'` token, which will get turned into real tokens later.
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
tokens.push(['TOKENS', nested]);
str = str.slice(index);
offsetInChunk += index;
}
if (str.slice(0, closingDelimiter.length) !== closingDelimiter) {
this.error(`missing ${closingDelimiter}`, {
length: delimiter.length
});
2012-04-10 18:57:45 +00:00
}
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
return {
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
tokens,
index: offsetInChunk + closingDelimiter.length
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00: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 05:55:30 +00:00
}
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00: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-03 02:34:34 +00:00
// Merge the array `tokens` of the fake token types `'TOKENS'` and `'NEOSTRING'`
// (as returned by `matchWithInterpolations`) into the token stream. The value
// of `'NEOSTRING'`s are converted using `fn` and turned into strings using
// `options` first.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
mergeInterpolationTokens(tokens, options, fn) {
var $, converted, double, endOffset, firstIndex, heregex, i, indent, j, jsx, k, lastToken, len, len1, locationToken, lparen, placeholderToken, quote, ref, ref1, rparen, tag, token, tokensToPush, val, value;
({quote, indent, double, heregex, endOffset, jsx} = options);
2015-02-07 19:16:59 +00:00
if (tokens.length > 1) {
lparen = this.token('STRING_START', '(', {
length: (ref = quote != null ? quote.length : void 0) != null ? ref : 0,
data: {quote},
generated: !(quote != null ? quote.length : void 0)
});
2012-04-10 18:57:45 +00:00
}
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
firstIndex = this.tokens.length;
$ = tokens.length - 1;
for (i = j = 0, len = tokens.length; j < len; i = ++j) {
token = tokens[i];
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
[tag, value] = token;
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
switch (tag) {
case 'TOKENS':
// There are comments (and nothing else) in this interpolation.
if (value.length === 2 && (value[0].comments || value[1].comments)) {
placeholderToken = this.makeToken('JS', '', {
generated: true
});
// Use the same location data as the first parenthesis.
placeholderToken[2] = value[0][2];
for (k = 0, len1 = value.length; k < len1; k++) {
val = value[k];
if (!val.comments) {
continue;
}
if (placeholderToken.comments == null) {
placeholderToken.comments = [];
}
placeholderToken.comments.push(...val.comments);
}
value.splice(1, 0, placeholderToken);
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00: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-03 02:34:34 +00:00
// Push all the tokens in the fake `'TOKENS'` token. These already have
// sane location data.
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
locationToken = value[0];
tokensToPush = value;
break;
case 'NEOSTRING':
[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-03 02:34:34 +00:00
// Convert `'NEOSTRING'` into `'STRING'`.
converted = fn.call(this, token[1], i);
if (i === 0) {
addTokenData(token, {
initialChunk: true
});
}
if (i === $) {
addTokenData(token, {
finalChunk: true
});
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
}
addTokenData(token, {indent, quote, double});
if (heregex) {
addTokenData(token, {heregex});
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
}
if (jsx) {
addTokenData(token, {jsx});
}
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
token[0] = 'STRING';
token[1] = '"' + converted + '"';
if (tokens.length === 1 && (quote != null)) {
token[2].first_column -= quote.length;
if (token[1].substr(-2, 1) === '\n') {
token[2].last_line += 1;
token[2].last_column = quote.length - 1;
} else {
token[2].last_column += quote.length;
if (token[1].length === 2) {
token[2].last_column -= 1;
}
}
token[2].last_column_exclusive += quote.length;
token[2].range = [token[2].range[0] - quote.length, token[2].range[1] + quote.length];
}
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
locationToken = token;
tokensToPush = [token];
}
this.tokens.push(...tokensToPush);
}
2015-02-07 19:16:59 +00:00
if (lparen) {
[lastToken] = slice.call(tokens, -1);
2015-02-07 19:16:59 +00:00
lparen.origin = [
[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-03 02:34:34 +00:00
'STRING',
null,
{
2015-02-07 19:16:59 +00:00
first_line: lparen[2].first_line,
first_column: lparen[2].first_column,
last_line: lastToken[2].last_line,
2018-08-21 23:57:00 +00:00
last_column: lastToken[2].last_column,
last_line_exclusive: lastToken[2].last_line_exclusive,
last_column_exclusive: lastToken[2].last_column_exclusive,
2018-08-21 23:57:00 +00:00
range: [lparen[2].range[0],
lastToken[2].range[1]]
2015-02-07 19:16:59 +00:00
}
];
if (!(quote != null ? quote.length : void 0)) {
lparen[2] = lparen.origin[2];
}
return rparen = this.token('STRING_END', ')', {
offset: endOffset - (quote != null ? quote : '').length,
length: (ref1 = quote != null ? quote.length : void 0) != null ? ref1 : 0,
generated: !(quote != null ? quote.length : void 0)
});
2012-04-10 18:57:45 +00: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 05:55:30 +00: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-03 02:34:34 +00:00
// Pairs up a closing token, ensuring that all listed pairs of tokens are
// correctly balanced throughout the course of the token stream.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
pair(tag) {
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
var lastIndent, prev, ref, ref1, wanted;
ref = this.ends, [prev] = slice.call(ref, -1);
if (tag !== (wanted = prev != null ? prev.tag : void 0)) {
2012-04-10 18:57:45 +00:00
if ('OUTDENT' !== wanted) {
this.error(`unmatched ${tag}`);
2012-04-10 18:57:45 +00: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-03 02:34:34 +00:00
// Auto-close `INDENT` to support syntax like this:
// el.click((event) ->
// el.hide())
ref1 = this.indents, [lastIndent] = slice.call(ref1, -1);
this.outdentToken({
moveOut: lastIndent,
noNewlines: true
});
2011-09-16 23:26:04 +00:00
return this.pair(tag);
}
return this.ends.pop();
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
}
[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-03 02:34:34 +00:00
// Helpers
// -------
// Compensate for the things we strip out initially (e.g. carriage returns)
// so that location data stays accurate with respect to the original source file.
getLocationDataCompensation(start, end) {
var compensation, current, initialEnd, totalCompensation;
totalCompensation = 0;
initialEnd = end;
current = start;
while (current <= end) {
if (current === end && start !== initialEnd) {
break;
}
compensation = this.locationDataCompensations[current];
if (compensation != null) {
totalCompensation += compensation;
end += compensation;
}
current++;
}
return totalCompensation;
}
// Returns the line and column number from an offset into the current chunk.
[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-03 02:34:34 +00:00
// `offset` is a number of characters into `@chunk`.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
getLineAndColumnFromChunk(offset) {
var column, columnCompensation, compensation, lastLine, lineCount, previousLinesCompensation, ref, string;
compensation = this.getLocationDataCompensation(this.chunkOffset, this.chunkOffset + offset);
if (offset === 0) {
return [this.chunkLine, this.chunkColumn + compensation, this.chunkOffset + compensation];
}
if (offset >= this.chunk.length) {
string = this.chunk;
} else {
string = this.chunk.slice(0, +(offset - 1) + 1 || 9e9);
}
lineCount = count(string, '\n');
column = this.chunkColumn;
if (lineCount > 0) {
ref = string.split('\n'), [lastLine] = slice.call(ref, -1);
column = lastLine.length;
previousLinesCompensation = this.getLocationDataCompensation(this.chunkOffset, this.chunkOffset + offset - column);
if (previousLinesCompensation < 0) {
// Don't recompensate for initially inserted newline.
previousLinesCompensation = 0;
}
columnCompensation = this.getLocationDataCompensation(this.chunkOffset + offset + previousLinesCompensation - column, this.chunkOffset + offset + previousLinesCompensation);
} else {
column += string.length;
columnCompensation = compensation;
}
return [this.chunkLine + lineCount, column + columnCompensation, this.chunkOffset + offset + compensation];
2018-08-21 23:57:00 +00:00
}
makeLocationData({offsetInChunk, length}) {
2018-08-24 06:58:28 +00:00
var endOffset, lastCharacter, locationData;
2018-08-21 23:57:00 +00:00
locationData = {
range: []
};
[locationData.first_line, locationData.first_column, locationData.range[0]] = this.getLineAndColumnFromChunk(offsetInChunk);
// Use length - 1 for the final offset - were supplying the last_line and the last_column,
// so if last_column == first_column, then were looking at a character of length 1.
lastCharacter = length > 0 ? length - 1 : 0;
2018-08-24 06:58:28 +00:00
[locationData.last_line, locationData.last_column, endOffset] = this.getLineAndColumnFromChunk(offsetInChunk + lastCharacter);
[locationData.last_line_exclusive, locationData.last_column_exclusive] = this.getLineAndColumnFromChunk(offsetInChunk + lastCharacter + (length > 0 ? 1 : 0));
locationData.range[1] = length > 0 ? endOffset + 1 : endOffset;
2018-08-21 23:57:00 +00:00
return locationData;
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
}
[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-03 02:34:34 +00:00
// Same as `token`, except this just returns the token without adding it
// to the results.
makeToken(tag, value, {
offset: offsetInChunk = 0,
length = value.length,
origin,
generated,
indentSize
} = {}) {
2018-08-21 23:57:00 +00:00
var token;
token = [tag, value, this.makeLocationData({offsetInChunk, length})];
if (origin) {
token.origin = origin;
}
if (generated) {
token.generated = true;
}
if (indentSize != null) {
token.indentSize = indentSize;
}
return token;
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
}
[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-03 02:34:34 +00:00
// Add a token to the results.
// `offset` is the offset into the current `@chunk` where the token starts.
// `length` is the length of the token in the `@chunk`, after the offset. If
// not specified, the length of `value` will be used.
// Returns the new token.
token(tag, value, {offset, length, origin, data, generated, indentSize} = {}) {
var token;
token = this.makeToken(tag, value, {offset, length, origin, generated, indentSize});
if (data) {
addTokenData(token, data);
}
this.tokens.push(token);
return token;
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
}
[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-03 02:34:34 +00:00
// Peek at the last tag in the token stream.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
tag() {
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
var ref, token;
ref = this.tokens, [token] = slice.call(ref, -1);
return token != null ? token[0] : 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 05:55:30 +00: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-03 02:34:34 +00:00
// Peek at the last value in the token stream.
value(useOrigin = false) {
var ref, token;
ref = this.tokens, [token] = slice.call(ref, -1);
if (useOrigin && ((token != null ? token.origin : void 0) != null)) {
return token.origin[1];
} else {
return token != null ? token[1] : 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 05:55:30 +00: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-03 02:34:34 +00:00
// Get the previous token in the token stream.
prev() {
return this.tokens[this.tokens.length - 1];
}
[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-03 02:34:34 +00:00
// Are we in the midst of an unfinished expression?
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
unfinished() {
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
var ref;
return LINE_CONTINUER.test(this.chunk) || (ref = this.tag(), indexOf.call(UNFINISHED, ref) >= 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 05:55:30 +00:00
}
validateUnicodeCodePointEscapes(str, options) {
return replaceUnicodeCodePointEscapes(str, merge(options, {error: this.error}));
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
}
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00: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-03 02:34:34 +00:00
// Validates escapes in strings and regexes.
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
validateEscapes(str, options = {}) {
2017-04-20 19:41:28 +00:00
var before, hex, invalidEscape, invalidEscapeRegex, match, message, octal, ref, unicode, unicodeCodePoint;
invalidEscapeRegex = options.isRegex ? REGEX_INVALID_ESCAPE : STRING_INVALID_ESCAPE;
match = invalidEscapeRegex.exec(str);
if (!match) {
return;
}
match[0], before = match[1], octal = match[2], hex = match[3], unicodeCodePoint = match[4], unicode = match[5];
message = octal ? "octal escape sequences are not allowed" : "invalid escape sequence";
2017-04-20 19:41:28 +00:00
invalidEscape = `\\${octal || hex || unicodeCodePoint || unicode}`;
return this.error(`${message} ${invalidEscape}`, {
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
offset: ((ref = options.offsetInChunk) != null ? ref : 0) + match.index + before.length,
length: invalidEscape.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 05:55:30 +00:00
}
suppressSemicolons() {
var ref, ref1, results;
results = [];
while (this.value() === ';') {
this.tokens.pop();
if (ref = (ref1 = this.prev()) != null ? ref1[0] : void 0, indexOf.call(['=', ...UNFINISHED], ref) >= 0) {
results.push(this.error('unexpected ;'));
} else {
results.push(void 0);
}
}
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 05:55:30 +00:00
error(message, options = {}) {
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
var first_column, first_line, location, ref, ref1;
location = 'first_line' in options ? options : ([first_line, first_column] = this.getLineAndColumnFromChunk((ref = options.offset) != null ? ref : 0), {
first_line,
first_column,
last_column: first_column + ((ref1 = options.length) != null ? ref1 : 1) - 1
});
return throwSyntaxError(message, location);
[CS2] Compile class constructors to ES2015 classes (#4354) * Compile classes to ES2015 classes Rather than compiling classes to named functions with prototype and class assignments, they are now compiled to ES2015 class declarations. Backwards compatibility has been maintained by compiling ES2015- incompatible properties as prototype or class assignments. `super` continues to be compiled as before. Where possible, classes will be compiled "bare", without an enclosing IIFE. This is possible when the class contains only ES2015 compatible expressions (methods and static methods), and has no parent (this last constraint is a result of the legacy `super` compilation, and could be removed once ES2015 `super` is being used). Classes are still assigned to variables to maintain compatibility for assigned class expressions. There are a few changes to existing functionality that could break backwards compatibility: - Derived constructors that deliberately don't call `super` are no longer possible. ES2015 derived classes can't use `this` unless the parent constructor has been called, so it's now called implicitly when not present. - As a consequence of the above, derived constructors with @ parameters or bound methods and explicit `super` calls are not allowed. The implicit `super` must be used in these cases. * Add tests to verify class interoperability with ES * Refactor class nodes to separate executable body logic Logic has been redistributed amongst the class nodes so that: - `Class` contains the logic necessary to compile an ES class declaration. - `ExecutableClassBody` contains the logic necessary to compile CS' class extensions that require an executable class body. `Class` still necessarily contains logic to determine whether an expression is valid in an ES class initializer or not. If any invalid expressions are found then `Class` will wrap itself in an `ExecutableClassBody` when compiling. * Rename `Code#static` to `Code#isStatic` This naming is more consistent with other `Code` flags. * Output anonymous classes when possible Anonymous classes can be output when: - The class has no parent. The current super compilation needs a class variable to reference. This condition will go away when ES2015 super is in use. - The class contains no bound static methods. Bound static methods have their context set to the class name. * Throw errors at compile time for async or generator constructors * Improve handling of anonymous classes Anonymous classes are now always anonymous. If a name is required (e.g. for bound static methods or derived classes) then the class is compiled in an `ExecutableClassBody` which will give the anonymous class a stable reference. * Add a `replaceInContext` method to `Node` `replaceInContext` will traverse children looking for a node for which `match` returns true. Once found, the matching node will be replaced by the result of calling `replacement`. * Separate `this` assignments from function parameters This change has been made to simplify two future changes: 1. Outputting `@`-param assignments after a `super` call. In this case it is necessary that non-`@` parameters are available before `super` is called, so destructuring has to happen before `this` assignment. 2. Compiling destructured assignment to ES6 In this case also destructuring has to happen before `this`, as destructuring can happen in the arguments list, but `this` assignment can not. A bonus side-effect is that default values for `@` params are now output as ES6 default parameters, e.g. (@a = 1) -> becomes function a (a = 1) { this.a = a; } * Change `super` handling in class constructors Inside an ES derived constructor (a constructor for a class that extends another class), it is impossible to access `this` until `super` has been called. This conflicts with CoffeeScript's `@`-param and bound method features, which compile to `this` references at the top of a function body. For example: class B extends A constructor: (@param) -> super method: => This would compile to something like: class B extends A { constructor (param) { this.param = param; this.method = bind(this.method, this); super(...arguments); } } This would break in an ES-compliant runtime as there are `this` references before the call to `super`. Before this commit we were dealing with this by injecting an implicit `super` call into derived constructors that do not already have an explicit `super` call. Furthermore, we would disallow explicit `super` calls in derived constructors that used bound methods or `@`-params, meaning the above example would need to be rewritten as: class B extends A constructor: (@param) -> method: => This would result in a call to `super(...arguments)` being generated as the first expression in `B#constructor`. Whilst this approach seems to work pretty well, and is arguably more convenient than having to manually call `super` when you don't particularly care about the arguments, it does introduce some 'magic' and separation from ES, and would likely be a pain point in a project that made use of significant constructor overriding. This commit introduces a mechanism through which `super` in constructors is 'expanded' to include any generated `this` assignments, whilst retaining the same semantics of a super call. The first example above now compiles to something like: class B extends A { constructor (param) { var ref ref = super(...arguments), this.param = param, this.method = bind(this.method, this), ref; } } * Improve `super` handling in constructors Rather than functions expanding their `super` calls, the `SuperCall` node can now be given a list of `thisAssignments` to apply when it is compiled. This allows us to use the normal compiler machinery to determine whether the `super` result needs to be cached, whether it appears inline or not, etc. * Fix anonymous classes at the top level Anonymous classes in ES are only valid within expressions. If an anonymous class is at the top level it will now be wrapped in parenthses to force it into an expression. * Re-add Parens wrapper around executable class bodies This was lost in the refactoring, but it necessary to ensure `new class ...` works as expected when there's an executable body. * Throw compiler errors for badly configured derived constructors Rather than letting them become runtime errors, the following checks are now performed when compiling a derived constructor: - The constructor **must** include a call to `super`. - The constructor **must not** reference `this` in the function body before `super` has been called. * Add some tests exercising new class behaviour - async methods in classes - `this` access after `super` in extended classes - constructor super in arrow functions - constructor functions can't be async - constructor functions can't be generators - derived constructors must call super - derived constructors can't reference `this` before calling super - generator methods in classes - 'new' target * Improve constructor `super` errors Add a check for `super` in non-extended class constructors, and explicitly mention derived constructors in the "can't reference this before super" error. * Fix compilation of multiple `super` paths in derived constructors `super` can only be called once, but it can be called conditionally from multiple locations. The chosen fix is to add the `this` assignments to every super call. * Additional class tests, added as a separate file to simplify testing and merging. Some methods are commented out because they currently throw and I'm not sure how to test for compilation errors like those. There is also one test which I deliberately left without passing, `super` in an external prototype override. This test should 'pass' but is really a variation on the failing `super only allowed in an instance method` tests above it. * Changes to the tests. Found bug in super in prototype method. fixed. * Added failing test back in, dealing with bound functions in external prototype overrides. * Located a bug in the compiler relating to assertions and escaped ES6 classes. * Move tests from classes-additional.coffee into classes.coffee; comment out console.log * Cleaned up tests and made changes based on feedback. Test at the end still has issues, but it's commented out for now. * Make HoistTarget.expand recursive It's possible that a hoisted node may itself contain hoisted nodes (e.g. a class method inside a class method). For this to work the hoisted fragments need to be expanded recursively. * Uncomment final test in classes.coffee The test case now compiles, however another issue is affecting the test due to the error for `this` before `super` triggering based on source order rather than execution order. These have been commented out for now. * Fixed last test TODOs in test/classes.coffee Turns out an expression like `this.foo = super()` won't run in JS as it attempts to lookup `this` before evaluating `super` (i.e. throws "this is not defined"). * Added more tests for compatability checks, statics, prototypes and ES6 expectations. Cleaned test "nested classes with super". * Changes to reflect feedback and to comment out issues that will be addressed seperately. * Clean up test/classes.coffee - Trim trailing whitespace. - Rephrase a condition to be more idiomatic. * Remove check for `super` in derived constructors In order to be usable at runtime, an extended ES class must call `super` OR return an alternative object. This check prevented the latter case, and checking for an alternative return can't be completed statically without control flow analysis. * Disallow 'super' in constructor parameter defaults There are many edge cases when combining 'super' in parameter defaults with @-parameters and bound functions (and potentially property initializers in the future). Rather than attempting to resolve these edge cases, 'super' is now explicitly disallowed in constructor parameter defaults. * Disallow @-params in derived constructors without 'super' @-parameters can't be assigned unless 'super' is called.
2017-01-13 05:55:30 +00:00
}
2011-12-14 15:39:20 +00: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 05:55:30 +00: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-03 02:34:34 +00:00
// Helper functions
// ----------------
[CS2] Output ES2015 arrow functions, default parameters, rest parameters (#4311) * Eliminate wrapper around “bound” (arrow) functions; output `=>` for such functions * Remove irrelevant (and breaking) tests * Minor cleanup * When a function parameter is a splat (i.e., it uses the ES2015 rest parameter syntax) output that parameter as ES2015 * Rearrange function parameters when one of the parameters is a splat and isn’t the last parameter (very WIP) * Handle params like `@param`, adding assignment expressions for them when they appear; ensure splat parameter is last * Add parameter names (not a text like `'\nValue IdentifierLiteral: a'`) to the scope, so that parameters can’t be deleted; move body-related lines together; more explanation of what’s going on * For parameters with a default value, correctly add the parameter name to the function scope * Handle expansions in function parameters: when an expansion is found, set the parameters to only be the original parameters left of the expansion, then an `...args` parameter; and in the function body define variables for the parameters to the right of the expansion, including setting default values * Handle splat parameters the same way we handle expansions: if a splat parameter is found, it becomes the last parameter in the function definition, and all following parameters get declared in the function body. Fix the splat/rest parameter values after the post-splat parameters have been extracted from it. Clean up `Code.compileNode` so that we loop through the parameters only once, and we create all expressions using calls like `new IdentifierLiteral` rather than `@makeCode`. * Fix parameter name when a parameter is a splat attached to `this` (e.g. `@param...`) * Rather than assigning post-splat parameters based on index, use slice; passes test “Functions with splats being called with too few arguments” * Dial back our w00t indentation * Better parsing of parameter names (WIP) * Refactor processing of splat/expansion parameters * Fix assignment of default parameters for parameters that come after a splat * Better check for whether a param is attached to `this` * More understandable variable names * For parameters after a splat or expansion, assign them similar to the 1.x destructuring method of using `arguments`, except only concern ourselves with the post-splat parameters instead of all parameters; and use the splat/expansion parameter name, since `arguments` in ES fat arrow functions refers to the parent function’s `arguments` rather than the fat arrow function’s arguments/parameters * Don’t add unnamed parameters (like `[]` as a parameter) to the function scope * Disallow multiple splat/expansion parameters in function definitions; disallow lone expansion parameters * Fix `this` params not getting assigned if the parameter is after a splat parameter * Allow names of function parameters attached to `this` to be reserved words * Always add a statement to the function body defining a variable with its default value, if it has one, if the variable `== null`; this covers the case when ES doesn’t apply the default value when `null` is passed in as a value, but CoffeeScript expects `null` and `undefined` to act interchangeably * Aftermath of having both `undefined` and `null` trigger the use of default values for parameters with default values * More careful parsing of destructured parameters * Fall back to processing destructured parameters in the function body, to account for `this` or default values within destructured objects * Clean up comments * Restore new bare function test, minus the arrow function part of it * Test that bound/arrow functions aren’t overwriting the `arguments` object, which should refer to the parent scope’s `arguments` (like `this`) * Follow ES2015 spec for parameter default values: `null` gets assigned as as `null`, not the default value * Mimic ES default parameters behavior for parameters after a splat or expansion parameter * Bound functions cannot be generators: remove no-longer-relevant test, add check to throw error if `yield` appears inside a bound (arrow) function * Error for bound generator functions should underline the `yield`
2016-10-26 05:26:13 +00:00
isUnassignable = function(name, displayName = name) {
switch (false) {
case indexOf.call([...JS_KEYWORDS, ...COFFEE_KEYWORDS], name) < 0:
return `keyword '${displayName}' can't be assigned`;
case indexOf.call(STRICT_PROSCRIBED, name) < 0:
return `'${displayName}' can't be assigned`;
case indexOf.call(RESERVED, name) < 0:
return `reserved word '${displayName}' can't be assigned`;
default:
return false;
}
};
exports.isUnassignable = isUnassignable;
[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-03 02:34:34 +00:00
// `from` isnt a CoffeeScript keyword, but it behaves like one in `import` and
// `export` statements (handled above) and in the declaration line of a `for`
// loop. Try to detect when `from` is a variable identifier and when it is this
// “sometimes” keyword.
isForFrom = function(prev) {
[CS2] Destructuring (#4478) * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Compile default values in destructured assignment to ES2015 * Rename `wrapInBraces` to `wrapInParentheses`, and `compilePatternMatch` to `compileDestructuring`, for clarity; style improvements (no `==` or `!=`, etc.) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Optional check for existence that only checks `!== undefined`, not `!= null`, to follow ES convention that default values only apply when a variable is undefined, not falsy * Add comments; remove unnecessary array splats in function tests * The fallback destructuring code should apply default values only if `undefined`, not falsy, to follow ES spec * Support destructuring in function parameters (first pass); catch destructured reserved words * Destructured variables in function parameter lists shouldn’t be added to the function body with `var` declarations; treat splat array function parameters the legacy way to avoid rethinking #4005 * Remove redundancy in undefined-only check for existence; fix passing option to check * Fix undefined redundancy * Simplify getting the variable name * Reimplement “check for existence if not undefined” without creating a new operator * `Obj::isAssignable` should not mutate; pass `lhs` property in from `Assign` or `Code` to child arrays and objects so that those child nodes are set as allowable for destructuring * Revert changes to tests * Restore revised test for empty destructuring assignment
2017-04-06 17:06:45 +00:00
var ref;
// `for i from iterable`
if (prev[0] === 'IDENTIFIER') {
return true;
2018-01-31 14:33:17 +00:00
// `for from…`
} else if (prev[0] === 'FOR') {
return false;
// `for {from}…`, `for [from]…`, `for {a, from}…`, `for {a: from}…`
} else if ((ref = prev[1]) === '{' || ref === '[' || ref === ',' || ref === ':') {
return false;
} else {
2018-01-31 14:33:17 +00:00
return true;
}
};
addTokenData = function(token, data) {
return Object.assign((token.data != null ? token.data : token.data = {}), data);
};
[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-03 02:34:34 +00:00
// Constants
// ---------
// Keywords that CoffeeScript shares in common with JavaScript.
JS_KEYWORDS = ['true', 'false', 'null', 'this', 'new', 'delete', 'typeof', 'in', 'instanceof', 'return', 'throw', 'break', 'continue', 'debugger', 'yield', 'await', 'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally', 'class', 'extends', 'super', 'import', 'export', 'default'];
[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-03 02:34:34 +00:00
// CoffeeScript-only keywords.
COFFEE_KEYWORDS = ['undefined', 'Infinity', 'NaN', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when'];
2011-04-30 14:35:56 +00:00
COFFEE_ALIAS_MAP = {
and: '&&',
or: '||',
is: '==',
isnt: '!=',
not: '!',
2010-10-23 18:24:30 +00:00
yes: 'true',
no: 'false',
on: 'true',
off: 'false'
2011-04-30 14:35:56 +00:00
};
2011-04-30 14:35:56 +00:00
COFFEE_ALIASES = (function() {
var results;
results = [];
2011-04-30 14:35:56 +00:00
for (key in COFFEE_ALIAS_MAP) {
results.push(key);
2011-04-30 14:35:56 +00:00
}
return results;
2011-04-30 14:35:56 +00:00
})();
2011-04-30 14:35:56 +00:00
COFFEE_KEYWORDS = COFFEE_KEYWORDS.concat(COFFEE_ALIASES);
[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-03 02:34:34 +00:00
// The list of keywords that are reserved by JavaScript, but not used, or are
// used by CoffeeScript internally. We throw an error when these are encountered,
// to avoid having a JavaScript error at runtime.
Support import and export of ES2015 modules (#4300) This pull request adds support for ES2015 modules, by recognizing `import` and `export` statements. The following syntaxes are supported, based on the MDN [import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) and [export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) pages: ```js import "module-name" import defaultMember from "module-name" import * as name from "module-name" import { } from "module-name" import { member } from "module-name" import { member as alias } from "module-name" import { member1, member2 as alias2, … } from "module-name" import defaultMember, * as name from "module-name" import defaultMember, { … } from "module-name" export default expression export class name export { } export { name } export { name as exportedName } export { name as default } export { name1, name2 as exportedName2, name3 as default, … } export * from "module-name" export { … } from "module-name" ``` As a subsitute for ECMAScript’s `export var name = …` and `export function name {}`, CoffeeScript also supports: ```js export name = … ``` CoffeeScript also supports optional commas within `{ … }`. This PR converts the supported `import` and `export` statements into ES2015 `import` and `export` statements; it **does not resolve the modules**. So any CoffeeScript with `import` or `export` statements will be output as ES2015, and will need to be transpiled by another tool such as Babel before it can be used in a browser. We will need to add a warning to the documentation explaining this. This should be fully backwards-compatible, as `import` and `export` were previously reserved keywords. No flags are used. There are extensive tests included, though because no current JavaScript runtime supports `import` or `export`, the tests compare strings of what the compiled CoffeeScript output is against what the expected ES2015 should be. I also conducted two more elaborate tests: * I forked the [ember-piqu](https://github.com/pauc/piqu-ember) project, which was an Ember CLI app that used ember-cli-coffeescript and [ember-cli-coffees6](https://github.com/alexspeller/ember-cli-coffees6) (which adds “support” for `import`/`export` by wrapping such statements in backticks before passing the result to the CoffeeScript compiler). I removed `ember-cli-coffees6` and replaced the CoffeeScript compiler used in the build chain with this code, and the app built without errors. [Demo here.](https://github.com/GeoffreyBooth/coffeescript-modules-test-piqu) * I also forked the [CoffeeScript version of Meteor’s Todos example app](https://github.com/meteor/todos/tree/coffeescript), and replaced all of its `require` statements with the `import` and `export` statements from the original ES2015 version of the app on its `master` branch. I then updated the `coffeescript` Meteor package in the app to use this new code, and again the app builds without errors. [Demo here.](https://github.com/GeoffreyBooth/coffeescript-modules-test-meteor-todos) The discussion history for this work started [here](https://github.com/jashkenas/coffeescript/pull/4160) and continued [here](https://github.com/GeoffreyBooth/coffeescript/pull/2). @lydell provided guidance, and @JimPanic and @rattrayalex contributed essential code.
2016-09-14 18:46:05 +00:00
RESERVED = ['case', 'function', 'var', 'void', 'with', 'const', 'let', 'enum', 'native', 'implements', 'interface', 'package', 'private', 'protected', 'public', 'static'];
STRICT_PROSCRIBED = ['arguments', 'eval'];
[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-03 02:34:34 +00:00
// The superset of both JavaScript keywords and reserved words, none of which may
// be used as identifiers or properties.
exports.JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat(STRICT_PROSCRIBED);
Refactor `Literal` into several subtypes Previously, the parser created `Literal` nodes for many things. This resulted in information loss. Instead of being able to check the node type, we had to use regexes to tell the different types of `Literal`s apart. That was a bit like parsing literals twice: Once in the lexer, and once (or more) in the compiler. It also caused problems, such as `` `this` `` and `this` being indistinguishable (fixes #2009). Instead returning `new Literal` in the grammar, subtypes of it are now returned instead, such as `NumberLiteral`, `StringLiteral` and `IdentifierLiteral`. `new Literal` by itself is only used to represent code chunks that fit no category. (While mentioning `NumberLiteral`, there's also `InfinityLiteral` now, which is a subtype of `NumberLiteral`.) `StringWithInterpolations` has been added as a subtype of `Parens`, and `RegexWithInterpolations` as a subtype of `Call`. This makes it easier for other programs to make use of CoffeeScript's "AST" (nodes). For example, it is now possible to distinguish between `"a #{b} c"` and `"a " + b + " c"`. Fixes #4192. `SuperCall` has been added as a subtype of `Call`. Note, though, that some information is still lost, especially in the lexer. For example, there is no way to distinguish a heredoc from a regular string, or a heregex without interpolations from a regular regex. Binary and octal number literals are indistinguishable from hexadecimal literals. After the new subtypes were added, they were taken advantage of, removing most regexes in nodes.coffee. `SIMPLENUM` (which matches non-hex integers) had to be kept, though, because such numbers need special handling in JavaScript (for example in `1..toString()`). An especially nice hack to get rid of was using `new String()` for the token value for reserved identifiers (to be able to set a property on them which could survive through the parser). Now it's a good old regular string. In range literals, slices, splices and for loop steps when number literals are involved, CoffeeScript can do some optimizations, such as precomputing the value of, say, `5 - 3` (outputting `2` instead of `5 - 3` literally). As a side bonus, this now also works with hexadecimal number literals, such as `0x02`. Finally, this also improves the output of `coffee --nodes`: # Before: $ bin/coffee -ne 'while true "#{a}" break' Block While Value Bool Block Value Parens Block Op + Value """" Value Parens Block Value "a" "break" # After: $ bin/coffee -ne 'while true "#{a}" break' Block While Value BooleanLiteral: true Block Value StringWithInterpolations Block Op + Value StringLiteral: "" Value Parens Block Value IdentifierLiteral: a StatementLiteral: break
2016-01-31 19:24:31 +00: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-03 02:34:34 +00:00
// The character code of the nasty Microsoft madness otherwise known as the BOM.
BOM = 65279;
[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-03 02:34:34 +00:00
// Token matching regexes.
IDENTIFIER = /^(?!\d)((?:(?!\s)[$\w\x7f-\uffff])+)([^\n\S]*:(?!:))?/; // Is this a property name?
// Like `IDENTIFIER`, but includes `-`s
JSX_IDENTIFIER_PART = /(?:(?!\s)[\-$\w\x7f-\uffff])+/.source;
// In https://facebook.github.io/jsx/ spec, JSXElementName can be
// JSXIdentifier, JSXNamespacedName (JSXIdentifier : JSXIdentifier), or
// JSXMemberExpression (two or more JSXIdentifier connected by `.`s).
JSX_IDENTIFIER = RegExp(`^(?![\\d<])(${JSX_IDENTIFIER_PART // Must not start with `<`.
// JSXNamespacedName
// JSXMemberExpression
}(?:\\s*:\\s*${JSX_IDENTIFIER_PART}|(?:\\s*\\.\\s*${JSX_IDENTIFIER_PART})+)?)`);
// Fragment: <></>
JSX_FRAGMENT_IDENTIFIER = /^()>/; // Ends immediately with `>`.
// In https://facebook.github.io/jsx/ spec, JSXAttributeName can be either
// JSXIdentifier or JSXNamespacedName which is JSXIdentifier : JSXIdentifier
JSX_ATTRIBUTE = RegExp(`^(?!\\d)(${JSX_IDENTIFIER_PART // JSXNamespacedName
[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-03 02:34:34 +00:00
// Is this an attribute with a value?
}(?:\\s*:\\s*${JSX_IDENTIFIER_PART})?)([^\\S]*=(?!=))?`);
2022-10-25 16:23:39 +00:00
NUMBER = /^0b[01](?:_?[01])*n?|^0o[0-7](?:_?[0-7])*n?|^0x[\da-f](?:_?[\da-f])*n?|^\d+(?:_\d+)*n|^(?:\d+(?:_\d+)*)?\.?\d+(?:_\d+)*(?:e[+-]?\d+(?:_\d+)*)?/i; // binary
[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-03 02:34:34 +00:00
// octal
// hex
AST: numeric separators, BigInt (#5272) * Revert to more complicated lexing of numbers, as the Number constructor can't handle BigInts or numbers with numeric separators * Add debugging information to error message test (#5239) One of the test cases in test/error_messages.coffee fails intermittently in the Node.js ecosystem-testing tool CITGM. In an effort to help debug what's going on when this occurs, this adds more information to the AssertionError message in question. * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Numeric literal separators (#5215) * implement numeric literal separators * add tests * Revert changes to package-lock.json * small regex adjustment * split tests * add comment * Add Node versions to CI * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Update output * Fix style * support bigint literal with separators * un-disallow property access on number literal * Update output * Refactor numeric literal separator tests to be more like the rest of the tests * Add test for numeric property with underscore Co-authored-by: Geoffrey Booth <GeoffreyBooth@users.noreply.github.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> * Update test style and output * numeric separator parsed value * BigInt AST; parseNumber() Co-authored-by: Geoffrey Booth <GeoffreyBooth@users.noreply.github.com> Co-authored-by: Rich Trott <rtrott@gmail.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> Co-authored-by: square <Inve1951@users.noreply.github.com>
2019-12-30 00:20:43 +00:00
// decimal bigint
[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-03 02:34:34 +00:00
// decimal
AST: numeric separators, BigInt (#5272) * Revert to more complicated lexing of numbers, as the Number constructor can't handle BigInts or numbers with numeric separators * Add debugging information to error message test (#5239) One of the test cases in test/error_messages.coffee fails intermittently in the Node.js ecosystem-testing tool CITGM. In an effort to help debug what's going on when this occurs, this adds more information to the AssertionError message in question. * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Numeric literal separators (#5215) * implement numeric literal separators * add tests * Revert changes to package-lock.json * small regex adjustment * split tests * add comment * Add Node versions to CI * Fix #5103: Add support for BigInt literals (#5104) * Fix #5103: Add support for BigInt literals * Fix typos found in testing * Support binary, octal and hex BigInt literals * Make decimal BigInt test consistent other bases * Correct test BigInt test names * Add Node versions to CI * Update output * Fix style * support bigint literal with separators * un-disallow property access on number literal * Update output * Refactor numeric literal separator tests to be more like the rest of the tests * Add test for numeric property with underscore Co-authored-by: Geoffrey Booth <GeoffreyBooth@users.noreply.github.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> * Update test style and output * numeric separator parsed value * BigInt AST; parseNumber() Co-authored-by: Geoffrey Booth <GeoffreyBooth@users.noreply.github.com> Co-authored-by: Rich Trott <rtrott@gmail.com> Co-authored-by: Robert de Forest <guitar.robot@gmail.com> Co-authored-by: square <Inve1951@users.noreply.github.com>
2019-12-30 00:20:43 +00:00
// decimal without support for numeric literal separators for reference:
// \d*\.?\d+ (?:e[+-]?\d+)?
[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-03 02:34:34 +00:00
OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>*\/%])\2=?|\?(\.|::)|\.{2,3})/; // function
// compound assign / compare
// zero-fill right shift
// doubles
// logic / shift / power / floor division / modulo
// soak access
// range or splat
WHITESPACE = /^[^\n\S]+/;
COMMENT = /^(\s*)###([^#][\s\S]*?)(?:###([^\n\S]*)|###$)|^((?:\s*#(?!##[^#]).*)+)/;
2014-09-06 10:55:27 +00:00
CODE = /^[-=]>/;
MULTI_DENT = /^(?:\n[^\n\S]*)+/;
JSTOKEN = /^`(?!``)((?:[^`\\]|\\[\s\S])*)`/;
HERE_JSTOKEN = /^```((?:[^`\\]|\\[\s\S]|`(?!``))*)```/;
[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-03 02:34:34 +00:00
// String-matching-regexes.
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
STRING_START = /^(?:'''|"""|'|")/;
STRING_SINGLE = /^(?:[^\\']|\\[\s\S])*/;
STRING_DOUBLE = /^(?:[^\\"#]|\\[\s\S]|\#(?!\{))*/;
HEREDOC_SINGLE = /^(?:[^\\']|\\[\s\S]|'(?!''))*/;
HEREDOC_DOUBLE = /^(?:[^\\"#]|\\[\s\S]|"(?!"")|\#(?!\{))*/;
INSIDE_JSX = /^(?:[^\{<])*/; // Start of CoffeeScript interpolation. // Similar to `HEREDOC_DOUBLE` but there is no escaping.
// Maybe JSX tag (`<` not allowed even if bare).
JSX_INTERPOLATION = /^(?:\{|<(?!\/))/; // CoffeeScript interpolation.
// JSX opening tag.
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
HEREDOC_INDENT = /\n+([^\n\S]*)(?=\S)/g;
[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-03 02:34:34 +00:00
// Regex-matching-regexes.
REGEX = /^\/(?!\/)((?:[^[\/\n\\]|\\[^\n]|\[(?:\\[^\n]|[^\]\n\\])*\])*)(\/)?/; // Every other thing.
// Anything but newlines escaped.
// Character class.
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
REGEX_FLAGS = /^\w*/;
VALID_FLAGS = /^(?!.*(.).*\1)[gimsuy]*$/;
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
HEREGEX = /^(?:[^\\\/#\s]|\\[\s\S]|\/(?!\/\/)|\#(?!\{)|\s+(?:#(?!\{).*)?)*/; // Match any character, except those that need special handling below.
// Match `\` followed by any character.
// Match any `/` except `///`.
// Match `#` which is not part of interpolation, e.g. `#{}`.
// Comments consume everything until the end of the line, including `///`.
HEREGEX_COMMENT = /(\s+)(#(?!{).*)/gm;
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
REGEX_ILLEGAL = /^(\/|\/{3}\s*)(\*)/;
Fix #3410, #3182: Allow regex to start with space or = A regex may not follow a specific set of tokens. These were already known before in the `NOT_REGEX` and `NOT_SPACED_REGEX` arrays. (However, I've refactored them to be more correct and to add a few missing tokens). In all other cases (except after a spaced callable) a slash is the start of a regex, and may now start with a space or an equals sign. It’s really that simple! A slash after a spaced callable is the only ambigous case. We cannot know if that's division or function application with a regex as the argument. The spacing determines which is which: Space on both sides: - `a / b/i` -> `a / b / i` - `a /= b/i` -> `a /= b / i` No spaces: - `a/b/i` -> `a / b / i` - `a/=b/i` -> `a /= b / i` Space on the right side: - `a/ b/i` -> `a / b / i` - `a/= b/i` -> `a /= b / i` Space on the left side: - `a /b/i` -> `a(/b/i)` - `a /=b/i` -> `a(/=b/i)` The last case used to compile to `a /= b / i`, but that has been changed to be consistent with the `/` operator. The last case really looks like a regex, so it should be parsed as one. Moreover, you may now also space the `/` and `/=` operators with other whitespace characters than a space (such as tabs and non-breaking spaces) for consistency. Lastly, unclosed regexes are now reported as such, instead of generating some other confusing error message. It should perhaps also be noted that apart from escaping (such as `a /\ b/`) you may now also use parentheses to disambiguate division and regex: `a (/ b/)`. See https://github.com/jashkenas/coffeescript/issues/3182#issuecomment-26688427.
2015-01-10 00:48:00 +00:00
POSSIBLY_DIVISION = /^\/=?\s/;
[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-03 02:34:34 +00:00
// Other regexes.
Refactor interpolation (and string and regex) handling in lexer - Fix #3394: Unclosed single-quoted strings (both regular ones and heredocs) used to pass through the lexer, causing a parsing error later, while double-quoted strings caused an error already in the lexing phase. Now both single and double-quoted unclosed strings error out in the lexer (which is the more logical option) with consistent error messages. This also fixes the last comment by @satyr in #3301. - Similar to the above, unclosed heregexes also used to pass through the lexer and not error until in the parsing phase, which resulted in confusing error messages. This has been fixed, too. - Fix #3348, by adding passing tests. - Fix #3529: If a string starts with an interpolation, an empty string is no longer emitted before the interpolation (unless it is needed to coerce the interpolation into a string). - Block comments cannot contain `*/`. Now the error message also shows exactly where the offending `*/`. This improvement might seem unrelated, but I had to touch that code anyway to refactor string and regex related code, and the change was very trivial. Moreover, it's consistent with the next two points. - Regexes cannot start with `*`. Now the error message also shows exactly where the offending `*` is. (It might actually not be exatly at the start in heregexes.) It is a very minor improvement, but it was trivial to add. - Octal escapes in strings are forbidden in CoffeeScript (just like in JavaScript strict mode). However, this used to be the case only for regular strings. Now they are also forbidden in heredocs. Moreover, the errors now point at the offending octal escape. - Invalid regex flags are no longer allowed. This includes repeated modifiers and unknown ones. Moreover, invalid modifiers do not stop a heregex from being matched, which results in better error messages. - Fix #3621: `///a#{1}///` compiles to `RegExp("a" + 1)`. So does `RegExp("a#{1}")`. Still, those two code snippets used to generate different tokens, which is a bit weird, but more importantly causes problems for coffeelint (see clutchski/coffeelint#340). This required lots of tests in test/location.coffee to be updated. Note that some updates to those tests are unrelated to this point; some have been updated to be more consistent (I discovered this because the refactored code happened to be seemingly more correct). - Regular regex literals used to erraneously allow newlines to be escaped, causing invalid JavaScript output. This has been fixed. - Heregexes may now be completely empty (`//////`), instead of erroring out with a confusing message. - Fix #2388: Heredocs and heregexes used to be lexed simply, which meant that you couldn't nest a heredoc within a heredoc (double-quoted, that is) or a heregex inside a heregex. - Fix #2321: If you used division inside interpolation and then a slash later in the string containing that interpolation, the division slash and the latter slash was erraneously matched as a regex. This has been fixed. - Indentation inside interpolations in heredocs no longer affect how much indentation is removed from each line of the heredoc (which is more intuitive). - Whitespace is now correctly trimmed from the start and end of strings in a few edge cases. - Last but not least, the lexing of interpolated strings now seems to be more efficient. For a regular double-quoted string, we used to use a custom function to find the end of it (taking interpolations and interpolations within interpolations etc. into account). Then we used to re-find the interpolations and recursively lex their contents. In effect, the same string was processed twice, or even more in the case of deeper nesting of interpolations. Now the same string is processed just once. - Code duplication between regular strings, heredocs, regular regexes and heregexes has been reduced. - The above two points should result in more easily read code, too.
2015-01-03 22:40:43 +00:00
HERECOMMENT_ILLEGAL = /\*\//;
LINE_CONTINUER = /^\s*(?:,|\??\.(?![.\d])|\??::)/;
STRING_INVALID_ESCAPE = /((?:^|[^\\])(?:\\\\)*)\\(?:(0\d|[1-7])|(x(?![\da-fA-F]{2}).{0,2})|(u\{(?![\da-fA-F]{1,}\})[^}]*\}?)|(u(?!\{|[\da-fA-F]{4}).{0,4}))/; // Make sure the escape isnt escaped.
[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-03 02:34:34 +00:00
// octal escape
// hex escape
// unicode code point escape
// unicode escape
REGEX_INVALID_ESCAPE = /((?:^|[^\\])(?:\\\\)*)\\(?:(0\d)|(x(?![\da-fA-F]{2}).{0,2})|(u\{(?![\da-fA-F]{1,}\})[^}]*\}?)|(u(?!\{|[\da-fA-F]{4}).{0,4}))/; // Make sure the escape isnt escaped.
[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-03 02:34:34 +00:00
// octal escape
// hex escape
// unicode code point escape
// unicode escape
2010-10-03 23:22:42 +00:00
TRAILING_SPACES = /\s+$/;
[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-03 02:34:34 +00:00
// Compound assignment tokens.
COMPOUND_ASSIGN = ['-=', '+=', '/=', '*=', '%=', '||=', '&&=', '?=', '<<=', '>>=', '>>>=', '&=', '^=', '|=', '**=', '//=', '%%='];
[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-03 02:34:34 +00:00
// Unary tokens.
UNARY = ['NEW', 'TYPEOF', 'DELETE'];
UNARY_MATH = ['!', '~'];
[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-03 02:34:34 +00:00
// Bit-shifting tokens.
SHIFT = ['<<', '>>', '>>>'];
[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-03 02:34:34 +00:00
// Comparison tokens.
2010-10-23 18:24:30 +00:00
COMPARE = ['==', '!=', '<', '>', '<=', '>='];
[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-03 02:34:34 +00:00
// Mathematical tokens.
MATH = ['*', '/', '%', '//', '%%'];
[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-03 02:34:34 +00:00
// Relational tokens that are negatable with `not` prefix.
RELATION = ['IN', 'OF', 'INSTANCEOF'];
[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-03 02:34:34 +00:00
// Boolean tokens.
BOOL = ['TRUE', 'FALSE'];
[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-03 02:34:34 +00:00
// Tokens which could legitimately be invoked or indexed. An opening
// parentheses or bracket following these tokens will be recorded as the start
// of a function invocation or indexing operation.
CALLABLE = ['IDENTIFIER', 'PROPERTY', ')', ']', '?', '@', 'THIS', 'SUPER', 'DYNAMIC_IMPORT'];
INDEXABLE = CALLABLE.concat(['NUMBER', 'INFINITY', 'NAN', 'STRING', 'STRING_END', 'REGEX', 'REGEX_END', 'BOOL', 'NULL', 'UNDEFINED', '}', '::']);
[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-03 02:34:34 +00:00
// Tokens which can be the left-hand side of a less-than comparison, i.e. `a<b`.
COMPARABLE_LEFT_SIDE = ['IDENTIFIER', ')', ']', 'NUMBER'];
[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-03 02:34:34 +00:00
// Tokens which a regular expression will never immediately follow (except spaced
// CALLABLEs in some cases), but which a division operator can.
// See: http://www-archive.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions
Fix #3410, #3182: Allow regex to start with space or = A regex may not follow a specific set of tokens. These were already known before in the `NOT_REGEX` and `NOT_SPACED_REGEX` arrays. (However, I've refactored them to be more correct and to add a few missing tokens). In all other cases (except after a spaced callable) a slash is the start of a regex, and may now start with a space or an equals sign. It’s really that simple! A slash after a spaced callable is the only ambigous case. We cannot know if that's division or function application with a regex as the argument. The spacing determines which is which: Space on both sides: - `a / b/i` -> `a / b / i` - `a /= b/i` -> `a /= b / i` No spaces: - `a/b/i` -> `a / b / i` - `a/=b/i` -> `a /= b / i` Space on the right side: - `a/ b/i` -> `a / b / i` - `a/= b/i` -> `a /= b / i` Space on the left side: - `a /b/i` -> `a(/b/i)` - `a /=b/i` -> `a(/=b/i)` The last case used to compile to `a /= b / i`, but that has been changed to be consistent with the `/` operator. The last case really looks like a regex, so it should be parsed as one. Moreover, you may now also space the `/` and `/=` operators with other whitespace characters than a space (such as tabs and non-breaking spaces) for consistency. Lastly, unclosed regexes are now reported as such, instead of generating some other confusing error message. It should perhaps also be noted that apart from escaping (such as `a /\ b/`) you may now also use parentheses to disambiguate division and regex: `a (/ b/)`. See https://github.com/jashkenas/coffeescript/issues/3182#issuecomment-26688427.
2015-01-10 00:48:00 +00:00
NOT_REGEX = INDEXABLE.concat(['++', '--']);
[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-03 02:34:34 +00:00
// Tokens that, when immediately preceding a `WHEN`, indicate that the `WHEN`
// occurs at the start of a line. We disambiguate these from trailing whens to
// avoid an ambiguity in the grammar.
LINE_BREAK = ['INDENT', 'OUTDENT', 'TERMINATOR'];
2011-12-14 15:39:20 +00: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-03 02:34:34 +00:00
// Additional indent in front of these is ignored.
2014-01-22 18:30:13 +00:00
INDENTABLE_CLOSERS = [')', '}', ']'];
}).call(this);