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

309 lines
9.9 KiB
JavaScript
Raw Normal View History

2.0.0-beta3 (#4594) * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * Correct comment * object destructuring * Allow custom position of the rest element. * Output simple array destructuring assignments to ES2015 * Output simple object destructured assignments to ES2015 * Compile shorthand object properties to ES2015 shorthand properties This dramatically improves the appearance of destructured imports. * Don’t confuse the syntax highlighter * Comment Assign::compilePatternMatch a bit * Assignment expressions in conditionals are a bad practice * Rename `wrapInBraces` to `wrapInParentheses`, to set the stage for future `wrapInBraces` that uses `{` and `wrapInBrackets` that uses `[` * object destructuring * Allow custom position of the rest element. * rest element in object destructuring * rest element in object destructuring * fix string interpolation * merging * fixing splats in object literal * Rest element in parameter destructuring * merging with CS2 * merged with CS2 * Add support for the object spread initializer. https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md * Fix misspellings, trailing whitespace, other minor details * merging with beta2 * refactor object spread properties * small fix * - Fixed object spread function parameters. - Clean up "Assign" and moved all logic for object rest properties in single method (compileObjectDestruct). - Add helper function "objectWithoutKeys" to the "UTILITIES" for use with object rest properties, e.g. {a, b, r...} = obj => {a, b} = obj, r = objectWithoutKeys(...) - Clean up "Obj" and moved all logic for object spread properties in single method (compileSpread). - Clean up "Code". - Add method "hasSplat" to "Obj" and "Value" for checking if Obj contains the splat. - Enable placing spread syntax triple dots on either right or left, per #85 (https://github.com/coffeescript6/discuss/issues/85) * Fixed typos * Remove unused code * Removed dots (e.g. splat) on the left side from the grammar * Initial release for deep spread properties, e.g. obj2 = {obj.b..., a: 1} or {obj[b][c]..., d: 7} Tests need to be prepared! * 1. Object literal spread properties Object literals: - obj = { {b:{c:{d:1}}}..., a:1 } Parenthetical: - obj = { ( body ), a:1 } - obj = { ( body )..., a:1 } Invocation: - obj = { ( (args) -> ... )(params), a:1 } - obj = { ( (args) -> ... )(params)..., a:1 } - obj = { foo(), a:1 } - obj = { foo()..., a:1 } 2. Refactor, cleanup & other optimizations. * Merged with 2.0 * Cleanup * Some more cleanup. * Fixed error with freeVariable and object destructuring. * Fixed errors with object spread properties. * Improvements, fixed errors. * Minor improvement. * Minor improvements. * Typo. * Remove unnecessary whitespace. * Remove unnecessary whitespace. * Changed few "assertErrorFormat" tests since parentheses are now allowed in the Obj. * Whitespace cleanup * Comments cleanup * fix destructured obj param declarations * refine fix; add test * Refactor function args ({a, b...}) * Additional tests for object destructuring in function argument. * Minor improvement for object destructuring variable declaration. * refactor function args ({a, b...}) and ({a, b...} = {}); Obj And Param cleanup * fix comment * Fix object destructuring variable declaration. * more tests with default values * fix typo * Fixed default values in object destructuring. * small fix * Babel’s tests for object rest spread * Style: spaces after colons in object declarations * Cleanup comments * Simplify Babel tests * Fix comments * Fix destructuring with splats in multiple objects * Add test for default values in detsructuring assignment with splats * Handle default values when assigning to object splats * Rewrite traverseRest to fix handling of dynamic keys * Fix double parens around destructuring with splats * Update compileObjectDestruct comments * Improve formatting of top-level destructures with splats and tidy parens * Added a bigger destructuring-with-defaults test and fixed a bug * Refactor destructuring grammar to allow additional forms * Add a missing case to ObjSpreadExpr * These tests shouldn’t run in the browser * Fix test.html * Fix docs scroll position getting screwed up by CodeMirror initialization * Breaking change documentation about => (fixes #4593) * Spread/rest syntax documentation * Documentation about bound class methods * 2.0.0-beta3 changelog * Add note about ‘lib’ * Fix accidentally converting this to tabs * Bump version to 2.0.0-beta3 * Update annotated source and test.html
2017-06-30 16:58:05 +00:00
// Generated by CoffeeScript 2.0.0-beta3
(function() {
[CS2] Add #! support for executable scripts on Linux. (#3946) * Add #! support for executable scripts on Linux. Pass arguments to executable script unchanged if using "#!/usr/bin/env coffee". (Previously, "./test.coffee -abck" would be turned into "-a -b -c -k", for example.) Fixes #1752. * refactor option parsing clean up parsing code and in the process fix oustanding bug where coffeescript modified arguments meant for an executable script * address comments * intermediate save * add note saying where OptionParser is used in coffee command * add some more work * fix flatten functions * refactor tests * make argument processing less confusing * add basic test * remove unused file * compilation now hangs * remove unnecessary changes * add tests!!! * add/fix some tests * clarify a test * fix helpers * fix opt parsing * fix infinite loop * make rule building easier to read * add tests for flag overlap * revamp argument parsing again and add more thorough testing * add tests, comment, clean unused method * address review comments * add test for direct invocation of shebang scripts * move shebang parsing test to separate file and check for browser * remove TODO * example backwards compatible warnings * add correct tests for warning 1 * add tests for warnings * commit output js libs and update docs * respond to review comments also add tests for help text * respond to review comments * fix example output * Rewrite argument parsing documentation to be more concise; add it to sidebar and body; add new output * Don’t mention deprecated syntax; clean up variable names
2017-07-19 23:25:06 +00:00
var Lexer, SourceMap, base64encode, checkShebangLine, compile, formatSourcePosition, getSourceMap, helpers, lexer, packageJson, parser, sourceMaps, sources, withPrettyErrors;
[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
({Lexer} = require('./lexer'));
[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
({parser} = require('./parser'));
helpers = require('./helpers');
2013-02-28 20:51:29 +00:00
SourceMap = require('./sourcemap');
packageJson = require('../../package.json');
exports.VERSION = packageJson.version;
exports.FILE_EXTENSIONS = ['.coffee', '.litcoffee', '.coffee.md'];
2013-07-30 04:06:41 +00:00
exports.helpers = helpers;
base64encode = function(src) {
switch (false) {
case typeof Buffer !== 'function':
return Buffer.from(src).toString('base64');
case typeof btoa !== 'function':
return btoa(encodeURIComponent(src).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
default:
throw new Error('Unable to base64 encode inline sourcemap.');
}
};
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 05:26:13 +00:00
return function(code, options = {}) {
2015-09-13 10:27:07 +00:00
var err;
try {
return fn.call(this, code, options);
2015-08-16 20:34:22 +00:00
} catch (error) {
err = error;
if (typeof code !== 'string') {
throw err;
}
throw helpers.updateSyntaxError(err, code, options.filename);
}
};
};
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00:00
sources = {};
sourceMaps = {};
exports.compile = compile = withPrettyErrors(function(code, options) {
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00: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;
[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
({merge, extend} = helpers);
options = extend({}, options);
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00:00
generateSourceMap = options.sourceMap || options.inlineMap || (options.filename == null);
filename = options.filename || '<anonymous>';
[CS2] Add #! support for executable scripts on Linux. (#3946) * Add #! support for executable scripts on Linux. Pass arguments to executable script unchanged if using "#!/usr/bin/env coffee". (Previously, "./test.coffee -abck" would be turned into "-a -b -c -k", for example.) Fixes #1752. * refactor option parsing clean up parsing code and in the process fix oustanding bug where coffeescript modified arguments meant for an executable script * address comments * intermediate save * add note saying where OptionParser is used in coffee command * add some more work * fix flatten functions * refactor tests * make argument processing less confusing * add basic test * remove unused file * compilation now hangs * remove unnecessary changes * add tests!!! * add/fix some tests * clarify a test * fix helpers * fix opt parsing * fix infinite loop * make rule building easier to read * add tests for flag overlap * revamp argument parsing again and add more thorough testing * add tests, comment, clean unused method * address review comments * add test for direct invocation of shebang scripts * move shebang parsing test to separate file and check for browser * remove TODO * example backwards compatible warnings * add correct tests for warning 1 * add tests for warnings * commit output js libs and update docs * respond to review comments also add tests for help text * respond to review comments * fix example output * Rewrite argument parsing documentation to be more concise; add it to sidebar and body; add new output * Don’t mention deprecated syntax; clean up variable names
2017-07-19 23:25:06 +00:00
checkShebangLine(filename, code);
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00:00
sources[filename] = code;
if (generateSourceMap) {
map = new SourceMap;
}
tokens = lexer.tokenize(code, options);
options.referencedVars = (function() {
var i, len, results;
results = [];
for (i = 0, len = tokens.length; i < len; i++) {
token = tokens[i];
if (token[0] === 'IDENTIFIER') {
results.push(token[1]);
}
}
return results;
})();
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 (!((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;
}
}
}
fragments = parser.parse(tokens).compileToFragments(options);
currentLine = 0;
2013-03-25 17:56:24 +00:00
if (options.header) {
currentLine += 1;
}
if (options.shiftLine) {
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 18:46:05 +00:00
for (j = 0, len1 = fragments.length; j < len1; j++) {
fragment = fragments[j];
if (generateSourceMap) {
if (fragment.locationData && !/^[;\s]*$/.test(fragment.code)) {
map.add([fragment.locationData.first_line, fragment.locationData.first_column], [currentLine, currentColumn], {
noReplace: true
});
2013-02-28 20:51:29 +00:00
}
newLines = helpers.count(fragment.code, "\n");
currentLine += newLines;
if (newLines) {
currentColumn = fragment.code.length - (fragment.code.lastIndexOf("\n") + 1);
} else {
currentColumn += fragment.code.length;
}
2013-02-28 20:51:29 +00:00
}
js += fragment.code;
}
if (options.header) {
header = `Generated by CoffeeScript ${this.VERSION}`;
js = `// ${header}\n${js}`;
}
if (generateSourceMap) {
v3SourceMap = map.generate(options, code);
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00:00
sourceMaps[filename] = map;
}
if (options.inlineMap) {
encoded = base64encode(JSON.stringify(v3SourceMap));
sourceMapDataURI = `//# sourceMappingURL=data:application/json;base64,${encoded}`;
sourceURL = `//# sourceURL=${(ref1 = options.filename) != null ? ref1 : 'coffeescript'}`;
js = `${js}\n${sourceMapDataURI}\n${sourceURL}`;
}
if (options.sourceMap) {
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
js,
sourceMap: map,
v3SourceMap: JSON.stringify(v3SourceMap, null, 2)
};
2013-03-04 14:45:25 +00:00
} else {
return js;
2013-02-28 20:51:29 +00:00
}
});
exports.tokens = withPrettyErrors(function(code, options) {
return lexer.tokenize(code, options);
});
exports.nodes = withPrettyErrors(function(source, options) {
if (typeof source === 'string') {
2010-11-20 21:25:22 +00:00
return parser.parse(lexer.tokenize(source, options));
} else {
return parser.parse(source);
}
});
exports.run = exports.eval = exports.register = function() {
throw new Error('require index.coffee, not this file');
2013-07-30 04:06:41 +00:00
};
lexer = new Lexer;
parser.lexer = {
lex: function() {
var tag, token;
token = parser.tokens[this.pos++];
if (token) {
[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, this.yytext, this.yylloc] = token;
parser.errorToken = token.origin || token;
this.yylineno = this.yylloc.first_line;
} else {
tag = '';
}
2010-11-02 04:05:06 +00:00
return tag;
},
setInput: function(tokens) {
parser.tokens = tokens;
return this.pos = 0;
},
upcomingInput: function() {
return "";
}
};
2010-09-21 07:50:32 +00:00
parser.yy = require('./nodes');
2011-12-14 15:39:20 +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
parser.yy.parseError = function(message, {token}) {
var errorLoc, errorTag, errorText, errorToken, tokens;
({errorToken, tokens} = parser);
[errorTag, errorText, errorLoc] = errorToken;
2015-02-07 19:16:59 +00: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 19:24:31 +00:00
case errorTag !== 'IDENTIFIER' && errorTag !== 'NUMBER' && errorTag !== 'INFINITY' && errorTag !== 'STRING' && errorTag !== 'STRING_START' && errorTag !== 'REGEX' && errorTag !== 'REGEX_START':
2015-02-07 19:16:59 +00:00
return errorTag.replace(/_START$/, '').toLowerCase();
default:
return helpers.nameWhitespaceCharacter(errorText);
}
})();
return helpers.throwSyntaxError(`unexpected ${errorText}`, errorLoc);
2013-02-25 18:09:42 +00:00
};
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00: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) {
fileLocation = `${frame.getEvalOrigin()}, `;
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00:00
}
} else {
filename = frame.getFileName();
}
filename || (filename = "<anonymous>");
line = frame.getLineNumber();
column = frame.getColumnNumber();
source = getSourceMapping(filename, line, column);
fileLocation = source ? `${filename}:${source[0]}:${source[1]}` : `${filename}:${line}:${column}`;
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00: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)) {
tp = `${typeName}.`;
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00:00
}
if (methodName && functionName.indexOf(`.${methodName}`) !== functionName.length - methodName.length - 1) {
as = ` [as ${methodName}]`;
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00:00
}
return `${tp}${functionName}${as} (${fileLocation})`;
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00:00
} else {
return `${typeName}.${methodName || '<anonymous>'} (${fileLocation})`;
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00:00
}
} else if (isConstructor) {
return `new ${functionName || '<anonymous>'} (${fileLocation})`;
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00:00
} else if (functionName) {
return `${functionName} (${fileLocation})`;
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00: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,
sourceMap: true,
literate: helpers.isLiterate(filename)
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00: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 i, len, results;
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00:00
results = [];
for (i = 0, len = stack.length; i < len; i++) {
frame = stack[i];
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00:00
if (frame.getFunction() === exports.run) {
break;
}
results.push(` at ${formatSourcePosition(frame, getSourceMapping)}`);
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00:00
}
return results;
})();
return `${err.toString()}\n${frames.join('\n')}\n`;
Fix stack trace (#4428) * Revert aee27fbff03870c5479c6c33e6b1f1a32219420c * Patch Jison’s output so that it requires `fs` only if we’re truly in a CommonJS/Node environment, not a browser environment that may happen to have globals named `require` and `exports` (as would be the case if require.js is being used). Fixes #4391. * Temporary fix for exceptions getting thrown when trying to generate a stack trace for a file that has been deleted since compilation; fixes #3890, but not well. A better solution would not try to recompile the file when trying to retrieve its stack trace. * Save the test REPL history in the system temp folder, not in the CoffeeScript project folder * Rewrite `getSourceMap` to never read a file from disk, and therefore not throw IO-related exceptions; source maps are either retrieved from memory, or the related source code is retrieved from memory to generate a new source map. Fixes #3890 the proper way. * Add test to verify that stack traces reference the correct line number. Closes #4418. * Get the parser working in the browser compiler again; rather than detecting a CommonJS environment generally, just check for `fs` before trying to use it * Follow Node’s standard of 4-space indentation of stack trace data * Better .gitignore * Fix caching of compiled code and source maps; add more tests to verify correct line numbers in stack traces * Better fallback value for the parser source * Fix the stack traces and tests when running in a browser * Update the browser compiler so that @murrayju doesn’t have any extra work to do to test this branch
2017-01-22 21:20:18 +00:00
};
[CS2] Add #! support for executable scripts on Linux. (#3946) * Add #! support for executable scripts on Linux. Pass arguments to executable script unchanged if using "#!/usr/bin/env coffee". (Previously, "./test.coffee -abck" would be turned into "-a -b -c -k", for example.) Fixes #1752. * refactor option parsing clean up parsing code and in the process fix oustanding bug where coffeescript modified arguments meant for an executable script * address comments * intermediate save * add note saying where OptionParser is used in coffee command * add some more work * fix flatten functions * refactor tests * make argument processing less confusing * add basic test * remove unused file * compilation now hangs * remove unnecessary changes * add tests!!! * add/fix some tests * clarify a test * fix helpers * fix opt parsing * fix infinite loop * make rule building easier to read * add tests for flag overlap * revamp argument parsing again and add more thorough testing * add tests, comment, clean unused method * address review comments * add test for direct invocation of shebang scripts * move shebang parsing test to separate file and check for browser * remove TODO * example backwards compatible warnings * add correct tests for warning 1 * add tests for warnings * commit output js libs and update docs * respond to review comments also add tests for help text * respond to review comments * fix example output * Rewrite argument parsing documentation to be more concise; add it to sidebar and body; add new output * Don’t mention deprecated syntax; clean up variable names
2017-07-19 23:25:06 +00:00
checkShebangLine = function(file, input) {
var args, firstLine, ref, rest;
firstLine = input.split(/$/m)[0];
rest = firstLine != null ? firstLine.match(/^#!\s*([^\s]+\s*)(.*)/) : void 0;
args = rest != null ? (ref = rest[2]) != null ? ref.split(/\s/).filter(function(s) {
return s !== '';
}) : void 0 : void 0;
if ((args != null ? args.length : void 0) > 1) {
console.error('The script to be run begins with a shebang line with more than one\nargument. This script will fail on platforms such as Linux which only\nallow a single argument.');
console.error(`The shebang line was: '${firstLine}' in file '${file}'`);
return console.error(`The arguments were: ${JSON.stringify(args)}`);
}
};
}).call(this);