2016-10-22 14:48:54 -04:00
|
|
|
// Generated by CoffeeScript 2.0.0-alpha
|
2010-07-24 11:31:43 -04:00
|
|
|
(function() {
|
2017-01-22 16:20:18 -05:00
|
|
|
var Lexer, SourceMap, base64encode, compile, ext, fn1, formatSourcePosition, fs, getSourceMap, helpers, i, len, lexer, packageJson, parser, path, ref, sourceMaps, sources, vm, withPrettyErrors,
|
2016-09-14 15:45:06 -04:00
|
|
|
hasProp = {}.hasOwnProperty;
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2010-10-24 14:19:47 -04:00
|
|
|
fs = require('fs');
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2013-03-17 23:46:54 -04:00
|
|
|
vm = require('vm');
|
|
|
|
|
2010-09-21 05:19:49 -04:00
|
|
|
path = require('path');
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2012-09-25 19:01:16 -04:00
|
|
|
Lexer = require('./lexer').Lexer;
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2010-09-28 16:47:12 -04:00
|
|
|
parser = require('./parser').parser;
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2013-02-27 21:54:17 -05:00
|
|
|
helpers = require('./helpers');
|
2013-02-28 15:51:29 -05:00
|
|
|
|
2013-03-18 07:23:05 -04:00
|
|
|
SourceMap = require('./sourcemap');
|
2012-09-25 19:01:16 -04:00
|
|
|
|
2016-12-15 23:52:31 -05:00
|
|
|
packageJson = require('../../package.json');
|
|
|
|
|
|
|
|
exports.VERSION = packageJson.version;
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2013-10-20 10:08:13 -04:00
|
|
|
exports.FILE_EXTENSIONS = ['.coffee', '.litcoffee', '.coffee.md'];
|
2013-07-30 00:06:41 -04:00
|
|
|
|
2013-03-04 16:40:39 -05:00
|
|
|
exports.helpers = helpers;
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2016-01-31 13:48:40 -05:00
|
|
|
base64encode = function(src) {
|
|
|
|
switch (false) {
|
|
|
|
case typeof Buffer !== 'function':
|
2016-10-21 12:56:25 -04:00
|
|
|
return Buffer.from(src).toString('base64');
|
2016-01-31 13:48:40 -05:00
|
|
|
case typeof btoa !== 'function':
|
2016-11-28 02:05:49 -05:00
|
|
|
return btoa(encodeURIComponent(src).replace(/%([0-9A-F]{2})/g, function(match, p1) {
|
|
|
|
return String.fromCharCode('0x' + p1);
|
|
|
|
}));
|
2016-01-31 13:48:40 -05:00
|
|
|
default:
|
|
|
|
throw new Error('Unable to base64 encode inline sourcemap.');
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-07-31 07:27:49 -04:00
|
|
|
withPrettyErrors = function(fn) {
|
[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 01:26:13 -04:00
|
|
|
return function(code, options = {}) {
|
2015-09-13 06:27:07 -04:00
|
|
|
var err;
|
2013-07-31 07:27:49 -04:00
|
|
|
try {
|
|
|
|
return fn.call(this, code, options);
|
2015-08-16 16:34:22 -04:00
|
|
|
} catch (error) {
|
|
|
|
err = error;
|
2015-05-01 07:43:04 -04:00
|
|
|
if (typeof code !== 'string') {
|
|
|
|
throw err;
|
|
|
|
}
|
2013-08-02 00:52:36 -04:00
|
|
|
throw helpers.updateSyntaxError(err, code, options.filename);
|
2013-07-31 07:27:49 -04:00
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
2017-01-22 16:20:18 -05:00
|
|
|
sources = {};
|
|
|
|
|
|
|
|
sourceMaps = {};
|
|
|
|
|
2013-07-31 07:27:49 -04:00
|
|
|
exports.compile = compile = withPrettyErrors(function(code, options) {
|
2017-01-22 16:20:18 -05:00
|
|
|
var currentColumn, currentLine, encoded, extend, filename, fragment, fragments, generateSourceMap, header, i, j, js, len, len1, map, merge, newLines, ref, ref1, sourceMapDataURI, sourceURL, token, tokens, v3SourceMap;
|
2013-10-20 15:21:06 -04:00
|
|
|
merge = helpers.merge, extend = helpers.extend;
|
|
|
|
options = extend({}, options);
|
2017-01-22 16:20:18 -05:00
|
|
|
generateSourceMap = options.sourceMap || options.inlineMap || (options.filename == null);
|
|
|
|
filename = options.filename || '<anonymous>';
|
|
|
|
sources[filename] = code;
|
2016-01-31 13:48:40 -05:00
|
|
|
if (generateSourceMap) {
|
2013-03-18 07:23:05 -04:00
|
|
|
map = new SourceMap;
|
2013-03-04 21:37:36 -05:00
|
|
|
}
|
Fix #1500, #1574, #3318: Name generated vars uniquely
Any variables generated by CoffeeScript are now made sure to be named to
something not present in the source code being compiled. This way you can no
longer interfere with them, either on purpose or by mistake. (#1500, #1574)
For example, `({a}, _arg) ->` now compiles correctly. (#1574)
As opposed to the somewhat complex implementations discussed in #1500, this
commit takes a very simple approach by saving all used variables names using a
single pass over the token stream. Any generated variables are then made sure
not to exist in that list.
`(@a) -> a` used to be equivalent to `(@a) -> @a`, but now throws a runtime
`ReferenceError` instead (unless `a` exists in an upper scope of course). (#3318)
`(@a) ->` used to compile to `(function(a) { this.a = a; })`. Now it compiles to
`(function(_at_a) { this.a = _at_a; })`. (But you cannot access `_at_a` either,
of course.)
Because of the above, `(@a, a) ->` is now valid; `@a` and `a` are not duplicate
parameters.
Duplicate this-parameters with a reserved word, such as `(@case, @case) ->`,
used to compile but now throws, just like regular duplicate parameters.
2015-01-10 17:04:30 -05:00
|
|
|
tokens = lexer.tokenize(code, options);
|
|
|
|
options.referencedVars = (function() {
|
2015-01-30 14:33:03 -05:00
|
|
|
var i, len, results;
|
|
|
|
results = [];
|
|
|
|
for (i = 0, len = tokens.length; i < len; i++) {
|
|
|
|
token = tokens[i];
|
2016-03-05 11:41:15 -05:00
|
|
|
if (token[0] === 'IDENTIFIER') {
|
2015-01-30 14:33:03 -05:00
|
|
|
results.push(token[1]);
|
Fix #1500, #1574, #3318: Name generated vars uniquely
Any variables generated by CoffeeScript are now made sure to be named to
something not present in the source code being compiled. This way you can no
longer interfere with them, either on purpose or by mistake. (#1500, #1574)
For example, `({a}, _arg) ->` now compiles correctly. (#1574)
As opposed to the somewhat complex implementations discussed in #1500, this
commit takes a very simple approach by saving all used variables names using a
single pass over the token stream. Any generated variables are then made sure
not to exist in that list.
`(@a) -> a` used to be equivalent to `(@a) -> @a`, but now throws a runtime
`ReferenceError` instead (unless `a` exists in an upper scope of course). (#3318)
`(@a) ->` used to compile to `(function(a) { this.a = a; })`. Now it compiles to
`(function(_at_a) { this.a = _at_a; })`. (But you cannot access `_at_a` either,
of course.)
Because of the above, `(@a, a) ->` is now valid; `@a` and `a` are not duplicate
parameters.
Duplicate this-parameters with a reserved word, such as `(@case, @case) ->`,
used to compile but now throws, just like regular duplicate parameters.
2015-01-10 17:04:30 -05:00
|
|
|
}
|
|
|
|
}
|
2015-01-30 14:33:03 -05:00
|
|
|
return results;
|
Fix #1500, #1574, #3318: Name generated vars uniquely
Any variables generated by CoffeeScript are now made sure to be named to
something not present in the source code being compiled. This way you can no
longer interfere with them, either on purpose or by mistake. (#1500, #1574)
For example, `({a}, _arg) ->` now compiles correctly. (#1574)
As opposed to the somewhat complex implementations discussed in #1500, this
commit takes a very simple approach by saving all used variables names using a
single pass over the token stream. Any generated variables are then made sure
not to exist in that list.
`(@a) -> a` used to be equivalent to `(@a) -> @a`, but now throws a runtime
`ReferenceError` instead (unless `a` exists in an upper scope of course). (#3318)
`(@a) ->` used to compile to `(function(a) { this.a = a; })`. Now it compiles to
`(function(_at_a) { this.a = _at_a; })`. (But you cannot access `_at_a` either,
of course.)
Because of the above, `(@a, a) ->` is now valid; `@a` and `a` are not duplicate
parameters.
Duplicate this-parameters with a reserved word, such as `(@case, @case) ->`,
used to compile but now throws, just like regular duplicate parameters.
2015-01-10 17:04:30 -05:00
|
|
|
})();
|
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 14:46:05 -04:00
|
|
|
if (!((options.bare != null) && options.bare === true)) {
|
|
|
|
for (i = 0, len = tokens.length; i < len; i++) {
|
|
|
|
token = tokens[i];
|
|
|
|
if ((ref = token[0]) === 'IMPORT' || ref === 'EXPORT') {
|
|
|
|
options.bare = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
Fix #1500, #1574, #3318: Name generated vars uniquely
Any variables generated by CoffeeScript are now made sure to be named to
something not present in the source code being compiled. This way you can no
longer interfere with them, either on purpose or by mistake. (#1500, #1574)
For example, `({a}, _arg) ->` now compiles correctly. (#1574)
As opposed to the somewhat complex implementations discussed in #1500, this
commit takes a very simple approach by saving all used variables names using a
single pass over the token stream. Any generated variables are then made sure
not to exist in that list.
`(@a) -> a` used to be equivalent to `(@a) -> @a`, but now throws a runtime
`ReferenceError` instead (unless `a` exists in an upper scope of course). (#3318)
`(@a) ->` used to compile to `(function(a) { this.a = a; })`. Now it compiles to
`(function(_at_a) { this.a = _at_a; })`. (But you cannot access `_at_a` either,
of course.)
Because of the above, `(@a, a) ->` is now valid; `@a` and `a` are not duplicate
parameters.
Duplicate this-parameters with a reserved word, such as `(@case, @case) ->`,
used to compile but now throws, just like regular duplicate parameters.
2015-01-10 17:04:30 -05:00
|
|
|
fragments = parser.parse(tokens).compileToFragments(options);
|
2013-03-04 21:37:36 -05:00
|
|
|
currentLine = 0;
|
2013-03-25 13:56:24 -04:00
|
|
|
if (options.header) {
|
|
|
|
currentLine += 1;
|
|
|
|
}
|
|
|
|
if (options.shiftLine) {
|
2013-03-04 21:37:36 -05:00
|
|
|
currentLine += 1;
|
|
|
|
}
|
|
|
|
currentColumn = 0;
|
|
|
|
js = "";
|
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 14:46:05 -04:00
|
|
|
for (j = 0, len1 = fragments.length; j < len1; j++) {
|
|
|
|
fragment = fragments[j];
|
2016-01-31 13:48:40 -05:00
|
|
|
if (generateSourceMap) {
|
2015-05-13 11:50:02 -04:00
|
|
|
if (fragment.locationData && !/^[;\s]*$/.test(fragment.code)) {
|
2013-03-18 07:23:05 -04:00
|
|
|
map.add([fragment.locationData.first_line, fragment.locationData.first_column], [currentLine, currentColumn], {
|
2013-03-04 21:37:36 -05:00
|
|
|
noReplace: true
|
|
|
|
});
|
2013-02-28 15:51:29 -05:00
|
|
|
}
|
2013-03-04 21:37:36 -05:00
|
|
|
newLines = helpers.count(fragment.code, "\n");
|
|
|
|
currentLine += newLines;
|
2013-08-06 16:25:23 -04:00
|
|
|
if (newLines) {
|
|
|
|
currentColumn = fragment.code.length - (fragment.code.lastIndexOf("\n") + 1);
|
|
|
|
} else {
|
|
|
|
currentColumn += fragment.code.length;
|
|
|
|
}
|
2013-02-28 15:51:29 -05:00
|
|
|
}
|
2013-03-04 21:37:36 -05:00
|
|
|
js += fragment.code;
|
2010-03-07 22:08:24 -05:00
|
|
|
}
|
2013-02-25 17:20:37 -05:00
|
|
|
if (options.header) {
|
2016-11-28 09:05:51 -05:00
|
|
|
header = `Generated by CoffeeScript ${this.VERSION}`;
|
|
|
|
js = `// ${header}\n${js}`;
|
2010-03-07 22:08:24 -05:00
|
|
|
}
|
2016-01-31 13:48:40 -05:00
|
|
|
if (generateSourceMap) {
|
|
|
|
v3SourceMap = map.generate(options, code);
|
2017-01-22 16:20:18 -05:00
|
|
|
sourceMaps[filename] = map;
|
2016-01-31 13:48:40 -05:00
|
|
|
}
|
|
|
|
if (options.inlineMap) {
|
Improve inline source maps generation
- Inline source maps are now shorter by not using pretty-printed JSON.
- `.register()`ed files are now given more information in their inline source
maps: The name and contents of the source file.
- Some code cleanup.
If you decode the inline source map generated (when using `.register()`) for a
file test.coffee with the contents `console.log "it works!"`, here is the
output:
Before:
{
"version": 3,
"file": "",
"sourceRoot": "",
"sources": [
""
],
"names": [],
"mappings": "AAAA;EAAA,OAAO,CAAC,GAAR,CAAY,eAAZ;AAAA"
}
After:
{"version":3,"file":"","sourceRoot":"","sources":["test.coffee"],"names":[],"mappings":"AAAA;EAAA,OAAO,CAAC,GAAR,CAAY,WAAZ;AAAA","sourcesContent":["console.log \"it works!\"\n"]}
Related: #4214.
2016-03-06 08:30:47 -05:00
|
|
|
encoded = base64encode(JSON.stringify(v3SourceMap));
|
2016-11-28 09:05:51 -05:00
|
|
|
sourceMapDataURI = `//# sourceMappingURL=data:application/json;base64,${encoded}`;
|
|
|
|
sourceURL = `//# sourceURL=${(ref1 = options.filename) != null ? ref1 : 'coffeescript'}`;
|
|
|
|
js = `${js}\n${sourceMapDataURI}\n${sourceURL}`;
|
2016-01-31 13:48:40 -05:00
|
|
|
}
|
2013-03-04 16:19:21 -05:00
|
|
|
if (options.sourceMap) {
|
Improve inline source maps generation
- Inline source maps are now shorter by not using pretty-printed JSON.
- `.register()`ed files are now given more information in their inline source
maps: The name and contents of the source file.
- Some code cleanup.
If you decode the inline source map generated (when using `.register()`) for a
file test.coffee with the contents `console.log "it works!"`, here is the
output:
Before:
{
"version": 3,
"file": "",
"sourceRoot": "",
"sources": [
""
],
"names": [],
"mappings": "AAAA;EAAA,OAAO,CAAC,GAAR,CAAY,eAAZ;AAAA"
}
After:
{"version":3,"file":"","sourceRoot":"","sources":["test.coffee"],"names":[],"mappings":"AAAA;EAAA,OAAO,CAAC,GAAR,CAAY,WAAZ;AAAA","sourcesContent":["console.log \"it works!\"\n"]}
Related: #4214.
2016-03-06 08:30:47 -05:00
|
|
|
return {
|
|
|
|
js: js,
|
|
|
|
sourceMap: map,
|
|
|
|
v3SourceMap: JSON.stringify(v3SourceMap, null, 2)
|
2013-03-01 11:34:39 -05:00
|
|
|
};
|
2013-03-04 09:45:25 -05:00
|
|
|
} else {
|
|
|
|
return js;
|
2013-02-28 15:51:29 -05:00
|
|
|
}
|
2013-07-31 07:27:49 -04:00
|
|
|
});
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2013-07-31 07:27:49 -04:00
|
|
|
exports.tokens = withPrettyErrors(function(code, options) {
|
2010-10-08 15:27:05 -04:00
|
|
|
return lexer.tokenize(code, options);
|
2013-07-31 07:27:49 -04:00
|
|
|
});
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2013-07-31 07:27:49 -04:00
|
|
|
exports.nodes = withPrettyErrors(function(source, options) {
|
2010-11-17 11:34:23 -05:00
|
|
|
if (typeof source === 'string') {
|
2010-11-20 16:25:22 -05:00
|
|
|
return parser.parse(lexer.tokenize(source, options));
|
2010-11-17 11:34:23 -05:00
|
|
|
} else {
|
|
|
|
return parser.parse(source);
|
|
|
|
}
|
2013-07-31 07:27:49 -04:00
|
|
|
});
|
2011-09-18 18:16:39 -04:00
|
|
|
|
[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 01:26:13 -04:00
|
|
|
exports.run = function(code, options = {}) {
|
2015-01-30 14:33:03 -05:00
|
|
|
var answer, dir, mainModule, ref;
|
2011-05-03 15:53:10 -04:00
|
|
|
mainModule = require.main;
|
2017-01-22 16:20:18 -05:00
|
|
|
mainModule.filename = process.argv[1] = options.filename ? fs.realpathSync(options.filename) : '<anonymous>';
|
2011-05-03 16:10:30 -04:00
|
|
|
mainModule.moduleCache && (mainModule.moduleCache = {});
|
2017-01-22 16:20:18 -05:00
|
|
|
dir = options.filename != null ? path.dirname(fs.realpathSync(options.filename)) : fs.realpathSync('.');
|
2013-10-20 16:50:13 -04:00
|
|
|
mainModule.paths = require('module')._nodeModulePaths(dir);
|
2013-02-27 21:54:17 -05:00
|
|
|
if (!helpers.isCoffee(mainModule.filename) || require.extensions) {
|
2013-03-12 02:26:51 -04:00
|
|
|
answer = compile(code, options);
|
2015-01-30 14:33:03 -05:00
|
|
|
code = (ref = answer.js) != null ? ref : answer;
|
2010-11-08 23:07:51 -05:00
|
|
|
}
|
2013-07-30 00:06:41 -04:00
|
|
|
return mainModule._compile(code, mainModule.filename);
|
2010-09-04 06:39:01 -04:00
|
|
|
};
|
2011-09-18 18:16:39 -04:00
|
|
|
|
[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 01:26:13 -04:00
|
|
|
exports["eval"] = function(code, options = {}) {
|
2015-01-30 14:33:03 -05:00
|
|
|
var Module, _module, _require, createContext, i, isContext, js, k, len, o, r, ref, ref1, ref2, ref3, sandbox, v;
|
2012-04-10 14:57:45 -04:00
|
|
|
if (!(code = code.trim())) {
|
|
|
|
return;
|
|
|
|
}
|
2015-01-30 14:33:03 -05:00
|
|
|
createContext = (ref = vm.Script.createContext) != null ? ref : vm.createContext;
|
|
|
|
isContext = (ref1 = vm.isContext) != null ? ref1 : function(ctx) {
|
2015-01-05 15:40:04 -05:00
|
|
|
return options.sandbox instanceof createContext().constructor;
|
|
|
|
};
|
|
|
|
if (createContext) {
|
2011-08-04 23:17:23 -04:00
|
|
|
if (options.sandbox != null) {
|
2015-01-05 15:40:04 -05:00
|
|
|
if (isContext(options.sandbox)) {
|
2011-08-04 23:17:23 -04:00
|
|
|
sandbox = options.sandbox;
|
|
|
|
} else {
|
2015-01-05 15:40:04 -05:00
|
|
|
sandbox = createContext();
|
2015-01-30 14:33:03 -05:00
|
|
|
ref2 = options.sandbox;
|
|
|
|
for (k in ref2) {
|
|
|
|
if (!hasProp.call(ref2, k)) continue;
|
|
|
|
v = ref2[k];
|
2011-08-04 23:17:23 -04:00
|
|
|
sandbox[k] = v;
|
|
|
|
}
|
2011-05-01 01:45:14 -04:00
|
|
|
}
|
2011-10-23 22:45:32 -04:00
|
|
|
sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox;
|
|
|
|
} else {
|
|
|
|
sandbox = global;
|
2011-04-29 13:59:59 -04:00
|
|
|
}
|
2011-08-04 23:17:23 -04:00
|
|
|
sandbox.__filename = options.filename || 'eval';
|
|
|
|
sandbox.__dirname = path.dirname(sandbox.__filename);
|
2011-10-23 22:45:32 -04:00
|
|
|
if (!(sandbox !== global || sandbox.module || sandbox.require)) {
|
2011-08-04 23:17:23 -04:00
|
|
|
Module = require('module');
|
|
|
|
sandbox.module = _module = new Module(options.modulename || 'eval');
|
|
|
|
sandbox.require = _require = function(path) {
|
2011-10-23 22:45:32 -04:00
|
|
|
return Module._load(path, _module, true);
|
2011-08-04 23:17:23 -04:00
|
|
|
};
|
|
|
|
_module.filename = sandbox.__filename;
|
2015-01-30 14:33:03 -05:00
|
|
|
ref3 = Object.getOwnPropertyNames(require);
|
|
|
|
for (i = 0, len = ref3.length; i < len; i++) {
|
|
|
|
r = ref3[i];
|
2015-06-22 08:36:29 -04:00
|
|
|
if (r !== 'paths' && r !== 'arguments' && r !== 'caller') {
|
2012-04-10 14:57:45 -04:00
|
|
|
_require[r] = require[r];
|
|
|
|
}
|
2011-08-04 23:17:23 -04:00
|
|
|
}
|
|
|
|
_require.paths = _module.paths = Module._nodeModulePaths(process.cwd());
|
|
|
|
_require.resolve = function(request) {
|
|
|
|
return Module._resolveFilename(request, _module);
|
|
|
|
};
|
2011-07-06 03:54:36 -04:00
|
|
|
}
|
|
|
|
}
|
2011-05-25 03:53:51 -04:00
|
|
|
o = {};
|
|
|
|
for (k in options) {
|
2015-01-30 14:33:03 -05:00
|
|
|
if (!hasProp.call(options, k)) continue;
|
2011-05-25 03:53:51 -04:00
|
|
|
v = options[k];
|
|
|
|
o[k] = v;
|
|
|
|
}
|
|
|
|
o.bare = true;
|
2011-07-06 16:31:48 -04:00
|
|
|
js = compile(code, o);
|
2011-10-23 22:45:32 -04:00
|
|
|
if (sandbox === global) {
|
|
|
|
return vm.runInThisContext(js);
|
2011-08-04 23:17:23 -04:00
|
|
|
} else {
|
2011-10-23 22:45:32 -04:00
|
|
|
return vm.runInContext(js, sandbox);
|
2011-08-04 23:17:23 -04:00
|
|
|
}
|
2010-09-21 01:36:23 -04:00
|
|
|
};
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2013-12-08 15:21:18 -05:00
|
|
|
exports.register = function() {
|
|
|
|
return require('./register');
|
|
|
|
};
|
|
|
|
|
2014-02-22 21:40:19 -05:00
|
|
|
if (require.extensions) {
|
2015-01-30 14:33:03 -05:00
|
|
|
ref = this.FILE_EXTENSIONS;
|
2016-01-07 01:21:05 -05:00
|
|
|
fn1 = function(ext) {
|
|
|
|
var base;
|
|
|
|
return (base = require.extensions)[ext] != null ? base[ext] : base[ext] = function() {
|
2016-11-28 09:05:51 -05:00
|
|
|
throw new Error(`Use CoffeeScript.register() or require the coffee-script/register module to require ${ext} files.`);
|
2016-01-07 01:21:05 -05:00
|
|
|
};
|
|
|
|
};
|
2015-01-30 14:33:03 -05:00
|
|
|
for (i = 0, len = ref.length; i < len; i++) {
|
|
|
|
ext = ref[i];
|
2016-01-07 01:21:05 -05:00
|
|
|
fn1(ext);
|
2014-02-22 21:40:19 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
[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 01:26:13 -04:00
|
|
|
exports._compileFile = function(filename, sourceMap = false, inlineMap = false) {
|
2015-09-13 06:27:07 -04:00
|
|
|
var answer, err, raw, stripped;
|
2013-03-17 23:46:54 -04:00
|
|
|
raw = fs.readFileSync(filename, 'utf8');
|
|
|
|
stripped = raw.charCodeAt(0) === 0xFEFF ? raw.substring(1) : raw;
|
2013-06-09 01:54:34 -04:00
|
|
|
try {
|
|
|
|
answer = compile(stripped, {
|
|
|
|
filename: filename,
|
2013-07-30 00:06:41 -04:00
|
|
|
sourceMap: sourceMap,
|
2016-01-31 13:48:40 -05:00
|
|
|
inlineMap: inlineMap,
|
Improve inline source maps generation
- Inline source maps are now shorter by not using pretty-printed JSON.
- `.register()`ed files are now given more information in their inline source
maps: The name and contents of the source file.
- Some code cleanup.
If you decode the inline source map generated (when using `.register()`) for a
file test.coffee with the contents `console.log "it works!"`, here is the
output:
Before:
{
"version": 3,
"file": "",
"sourceRoot": "",
"sources": [
""
],
"names": [],
"mappings": "AAAA;EAAA,OAAO,CAAC,GAAR,CAAY,eAAZ;AAAA"
}
After:
{"version":3,"file":"","sourceRoot":"","sources":["test.coffee"],"names":[],"mappings":"AAAA;EAAA,OAAO,CAAC,GAAR,CAAY,WAAZ;AAAA","sourcesContent":["console.log \"it works!\"\n"]}
Related: #4214.
2016-03-06 08:30:47 -05:00
|
|
|
sourceFiles: [filename],
|
2013-06-09 01:54:34 -04:00
|
|
|
literate: helpers.isLiterate(filename)
|
|
|
|
});
|
2015-08-16 16:34:22 -04:00
|
|
|
} catch (error) {
|
|
|
|
err = error;
|
2013-08-02 00:52:36 -04:00
|
|
|
throw helpers.updateSyntaxError(err, stripped, filename);
|
2013-06-09 01:54:34 -04:00
|
|
|
}
|
2013-07-30 00:06:41 -04:00
|
|
|
return answer;
|
|
|
|
};
|
|
|
|
|
2010-09-25 04:39:19 -04:00
|
|
|
lexer = new Lexer;
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2010-02-11 01:57:33 -05:00
|
|
|
parser.lexer = {
|
2010-05-14 23:40:04 -04:00
|
|
|
lex: function() {
|
2012-11-21 16:57:30 -05:00
|
|
|
var tag, token;
|
2015-01-15 11:47:07 -05:00
|
|
|
token = parser.tokens[this.pos++];
|
2013-01-14 15:20:35 -05:00
|
|
|
if (token) {
|
|
|
|
tag = token[0], this.yytext = token[1], this.yylloc = token[2];
|
2015-01-15 11:47:07 -05:00
|
|
|
parser.errorToken = token.origin || token;
|
2013-01-14 15:20:35 -05:00
|
|
|
this.yylineno = this.yylloc.first_line;
|
|
|
|
} else {
|
|
|
|
tag = '';
|
|
|
|
}
|
2010-11-02 00:05:06 -04:00
|
|
|
return tag;
|
2010-02-11 01:57:33 -05:00
|
|
|
},
|
2015-01-15 11:47:07 -05:00
|
|
|
setInput: function(tokens) {
|
|
|
|
parser.tokens = tokens;
|
2010-10-20 18:19:08 -04:00
|
|
|
return this.pos = 0;
|
2010-02-11 01:57:33 -05:00
|
|
|
},
|
2010-05-14 23:40:04 -04:00
|
|
|
upcomingInput: function() {
|
2010-02-11 01:57:33 -05:00
|
|
|
return "";
|
|
|
|
}
|
|
|
|
};
|
2011-09-18 18:16:39 -04:00
|
|
|
|
2010-09-21 03:50:32 -04:00
|
|
|
parser.yy = require('./nodes');
|
2011-12-14 10:39:20 -05:00
|
|
|
|
2015-01-30 14:33:03 -05:00
|
|
|
parser.yy.parseError = function(message, arg) {
|
2015-01-15 11:47:07 -05:00
|
|
|
var errorLoc, errorTag, errorText, errorToken, token, tokens;
|
2015-01-30 14:33:03 -05:00
|
|
|
token = arg.token;
|
2015-01-15 11:47:07 -05:00
|
|
|
errorToken = parser.errorToken, tokens = parser.tokens;
|
2014-01-26 00:25:13 -05:00
|
|
|
errorTag = errorToken[0], errorText = errorToken[1], errorLoc = errorToken[2];
|
Fix #3597: Allow interpolations in object keys
The following is now allowed:
o =
a: 1
b: 2
"#{'c'}": 3
"#{'d'}": 4
e: 5
"#{'f'}": 6
g: 7
It compiles to:
o = (
obj = {
a: 1,
b: 2
},
obj["" + 'c'] = 3,
obj["" + 'd'] = 4,
obj.e = 5,
obj["" + 'f'] = 6,
obj.g = 7,
obj
);
- Closes #3039. Empty interpolations in object keys are now _supposed_ to be
allowed.
- Closes #1131. No need to improve error messages for attempted key
interpolation anymore.
- Implementing this required fixing the following bug: `("" + a): 1` used to
error out on the colon, saying "unexpected colon". But really, it is the
attempted object key that is unexpected. Now the error is on the opening
parenthesis instead.
- However, the above fix broke some error message tests for regexes. The easiest
way to fix this was to make a seemingly unrelated change: The error messages
for unexpected identifiers, numbers, strings and regexes now say for example
'unexpected string' instead of 'unexpected """some #{really long} string"""'.
In other words, the tag _name_ is used instead of the tag _value_.
This was way easier to implement, and is more helpful to the user. Using the
tag value is good for operators, reserved words and the like, but not for
tokens which can contain any text. For example, 'unexpected identifier' is
better than 'unexpected expected' (if a variable called 'expected' was used
erraneously).
- While writing tests for the above point I found a few minor bugs with string
locations which have been fixed.
2015-02-07 14:16:59 -05:00
|
|
|
errorText = (function() {
|
|
|
|
switch (false) {
|
|
|
|
case errorToken !== tokens[tokens.length - 1]:
|
|
|
|
return 'end of input';
|
|
|
|
case errorTag !== 'INDENT' && errorTag !== 'OUTDENT':
|
|
|
|
return 'indentation';
|
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 14:24:31 -05:00
|
|
|
case errorTag !== 'IDENTIFIER' && errorTag !== 'NUMBER' && errorTag !== 'INFINITY' && errorTag !== 'STRING' && errorTag !== 'STRING_START' && errorTag !== 'REGEX' && errorTag !== 'REGEX_START':
|
Fix #3597: Allow interpolations in object keys
The following is now allowed:
o =
a: 1
b: 2
"#{'c'}": 3
"#{'d'}": 4
e: 5
"#{'f'}": 6
g: 7
It compiles to:
o = (
obj = {
a: 1,
b: 2
},
obj["" + 'c'] = 3,
obj["" + 'd'] = 4,
obj.e = 5,
obj["" + 'f'] = 6,
obj.g = 7,
obj
);
- Closes #3039. Empty interpolations in object keys are now _supposed_ to be
allowed.
- Closes #1131. No need to improve error messages for attempted key
interpolation anymore.
- Implementing this required fixing the following bug: `("" + a): 1` used to
error out on the colon, saying "unexpected colon". But really, it is the
attempted object key that is unexpected. Now the error is on the opening
parenthesis instead.
- However, the above fix broke some error message tests for regexes. The easiest
way to fix this was to make a seemingly unrelated change: The error messages
for unexpected identifiers, numbers, strings and regexes now say for example
'unexpected string' instead of 'unexpected """some #{really long} string"""'.
In other words, the tag _name_ is used instead of the tag _value_.
This was way easier to implement, and is more helpful to the user. Using the
tag value is good for operators, reserved words and the like, but not for
tokens which can contain any text. For example, 'unexpected identifier' is
better than 'unexpected expected' (if a variable called 'expected' was used
erraneously).
- While writing tests for the above point I found a few minor bugs with string
locations which have been fixed.
2015-02-07 14:16:59 -05:00
|
|
|
return errorTag.replace(/_START$/, '').toLowerCase();
|
|
|
|
default:
|
|
|
|
return helpers.nameWhitespaceCharacter(errorText);
|
|
|
|
}
|
|
|
|
})();
|
2016-11-28 09:05:51 -05:00
|
|
|
return helpers.throwSyntaxError(`unexpected ${errorText}`, errorLoc);
|
2013-02-25 13:09:42 -05:00
|
|
|
};
|
|
|
|
|
2017-01-22 16:20:18 -05:00
|
|
|
formatSourcePosition = function(frame, getSourceMapping) {
|
|
|
|
var as, column, fileLocation, filename, functionName, isConstructor, isMethodCall, line, methodName, source, tp, typeName;
|
|
|
|
filename = void 0;
|
|
|
|
fileLocation = '';
|
|
|
|
if (frame.isNative()) {
|
|
|
|
fileLocation = "native";
|
|
|
|
} else {
|
|
|
|
if (frame.isEval()) {
|
|
|
|
filename = frame.getScriptNameOrSourceURL();
|
|
|
|
if (!filename) {
|
2017-01-22 19:32:38 -05:00
|
|
|
fileLocation = `${frame.getEvalOrigin()}, `;
|
2017-01-22 16:20:18 -05:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
filename = frame.getFileName();
|
|
|
|
}
|
|
|
|
filename || (filename = "<anonymous>");
|
|
|
|
line = frame.getLineNumber();
|
|
|
|
column = frame.getColumnNumber();
|
|
|
|
source = getSourceMapping(filename, line, column);
|
2017-01-22 19:32:38 -05:00
|
|
|
fileLocation = source ? `${filename}:${source[0]}:${source[1]}` : `${filename}:${line}:${column}`;
|
2017-01-22 16:20:18 -05:00
|
|
|
}
|
|
|
|
functionName = frame.getFunctionName();
|
|
|
|
isConstructor = frame.isConstructor();
|
|
|
|
isMethodCall = !(frame.isToplevel() || isConstructor);
|
|
|
|
if (isMethodCall) {
|
|
|
|
methodName = frame.getMethodName();
|
|
|
|
typeName = frame.getTypeName();
|
|
|
|
if (functionName) {
|
|
|
|
tp = as = '';
|
|
|
|
if (typeName && functionName.indexOf(typeName)) {
|
2017-01-22 19:32:38 -05:00
|
|
|
tp = `${typeName}.`;
|
2017-01-22 16:20:18 -05:00
|
|
|
}
|
2017-01-22 19:32:38 -05:00
|
|
|
if (methodName && functionName.indexOf(`.${methodName}`) !== functionName.length - methodName.length - 1) {
|
|
|
|
as = ` [as ${methodName}]`;
|
2017-01-22 16:20:18 -05:00
|
|
|
}
|
2017-01-22 19:32:38 -05:00
|
|
|
return `${tp}${functionName}${as} (${fileLocation})`;
|
2017-01-22 16:20:18 -05:00
|
|
|
} else {
|
2017-01-22 19:32:38 -05:00
|
|
|
return `${typeName}.${methodName || '<anonymous>'} (${fileLocation})`;
|
2017-01-22 16:20:18 -05:00
|
|
|
}
|
|
|
|
} else if (isConstructor) {
|
2017-01-22 19:32:38 -05:00
|
|
|
return `new ${functionName || '<anonymous>'} (${fileLocation})`;
|
2017-01-22 16:20:18 -05:00
|
|
|
} else if (functionName) {
|
2017-01-22 19:32:38 -05:00
|
|
|
return `${functionName} (${fileLocation})`;
|
2017-01-22 16:20:18 -05:00
|
|
|
} else {
|
|
|
|
return fileLocation;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
getSourceMap = function(filename) {
|
|
|
|
var answer;
|
|
|
|
if (sourceMaps[filename] != null) {
|
|
|
|
return sourceMaps[filename];
|
|
|
|
} else if (sourceMaps['<anonymous>'] != null) {
|
|
|
|
return sourceMaps['<anonymous>'];
|
|
|
|
} else if (sources[filename] != null) {
|
|
|
|
answer = compile(sources[filename], {
|
|
|
|
filename: filename,
|
2017-02-04 22:33:09 -05:00
|
|
|
sourceMap: true,
|
|
|
|
literate: helpers.isLiterate(filename)
|
2017-01-22 16:20:18 -05:00
|
|
|
});
|
|
|
|
return answer.sourceMap;
|
|
|
|
} else {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
Error.prepareStackTrace = function(err, stack) {
|
|
|
|
var frame, frames, getSourceMapping;
|
|
|
|
getSourceMapping = function(filename, line, column) {
|
|
|
|
var answer, sourceMap;
|
|
|
|
sourceMap = getSourceMap(filename);
|
|
|
|
if (sourceMap != null) {
|
|
|
|
answer = sourceMap.sourceLocation([line - 1, column - 1]);
|
|
|
|
}
|
|
|
|
if (answer != null) {
|
|
|
|
return [answer[0] + 1, answer[1] + 1];
|
|
|
|
} else {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
frames = (function() {
|
|
|
|
var j, len1, results;
|
|
|
|
results = [];
|
|
|
|
for (j = 0, len1 = stack.length; j < len1; j++) {
|
|
|
|
frame = stack[j];
|
|
|
|
if (frame.getFunction() === exports.run) {
|
|
|
|
break;
|
|
|
|
}
|
2017-01-22 19:32:38 -05:00
|
|
|
results.push(` at ${formatSourcePosition(frame, getSourceMapping)}`);
|
2017-01-22 16:20:18 -05:00
|
|
|
}
|
|
|
|
return results;
|
|
|
|
})();
|
2017-01-22 19:32:38 -05:00
|
|
|
return `${err.toString()}\n${frames.join('\n')}\n`;
|
2017-01-22 16:20:18 -05:00
|
|
|
};
|
|
|
|
|
2010-09-21 03:53:58 -04:00
|
|
|
}).call(this);
|