1
0
Fork 0
mirror of https://github.com/jashkenas/coffeescript.git synced 2022-11-09 12:23:24 -05:00
jashkenas--coffeescript/lib/coffee-script/coffee-script.js
Geoffrey Booth fb2be8e1e3 [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-25 22:26:13 -07:00

400 lines
13 KiB
JavaScript

// Generated by CoffeeScript 2.0.0-alpha
(function() {
var Lexer, SourceMap, base64encode, compile, ext, fn1, formatSourcePosition, fs, getSourceMap, helpers, i, len, lexer, parser, path, ref, sourceMaps, vm, withPrettyErrors,
hasProp = {}.hasOwnProperty;
fs = require('fs');
vm = require('vm');
path = require('path');
Lexer = require('./lexer').Lexer;
parser = require('./parser').parser;
helpers = require('./helpers');
SourceMap = require('./sourcemap');
exports.VERSION = '2.0.0-alpha';
exports.FILE_EXTENSIONS = ['.coffee', '.litcoffee', '.coffee.md'];
exports.helpers = helpers;
base64encode = function(src) {
switch (false) {
case typeof Buffer !== 'function':
return Buffer.from(src).toString('base64');
case typeof btoa !== 'function':
return btoa(src);
default:
throw new Error('Unable to base64 encode inline sourcemap.');
}
};
withPrettyErrors = function(fn) {
return function(code, options = {}) {
var err;
try {
return fn.call(this, code, options);
} catch (error) {
err = error;
if (typeof code !== 'string') {
throw err;
}
throw helpers.updateSyntaxError(err, code, options.filename);
}
};
};
exports.compile = compile = withPrettyErrors(function(code, options) {
var currentColumn, currentLine, encoded, extend, fragment, fragments, generateSourceMap, header, i, j, js, len, len1, map, merge, newLines, ref, ref1, sourceMapDataURI, sourceURL, token, tokens, v3SourceMap;
merge = helpers.merge, extend = helpers.extend;
options = extend({}, options);
generateSourceMap = options.sourceMap || options.inlineMap;
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;
})();
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;
if (options.header) {
currentLine += 1;
}
if (options.shiftLine) {
currentLine += 1;
}
currentColumn = 0;
js = "";
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
});
}
newLines = helpers.count(fragment.code, "\n");
currentLine += newLines;
if (newLines) {
currentColumn = fragment.code.length - (fragment.code.lastIndexOf("\n") + 1);
} else {
currentColumn += fragment.code.length;
}
}
js += fragment.code;
}
if (options.header) {
header = "Generated by CoffeeScript " + this.VERSION;
js = "// " + header + "\n" + js;
}
if (generateSourceMap) {
v3SourceMap = map.generate(options, code);
}
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 {
js: js,
sourceMap: map,
v3SourceMap: JSON.stringify(v3SourceMap, null, 2)
};
} else {
return js;
}
});
exports.tokens = withPrettyErrors(function(code, options) {
return lexer.tokenize(code, options);
});
exports.nodes = withPrettyErrors(function(source, options) {
if (typeof source === 'string') {
return parser.parse(lexer.tokenize(source, options));
} else {
return parser.parse(source);
}
});
exports.run = function(code, options = {}) {
var answer, dir, mainModule, ref;
mainModule = require.main;
mainModule.filename = process.argv[1] = options.filename ? fs.realpathSync(options.filename) : '.';
mainModule.moduleCache && (mainModule.moduleCache = {});
dir = options.filename ? path.dirname(fs.realpathSync(options.filename)) : fs.realpathSync('.');
mainModule.paths = require('module')._nodeModulePaths(dir);
if (!helpers.isCoffee(mainModule.filename) || require.extensions) {
answer = compile(code, options);
code = (ref = answer.js) != null ? ref : answer;
}
return mainModule._compile(code, mainModule.filename);
};
exports["eval"] = function(code, options = {}) {
var Module, _module, _require, createContext, i, isContext, js, k, len, o, r, ref, ref1, ref2, ref3, sandbox, v;
if (!(code = code.trim())) {
return;
}
createContext = (ref = vm.Script.createContext) != null ? ref : vm.createContext;
isContext = (ref1 = vm.isContext) != null ? ref1 : function(ctx) {
return options.sandbox instanceof createContext().constructor;
};
if (createContext) {
if (options.sandbox != null) {
if (isContext(options.sandbox)) {
sandbox = options.sandbox;
} else {
sandbox = createContext();
ref2 = options.sandbox;
for (k in ref2) {
if (!hasProp.call(ref2, k)) continue;
v = ref2[k];
sandbox[k] = v;
}
}
sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox;
} else {
sandbox = global;
}
sandbox.__filename = options.filename || 'eval';
sandbox.__dirname = path.dirname(sandbox.__filename);
if (!(sandbox !== global || sandbox.module || sandbox.require)) {
Module = require('module');
sandbox.module = _module = new Module(options.modulename || 'eval');
sandbox.require = _require = function(path) {
return Module._load(path, _module, true);
};
_module.filename = sandbox.__filename;
ref3 = Object.getOwnPropertyNames(require);
for (i = 0, len = ref3.length; i < len; i++) {
r = ref3[i];
if (r !== 'paths' && r !== 'arguments' && r !== 'caller') {
_require[r] = require[r];
}
}
_require.paths = _module.paths = Module._nodeModulePaths(process.cwd());
_require.resolve = function(request) {
return Module._resolveFilename(request, _module);
};
}
}
o = {};
for (k in options) {
if (!hasProp.call(options, k)) continue;
v = options[k];
o[k] = v;
}
o.bare = true;
js = compile(code, o);
if (sandbox === global) {
return vm.runInThisContext(js);
} else {
return vm.runInContext(js, sandbox);
}
};
exports.register = function() {
return require('./register');
};
if (require.extensions) {
ref = this.FILE_EXTENSIONS;
fn1 = function(ext) {
var base;
return (base = require.extensions)[ext] != null ? base[ext] : base[ext] = function() {
throw new Error("Use CoffeeScript.register() or require the coffee-script/register module to require " + ext + " files.");
};
};
for (i = 0, len = ref.length; i < len; i++) {
ext = ref[i];
fn1(ext);
}
}
exports._compileFile = function(filename, sourceMap = false, inlineMap = false) {
var answer, err, raw, stripped;
raw = fs.readFileSync(filename, 'utf8');
stripped = raw.charCodeAt(0) === 0xFEFF ? raw.substring(1) : raw;
try {
answer = compile(stripped, {
filename: filename,
sourceMap: sourceMap,
inlineMap: inlineMap,
sourceFiles: [filename],
literate: helpers.isLiterate(filename)
});
} catch (error) {
err = error;
throw helpers.updateSyntaxError(err, stripped, filename);
}
return answer;
};
lexer = new Lexer;
parser.lexer = {
lex: function() {
var tag, token;
token = parser.tokens[this.pos++];
if (token) {
tag = token[0], this.yytext = token[1], this.yylloc = token[2];
parser.errorToken = token.origin || token;
this.yylineno = this.yylloc.first_line;
} else {
tag = '';
}
return tag;
},
setInput: function(tokens) {
parser.tokens = tokens;
return this.pos = 0;
},
upcomingInput: function() {
return "";
}
};
parser.yy = require('./nodes');
parser.yy.parseError = function(message, arg) {
var errorLoc, errorTag, errorText, errorToken, token, tokens;
token = arg.token;
errorToken = parser.errorToken, tokens = parser.tokens;
errorTag = errorToken[0], errorText = errorToken[1], errorLoc = errorToken[2];
errorText = (function() {
switch (false) {
case errorToken !== tokens[tokens.length - 1]:
return 'end of input';
case errorTag !== 'INDENT' && errorTag !== 'OUTDENT':
return 'indentation';
case errorTag !== 'IDENTIFIER' && errorTag !== 'NUMBER' && errorTag !== 'INFINITY' && errorTag !== 'STRING' && errorTag !== 'STRING_START' && errorTag !== 'REGEX' && errorTag !== 'REGEX_START':
return errorTag.replace(/_START$/, '').toLowerCase();
default:
return helpers.nameWhitespaceCharacter(errorText);
}
})();
return helpers.throwSyntaxError("unexpected " + errorText, errorLoc);
};
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()) + ", ";
}
} 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;
}
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 + ".";
}
if (methodName && functionName.indexOf("." + methodName) !== functionName.length - methodName.length - 1) {
as = " [as " + methodName + "]";
}
return "" + tp + functionName + as + " (" + fileLocation + ")";
} else {
return typeName + "." + (methodName || '<anonymous>') + " (" + fileLocation + ")";
}
} else if (isConstructor) {
return "new " + (functionName || '<anonymous>') + " (" + fileLocation + ")";
} else if (functionName) {
return functionName + " (" + fileLocation + ")";
} else {
return fileLocation;
}
};
sourceMaps = {};
getSourceMap = function(filename) {
var answer, j, len1, ref1;
if (sourceMaps[filename]) {
return sourceMaps[filename];
}
ref1 = exports.FILE_EXTENSIONS;
for (j = 0, len1 = ref1.length; j < len1; j++) {
ext = ref1[j];
if (helpers.ends(filename, ext)) {
answer = exports._compileFile(filename, true);
return sourceMaps[filename] = answer.sourceMap;
}
}
return null;
};
Error.prepareStackTrace = function(err, stack) {
var frame, frames, getSourceMapping;
getSourceMapping = function(filename, line, column) {
var answer, sourceMap;
sourceMap = getSourceMap(filename);
if (sourceMap) {
answer = sourceMap.sourceLocation([line - 1, column - 1]);
}
if (answer) {
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;
}
results.push(" at " + (formatSourcePosition(frame, getSourceMapping)));
}
return results;
})();
return (err.toString()) + "\n" + (frames.join('\n')) + "\n";
};
}).call(this);