diff --git a/lib/coffeescript/browser.js b/lib/coffeescript/browser.js index cf1b46543d..7225d9cbac 100644 --- a/lib/coffeescript/browser.js +++ b/lib/coffeescript/browser.js @@ -27,7 +27,7 @@ } if ((typeof btoa !== "undefined" && btoa !== null) && (typeof JSON !== "undefined" && JSON !== null)) { - compile = function(code, options = {}) { + compile = function compile(code, options = {}) { options.inlineMap = true; return CoffeeScript.compile(code, options); }; @@ -60,7 +60,7 @@ return xhr.send(null); }; - runScripts = function() { + runScripts = function runScripts() { var coffees, coffeetypes, execute, fn, i, index, j, len, s, script, scripts; scripts = window.document.getElementsByTagName('script'); coffeetypes = ['text/coffeescript', 'text/literate-coffeescript']; @@ -76,7 +76,7 @@ return results; })(); index = 0; - execute = function() { + execute = function execute() { var param; param = coffees[index]; if (param instanceof Array) { @@ -85,7 +85,7 @@ return execute(); } }; - fn = function(script, i) { + fn = function fn(script, i) { var options, source; options = { literate: script.type === coffeetypes[1] diff --git a/lib/coffeescript/cake.js b/lib/coffeescript/cake.js index 5ae03160b8..336881e13d 100644 --- a/lib/coffeescript/cake.js +++ b/lib/coffeescript/cake.js @@ -23,16 +23,16 @@ oparse = null; helpers.extend(global, { - task: function(name, description, action) { + task: function task(name, description, action) { if (!action) { [action, description] = [description, action]; } return tasks[name] = {name, description, action}; }, - option: function(letter, flag, description) { + option: function option(letter, flag, description) { return switches.push([letter, flag, description]); }, - invoke: function(name) { + invoke: function invoke(name) { if (!tasks[name]) { missingTask(name); } @@ -67,7 +67,7 @@ return results; }; - printTasks = function() { + printTasks = function printTasks() { var cakefilePath, desc, name, relative, spaces, task; relative = path.relative || path.resolve; cakefilePath = path.join(relative(__originalDirname, process.cwd()), 'Cakefile'); @@ -84,17 +84,17 @@ } }; - fatalError = function(message) { + fatalError = function fatalError(message) { console.error(message + '\n'); console.log('To see a list of all tasks/options, run "cake"'); return process.exit(1); }; - missingTask = function(task) { + missingTask = function missingTask(task) { return fatalError(`No such task: ${task}`); }; - cakefileDirectory = function(dir) { + cakefileDirectory = function cakefileDirectory(dir) { var parent; if (fs.existsSync(path.join(dir, 'Cakefile'))) { return dir; diff --git a/lib/coffeescript/coffeescript.js b/lib/coffeescript/coffeescript.js index 205211838f..59177018bb 100644 --- a/lib/coffeescript/coffeescript.js +++ b/lib/coffeescript/coffeescript.js @@ -25,7 +25,7 @@ exports.helpers = helpers; - base64encode = function(src) { + base64encode = function base64encode(src) { switch (false) { case typeof Buffer !== 'function': return Buffer.from(src).toString('base64'); @@ -38,7 +38,7 @@ } }; - withPrettyErrors = function(fn) { + withPrettyErrors = function withPrettyErrors(fn) { return function(code, options = {}) { var err; try { @@ -198,7 +198,7 @@ if (!(sandbox !== global || sandbox.module || sandbox.require)) { Module = require('module'); sandbox.module = _module = new Module(options.modulename || 'eval'); - sandbox.require = _require = function(path) { + sandbox.require = _require = function _require(path) { return Module._load(path, _module, true); }; _module.filename = sandbox.__filename; @@ -236,7 +236,7 @@ if (require.extensions) { ref = this.FILE_EXTENSIONS; - fn1 = function(ext) { + fn1 = function fn1(ext) { var base; return (base = require.extensions)[ext] != null ? base[ext] : base[ext] = function() { throw new Error(`Use CoffeeScript.register() or require the coffeescript/register module to require ${ext} files.`); @@ -270,7 +270,7 @@ lexer = new Lexer; parser.lexer = { - lex: function() { + lex: function lex() { var tag, token; token = parser.tokens[this.pos++]; if (token) { @@ -282,11 +282,11 @@ } return tag; }, - setInput: function(tokens) { + setInput: function setInput(tokens) { parser.tokens = tokens; return this.pos = 0; }, - upcomingInput: function() { + upcomingInput: function upcomingInput() { return ""; } }; @@ -312,7 +312,7 @@ return helpers.throwSyntaxError(`unexpected ${errorText}`, errorLoc); }; - formatSourcePosition = function(frame, getSourceMapping) { + formatSourcePosition = function formatSourcePosition(frame, getSourceMapping) { var as, column, fileLocation, filename, functionName, isConstructor, isMethodCall, line, methodName, source, tp, typeName; filename = void 0; fileLocation = ''; @@ -360,7 +360,7 @@ } }; - getSourceMap = function(filename) { + getSourceMap = function getSourceMap(filename) { var answer; if (sourceMaps[filename] != null) { return sourceMaps[filename]; @@ -380,7 +380,7 @@ Error.prepareStackTrace = function(err, stack) { var frame, frames, getSourceMapping; - getSourceMapping = function(filename, line, column) { + getSourceMapping = function getSourceMapping(filename, line, column) { var answer, sourceMap; sourceMap = getSourceMap(filename); if (sourceMap != null) { diff --git a/lib/coffeescript/command.js b/lib/coffeescript/command.js index 4a54ab456b..de22633ed8 100644 --- a/lib/coffeescript/command.js +++ b/lib/coffeescript/command.js @@ -21,15 +21,15 @@ helpers.extend(CoffeeScript, new EventEmitter); - printLine = function(line) { + printLine = function printLine(line) { return process.stdout.write(line + '\n'); }; - printWarn = function(line) { + printWarn = function printWarn(line) { return process.stderr.write(line + '\n'); }; - hidden = function(file) { + hidden = function hidden(file) { return /^\.|~$/.test(file); }; @@ -100,7 +100,7 @@ return results; }; - makePrelude = function(requires) { + makePrelude = function makePrelude(requires) { return requires.map(function(module) { var _, match, name; if (match = module.match(/^(.*)=(.*)$/)) { @@ -111,7 +111,7 @@ }).join(';'); }; - compilePath = function(source, topLevel, base) { + compilePath = function compilePath(source, topLevel, base) { var code, err, file, files, i, len, results, stats; if (indexOf.call(sources, source) >= 0 || watchedDirs[source] || !topLevel && (notSources[source] || hidden(source))) { return; @@ -177,7 +177,7 @@ } }; - findDirectoryIndex = function(source) { + findDirectoryIndex = function findDirectoryIndex(source) { var err, ext, i, index, len, ref; ref = CoffeeScript.FILE_EXTENSIONS; for (i = 0, len = ref.length; i < len; i++) { @@ -198,7 +198,7 @@ return process.exit(1); }; - compileScript = function(file, input, base = null) { + compileScript = function compileScript(file, input, base = null) { var compiled, err, message, o, options, t, task; o = opts; options = compileOptions(file, base); @@ -251,7 +251,7 @@ } }; - compileStdio = function() { + compileStdio = function compileStdio() { var buffers, stdin; buffers = []; stdin = process.openStdin(); @@ -267,7 +267,7 @@ joinTimeout = null; - compileJoin = function() { + compileJoin = function compileJoin() { if (!opts.join) { return; } @@ -281,12 +281,12 @@ } }; - watch = function(source, base) { + watch = function watch(source, base) { var compile, compileTimeout, err, prevStats, rewatch, startWatcher, watchErr, watcher; watcher = null; prevStats = null; compileTimeout = null; - watchErr = function(err) { + watchErr = function watchErr(err) { if (err.code !== 'ENOENT') { throw err; } @@ -301,7 +301,7 @@ return compileJoin(); } }; - compile = function() { + compile = function compile() { clearTimeout(compileTimeout); return compileTimeout = wait(25, function() { return fs.stat(source, function(err, stats) { @@ -322,7 +322,7 @@ }); }); }; - startWatcher = function() { + startWatcher = function startWatcher() { return watcher = fs.watch(source).on('change', compile).on('error', function(err) { if (err.code !== 'EPERM') { throw err; @@ -330,7 +330,7 @@ return removeSource(source, base); }); }; - rewatch = function() { + rewatch = function rewatch() { if (watcher != null) { watcher.close(); } @@ -344,11 +344,11 @@ } }; - watchDir = function(source, base) { + watchDir = function watchDir(source, base) { var err, readdirTimeout, startWatcher, stopWatcher, watcher; watcher = null; readdirTimeout = null; - startWatcher = function() { + startWatcher = function startWatcher() { return watcher = fs.watch(source).on('error', function(err) { if (err.code !== 'EPERM') { throw err; @@ -376,7 +376,7 @@ }); }); }; - stopWatcher = function() { + stopWatcher = function stopWatcher() { watcher.close(); return removeSourceDir(source, base); }; @@ -391,7 +391,7 @@ } }; - removeSourceDir = function(source, base) { + removeSourceDir = function removeSourceDir(source, base) { var file, i, len, sourcesChanged; delete watchedDirs[source]; sourcesChanged = false; @@ -408,7 +408,7 @@ } }; - removeSource = function(source, base) { + removeSource = function removeSource(source, base) { var index; index = sources.indexOf(source); sources.splice(index, 1); @@ -420,7 +420,7 @@ } }; - silentUnlink = function(path) { + silentUnlink = function silentUnlink(path) { var err, ref; try { return fs.unlinkSync(path); @@ -432,7 +432,7 @@ } }; - outputPath = function(source, base, extension = ".js") { + outputPath = function outputPath(source, base, extension = ".js") { var basename, dir, srcDir; basename = helpers.baseFileName(source, true, useWinPathSep); srcDir = path.dirname(source); @@ -446,10 +446,10 @@ return path.join(dir, basename + extension); }; - mkdirp = function(dir, fn) { + mkdirp = function mkdirp(dir, fn) { var mkdirs, mode; mode = 0o777 & ~process.umask(); - return (mkdirs = function(p, fn) { + return (mkdirs = function mkdirs(p, fn) { return fs.exists(p, function(exists) { if (exists) { return fn(); @@ -467,11 +467,11 @@ })(dir, fn); }; - writeJs = function(base, sourcePath, js, jsPath, generatedSourceMap = null) { + writeJs = function writeJs(base, sourcePath, js, jsPath, generatedSourceMap = null) { var compile, jsDir, sourceMapPath; sourceMapPath = outputPath(sourcePath, base, ".js.map"); jsDir = path.dirname(jsPath); - compile = function() { + compile = function compile() { if (opts.compile) { if (js.length <= 0) { js = ' '; @@ -506,15 +506,15 @@ }); }; - wait = function(milliseconds, func) { + wait = function wait(milliseconds, func) { return setTimeout(func, milliseconds); }; - timeLog = function(message) { + timeLog = function timeLog(message) { return console.log(`${(new Date).toLocaleTimeString()} - ${message}`); }; - printTokens = function(tokens) { + printTokens = function printTokens(tokens) { var strings, tag, token, value; strings = (function() { var i, len, results; @@ -530,7 +530,7 @@ return printLine(strings.join(' ')); }; - parseOptions = function() { + parseOptions = function parseOptions() { var o; optionParser = new optparse.OptionParser(SWITCHES, BANNER); o = opts = optionParser.parse(process.argv.slice(2)); @@ -539,7 +539,7 @@ return o.print = !!(o.print || (o.eval || o.stdio && o.compile)); }; - compileOptions = function(filename, base) { + compileOptions = function compileOptions(filename, base) { var answer, cwd, jsDir, jsPath; answer = { filename, @@ -571,7 +571,7 @@ return answer; }; - forkNode = function() { + forkNode = function forkNode() { var args, nodeArgs, p; nodeArgs = opts.nodejs.split(/\s+/); args = process.argv.slice(1); @@ -586,11 +586,11 @@ }); }; - usage = function() { + usage = function usage() { return printLine((new optparse.OptionParser(SWITCHES, BANNER)).help()); }; - version = function() { + version = function version() { return printLine(`CoffeeScript version ${CoffeeScript.VERSION}`); }; diff --git a/lib/coffeescript/grammar.js b/lib/coffeescript/grammar.js index 3a76a1c650..fe993d1cdf 100644 --- a/lib/coffeescript/grammar.js +++ b/lib/coffeescript/grammar.js @@ -6,7 +6,7 @@ unwrap = /^function\s*\(\)\s*\{\s*return\s*([\s\S]*);\s*\}/; - o = function(patternString, action, options) { + o = function o(patternString, action, options) { var addLocationDataFn, match, patternCount; patternString = patternString.replace(/\s{2,}/g, ' '); patternCount = patternString.split(' ').length; @@ -16,7 +16,7 @@ action = (match = unwrap.exec(action)) ? match[1] : `(${action}())`; action = action.replace(/\bnew /g, '$&yy.'); action = action.replace(/\b(?:Block\.wrap|extend)\b/g, 'yy.$&'); - addLocationDataFn = function(first, last) { + addLocationDataFn = function addLocationDataFn(first, last) { if (!last) { return `yy.addLocationDataFn(@${first})`; } else { diff --git a/lib/coffeescript/helpers.js b/lib/coffeescript/helpers.js index ddccae68a7..8b7c150ccd 100644 --- a/lib/coffeescript/helpers.js +++ b/lib/coffeescript/helpers.js @@ -12,7 +12,7 @@ return literal === string.substr(string.length - len - (back || 0), len); }; - exports.repeat = repeat = function(str, n) { + exports.repeat = repeat = function repeat(str, n) { var res; res = ''; while (n > 0) { @@ -62,7 +62,7 @@ return object; }; - exports.flatten = flatten = function(array) { + exports.flatten = flatten = function flatten(array) { var element, flattened, i, len1; flattened = []; for (i = 0, len1 = array.length; i < len1; i++) { @@ -121,7 +121,7 @@ return out.join('\n'); }; - buildLocationData = function(first, last) { + buildLocationData = function buildLocationData(first, last) { if (!last) { return first; } else { @@ -199,7 +199,7 @@ return error; }; - syntaxErrorToString = function() { + syntaxErrorToString = function syntaxErrorToString() { var codeLine, colorize, colorsEnabled, end, filename, first_column, first_line, last_column, last_line, marker, ref1, ref2, ref3, start; if (!(this.code && this.location)) { return Error.prototype.toString.call(this); @@ -220,7 +220,7 @@ colorsEnabled = ((ref1 = process.stdout) != null ? ref1.isTTY : void 0) && !((ref2 = process.env) != null ? ref2.NODE_DISABLE_COLORS : void 0); } if ((ref3 = this.colorful) != null ? ref3 : colorsEnabled) { - colorize = function(str) { + colorize = function colorize(str) { return `\x1B[1;31m${str}\x1B[0m`; }; codeLine = codeLine.slice(0, start) + colorize(codeLine.slice(start, end)) + codeLine.slice(end); diff --git a/lib/coffeescript/lexer.js b/lib/coffeescript/lexer.js index 459b3db81c..cee46b4b55 100644 --- a/lib/coffeescript/lexer.js +++ b/lib/coffeescript/lexer.js @@ -909,7 +909,7 @@ unicodeCodePointToUnicodeEscapes(codePoint) { var high, low, toUnicodeEscape; - toUnicodeEscape = function(val) { + toUnicodeEscape = function toUnicodeEscape(val) { var str; str = val.toString(16); return `\\u${repeat('0', 4 - str.length)}${str}`; @@ -1009,7 +1009,7 @@ }; - isUnassignable = function(name, displayName = name) { + isUnassignable = function isUnassignable(name, displayName = name) { switch (false) { case indexOf.call([...JS_KEYWORDS, ...COFFEE_KEYWORDS], name) < 0: return `keyword '${displayName}' can't be assigned`; @@ -1024,7 +1024,7 @@ exports.isUnassignable = isUnassignable; - isForFrom = function(prev) { + isForFrom = function isForFrom(prev) { var ref; if (prev[0] === 'IDENTIFIER') { if (prev[1] === 'from') { diff --git a/lib/coffeescript/nodes.js b/lib/coffeescript/nodes.js index 8e2f75fb3b..18996c4806 100644 --- a/lib/coffeescript/nodes.js +++ b/lib/coffeescript/nodes.js @@ -17,19 +17,19 @@ exports.addLocationDataFn = addLocationDataFn; - YES = function() { + YES = function YES() { return true; }; - NO = function() { + NO = function NO() { return false; }; - THIS = function() { + THIS = function THIS() { return this; }; - NEGATE = function() { + NEGATE = function NEGATE() { this.negated = !this.negated; return this; }; @@ -48,7 +48,7 @@ }; - fragmentsToText = function(fragments) { + fragmentsToText = function fragmentsToText(fragments) { var fragment; return ((function() { var j, len1, results; @@ -1419,7 +1419,7 @@ body = `var ${vars}; ${cond} ? ${i} <${this.equals} ${this.toVar} : ${i} >${this.equals} ${this.toVar}; ${cond} ? ${i}++ : ${i}--`; } post = `{ ${result}.push(${i}); }\n${idt}return ${result};\n${o.indent}`; - hasArgs = function(node) { + hasArgs = function hasArgs(node) { return node != null ? node.contains(isLiteralArguments) : void 0; }; if (hasArgs(this.from) || hasArgs(this.to)) { @@ -1812,7 +1812,7 @@ exprs = []; end = 0; start = 0; - pushSlice = function() { + pushSlice = function pushSlice() { if (end > start) { return exprs.push(new Value(new Obj(properties.slice(start, end), true))); } @@ -2399,6 +2399,7 @@ } }); } + compiledName = this.variable.compileToFragments(o, LEVEL_LIST); if (this.value instanceof Code) { if (this.value.isStatic) { this.value.name = this.variable.properties[0]; @@ -2407,10 +2408,11 @@ if (((ref5 = prototype.name) != null ? ref5.value : void 0) === 'prototype') { this.value.name = name; } + } else { + this.value.outputName = compiledName; } } val = this.value.compileToFragments(o, LEVEL_LIST); - compiledName = this.variable.compileToFragments(o, LEVEL_LIST); if (this.context === 'object') { if (this.variable.shouldCache()) { compiledName.unshift(this.makeCode('[')); @@ -2684,7 +2686,7 @@ } compileNode(o) { - var answer, body, condition, exprs, haveBodyParam, haveSplatParam, i, ifTrue, j, k, len1, len2, m, methodScope, modifiers, name, param, paramNames, params, paramsAfterSplat, ref, ref1, ref2, ref3, ref4, ref5, signature, splatParamName, thisAssignments, wasEmpty; + var answer, body, condition, exprs, haveBodyParam, haveSplatParam, i, ifTrue, j, k, len1, len2, m, methodScope, modifiers, name, outputName, param, paramNames, params, paramsAfterSplat, ref, ref1, ref2, ref3, ref4, ref5, signature, splatParamName, thisAssignments, wasEmpty; if (this.ctor) { if (this.isAsync) { this.name.error('Class constructor may not be async'); @@ -2843,7 +2845,17 @@ } else if (this.isGenerator) { modifiers.push('*'); } - signature = [this.makeCode('(')]; + if (this.outputName && !this.bound) { + outputName = fragmentsToText(this.outputName); + if (indexOf.call(JS_FORBIDDEN, outputName) >= 0 || /'|"|\.|\[/.test(outputName)) { + outputName = false; + } + } + signature = []; + if (outputName) { + signature.push(this.makeCode(` ${outputName}`)); + } + signature.push(this.makeCode('(')); for (i = k = 0, len2 = params.length; k < len2; i = ++k) { param = params[i]; if (i) { @@ -3059,7 +3071,7 @@ renameParam(node, newNode) { var isNode, replacement; - isNode = function(candidate) { + isNode = function isNode(candidate) { return candidate === node; }; replacement = (node, parent) => { @@ -4181,19 +4193,19 @@ })(); UTILITIES = { - modulo: function() { + modulo: function modulo() { return 'function(a, b) { return (+a % (b = +b) + b) % b; }'; }, - hasProp: function() { + hasProp: function hasProp() { return '{}.hasOwnProperty'; }, - indexOf: function() { + indexOf: function indexOf() { return '[].indexOf'; }, - slice: function() { + slice: function slice() { return '[].slice'; }, - splice: function() { + splice: function splice() { return '[].splice'; } }; @@ -4214,7 +4226,7 @@ SIMPLENUM = /^[+-]?\d+$/; - utility = function(name, o) { + utility = function utility(name, o) { var ref, root; ({root} = o.scope); if (name in root.utilities) { @@ -4226,24 +4238,24 @@ } }; - multident = function(code, tab) { + multident = function multident(code, tab) { code = code.replace(/\n/g, '$&' + tab); return code.replace(/\s+$/, ''); }; - isLiteralArguments = function(node) { + isLiteralArguments = function isLiteralArguments(node) { return node instanceof IdentifierLiteral && node.value === 'arguments'; }; - isLiteralThis = function(node) { + isLiteralThis = function isLiteralThis(node) { return node instanceof ThisLiteral || (node instanceof Code && node.bound); }; - shouldCacheOrIsAssignable = function(node) { + shouldCacheOrIsAssignable = function shouldCacheOrIsAssignable(node) { return node.shouldCache() || (typeof node.isAssignable === "function" ? node.isAssignable() : void 0); }; - unfoldSoak = function(o, parent, name) { + unfoldSoak = function unfoldSoak(o, parent, name) { var ifn; if (!(ifn = parent[name].unfoldSoak(o))) { return; diff --git a/lib/coffeescript/optparse.js b/lib/coffeescript/optparse.js index 3cc639ff3f..e6aff0d1f1 100644 --- a/lib/coffeescript/optparse.js +++ b/lib/coffeescript/optparse.js @@ -85,7 +85,7 @@ OPTIONAL = /\[(\w+(\*?))\]/; - buildRules = function(rules) { + buildRules = function buildRules(rules) { var j, len, results, tuple; results = []; for (j = 0, len = rules.length; j < len; j++) { @@ -98,7 +98,7 @@ return results; }; - buildRule = function(shortFlag, longFlag, description, options = {}) { + buildRule = function buildRule(shortFlag, longFlag, description, options = {}) { var match; match = longFlag.match(OPTIONAL); longFlag = longFlag.match(LONG_FLAG)[1]; @@ -112,7 +112,7 @@ }; }; - normalizeArguments = function(args) { + normalizeArguments = function normalizeArguments(args) { var arg, j, k, l, len, len1, match, ref, result; args = args.slice(0); result = []; diff --git a/lib/coffeescript/register.js b/lib/coffeescript/register.js index 8d3d982ec6..ea5f728844 100644 --- a/lib/coffeescript/register.js +++ b/lib/coffeescript/register.js @@ -10,7 +10,7 @@ path = require('path'); - loadFile = function(module, filename) { + loadFile = function loadFile(module, filename) { var answer; answer = CoffeeScript._compileFile(filename, false, true); return module._compile(answer, filename); @@ -23,7 +23,7 @@ require.extensions[ext] = loadFile; } Module = require('module'); - findExtension = function(filename) { + findExtension = function findExtension(filename) { var curExtension, extensions; extensions = path.basename(filename).split('.'); if (extensions[0] === '') { diff --git a/lib/coffeescript/repl.js b/lib/coffeescript/repl.js index 11faae8b66..115e8380e7 100644 --- a/lib/coffeescript/repl.js +++ b/lib/coffeescript/repl.js @@ -59,7 +59,7 @@ } }; - runInContext = function(js, context, filename) { + runInContext = function runInContext(js, context, filename) { if (context === global) { return vm.runInThisContext(js, filename); } else { @@ -67,7 +67,7 @@ } }; - addMultilineHandler = function(repl) { + addMultilineHandler = function addMultilineHandler(repl) { var inputStream, multiline, nodeLineListener, origPrompt, outputStream, ref, rli; ({rli, inputStream, outputStream} = repl); origPrompt = (ref = repl._prompt) != null ? ref : repl.prompt; @@ -123,7 +123,7 @@ }); }; - addHistory = function(repl, filename, maxSize) { + addHistory = function addHistory(repl, filename, maxSize) { var buffer, fd, lastLine, readFd, size, stat; lastLine = null; try { @@ -155,14 +155,14 @@ }); return repl.commands[getCommandId(repl, 'history')] = { help: 'Show command history', - action: function() { + action: function action() { repl.outputStream.write(`${repl.rli.history.slice(0).reverse().join('\n')}\n`); return repl.displayPrompt(); } }; }; - getCommandId = function(repl, commandName) { + getCommandId = function getCommandId(repl, commandName) { var commandsHaveLeadingDot; commandsHaveLeadingDot = repl.commands['.help'] != null; if (commandsHaveLeadingDot) { @@ -173,7 +173,7 @@ }; module.exports = { - start: function(opts = {}) { + start: function start(opts = {}) { var build, major, minor, repl; [major, minor, build] = process.versions.node.split('.').map(function(n) { return parseInt(n, 10); diff --git a/lib/coffeescript/rewriter.js b/lib/coffeescript/rewriter.js index ebae87c587..421014a665 100644 --- a/lib/coffeescript/rewriter.js +++ b/lib/coffeescript/rewriter.js @@ -3,7 +3,7 @@ var BALANCED_PAIRS, CALL_CLOSERS, EXPRESSION_CLOSE, EXPRESSION_END, EXPRESSION_START, IMPLICIT_CALL, IMPLICIT_END, IMPLICIT_FUNC, IMPLICIT_UNSPACED_CALL, INVERSES, LINEBREAKS, SINGLE_CLOSERS, SINGLE_LINERS, generate, k, left, len, rite, indexOf = [].indexOf; - generate = function(tag, value, origin) { + generate = function generate(tag, value, origin) { var tok; tok = [tag, value]; tok.generated = true; @@ -75,11 +75,11 @@ closeOpenCalls() { var action, condition; - condition = function(token, i) { + condition = function condition(token, i) { var ref; return ((ref = token[0]) === ')' || ref === 'CALL_END') || token[0] === 'OUTDENT' && this.tag(i - 1) === ')'; }; - action = function(token, i) { + action = function action(token, i) { return this.tokens[token[0] === 'OUTDENT' ? i - 1 : i][0] = 'CALL_END'; }; return this.scanTokens(function(token, i) { @@ -92,11 +92,11 @@ closeOpenIndexes() { var action, condition; - condition = function(token, i) { + condition = function condition(token, i) { var ref; return (ref = token[0]) === ']' || ref === 'INDEX_END'; }; - action = function(token, i) { + action = function action(token, i) { return token[0] = 'INDEX_END'; }; return this.scanTokens(function(token, i) { @@ -172,30 +172,30 @@ [tag] = token; [prevTag] = prevToken = i > 0 ? tokens[i - 1] : []; [nextTag] = i < tokens.length - 1 ? tokens[i + 1] : []; - stackTop = function() { + stackTop = function stackTop() { return stack[stack.length - 1]; }; startIdx = i; - forward = function(n) { + forward = function forward(n) { return i - startIdx + n; }; - inImplicit = function() { + inImplicit = function inImplicit() { var ref, ref1; return (ref = stackTop()) != null ? (ref1 = ref[2]) != null ? ref1.ours : void 0 : void 0; }; - inImplicitCall = function() { + inImplicitCall = function inImplicitCall() { var ref; return inImplicit() && ((ref = stackTop()) != null ? ref[0] : void 0) === '('; }; - inImplicitObject = function() { + inImplicitObject = function inImplicitObject() { var ref; return inImplicit() && ((ref = stackTop()) != null ? ref[0] : void 0) === '{'; }; - inImplicitControl = function() { + inImplicitControl = function inImplicitControl() { var ref; return inImplicit && ((ref = stackTop()) != null ? ref[0] : void 0) === 'CONTROL'; }; - startImplicitCall = function(j) { + startImplicitCall = function startImplicitCall(j) { var idx; idx = j != null ? j : i; stack.push([ @@ -208,12 +208,12 @@ return i += 1; } }; - endImplicitCall = function() { + endImplicitCall = function endImplicitCall() { stack.pop(); tokens.splice(i, 0, generate('CALL_END', ')', ['', 'end of input', token[2]])); return i += 1; }; - startImplicitObject = function(j, startsLine = true) { + startImplicitObject = function startImplicitObject(j, startsLine = true) { var idx, val; idx = j != null ? j : i; stack.push([ @@ -230,7 +230,7 @@ return i += 1; } }; - endImplicitObject = function(j) { + endImplicitObject = function endImplicitObject(j) { j = j != null ? j : i; stack.pop(); tokens.splice(j, 0, generate('}', '}', token)); @@ -393,11 +393,11 @@ normalizeLines() { var action, condition, indent, outdent, starter; starter = indent = outdent = null; - condition = function(token, i) { + condition = function condition(token, i) { var ref, ref1, ref2, ref3; return token[1] !== ';' && (ref = token[0], indexOf.call(SINGLE_CLOSERS, ref) >= 0) && !(token[0] === 'TERMINATOR' && (ref1 = this.tag(i + 1), indexOf.call(EXPRESSION_CLOSE, ref1) >= 0)) && !(token[0] === 'ELSE' && starter !== 'THEN') && !(((ref2 = token[0]) === 'CATCH' || ref2 === 'FINALLY') && (starter === '->' || starter === '=>')) || (ref3 = token[0], indexOf.call(CALL_CLOSERS, ref3) >= 0) && this.tokens[i - 1].newLine; }; - action = function(token, i) { + action = function action(token, i) { return this.tokens.splice((this.tag(i - 1) === ',' ? i - 1 : i), 0, outdent); }; return this.scanTokens(function(token, i, tokens) { @@ -442,13 +442,13 @@ tagPostfixConditionals() { var action, condition, original; original = null; - condition = function(token, i) { + condition = function condition(token, i) { var prevTag, tag; [tag] = token; [prevTag] = this.tokens[i - 1]; return tag === 'TERMINATOR' || (tag === 'INDENT' && indexOf.call(SINGLE_LINERS, prevTag) < 0); }; - action = function(token, i) { + action = function action(token, i) { if (token[0] !== 'INDENT' || (token.generated && !token.fromThen)) { return original[0] = 'POST_' + original[0]; } diff --git a/src/nodes.coffee b/src/nodes.coffee index 49d12250c6..1081aa5404 100644 --- a/src/nodes.coffee +++ b/src/nodes.coffee @@ -1764,15 +1764,18 @@ exports.Assign = class Assign extends Base else o.scope.find name.value + compiledName = @variable.compileToFragments o, LEVEL_LIST + if @value instanceof Code if @value.isStatic @value.name = @variable.properties[0] else if @variable.properties?.length >= 2 [properties..., prototype, name] = @variable.properties @value.name = name if prototype.name?.value is 'prototype' + else + @value.outputName = compiledName val = @value.compileToFragments o, LEVEL_LIST - compiledName = @variable.compileToFragments o, LEVEL_LIST if @context is 'object' if @variable.shouldCache() @@ -2144,18 +2147,18 @@ exports.Code = class Code extends Base # If there were parameters after the splat or expansion parameter, those # parameters need to be assigned in the body of the function. if paramsAfterSplat.length isnt 0 - # Create a destructured assignment, e.g. `[a, b, c] = [args..., b, c]` + # Create a destructured assignment, e.g. `[a, b, c] = [args..., b, c]`. exprs.unshift new Assign new Value( new Arr [new Splat(new IdentifierLiteral(splatParamName)), (param.asReference o for param in paramsAfterSplat)...] ), new Value new IdentifierLiteral splatParamName - # Add new expressions to the function body + # Add new expressions to the function body. wasEmpty = @body.isEmpty() @body.expressions.unshift thisAssignments... unless @expandCtorSuper thisAssignments @body.expressions.unshift exprs... @body.makeReturn() unless wasEmpty or @noReturn - # Assemble the output + # Assemble the output. modifiers = [] modifiers.push 'static' if @isMethod and @isStatic modifiers.push 'async' if @isAsync @@ -2164,7 +2167,14 @@ exports.Code = class Code extends Base else if @isGenerator modifiers.push '*' - signature = [@makeCode '('] + # Name this function, if it has a name we can use. + if @outputName and not @bound + outputName = fragmentsToText @outputName + outputName = no if outputName in JS_FORBIDDEN or /'|"|\.|\[/.test(outputName) + + signature = [] + signature.push @makeCode " #{outputName}" if outputName + signature.push @makeCode '(' for param, i in params signature.push @makeCode ', ' if i signature.push @makeCode '...' if haveSplatParam and i is params.length - 1 @@ -2173,7 +2183,7 @@ exports.Code = class Code extends Base body = @body.compileWithDeclarations o unless @body.isEmpty() - # We need to compile the body before method names to ensure super references are handled + # We need to compile the body before method names to ensure super references are handled. if @isMethod [methodScope, o.scope] = [o.scope, o.scope.parent] name = @name.compileToFragments o diff --git a/test/comments.coffee b/test/comments.coffee index e6489b2467..302d5c5baf 100644 --- a/test/comments.coffee +++ b/test/comments.coffee @@ -275,7 +275,7 @@ test "#3132: Format indented block-comment nicely", -> result = """ var fn; - fn = function() { + fn = function fn() { /* * Indented @@ -308,7 +308,7 @@ test "#3132: Format jsdoc-style block-comment nicely", -> */ var fn; - fn = function() { + fn = function fn() { return 1; }; @@ -336,7 +336,7 @@ test "#3132: Format hand-made (raw) jsdoc-style block-comment nicely", -> */ var fn; - fn = function() { + fn = function fn() { return 1; }; diff --git a/test/functions.coffee b/test/functions.coffee index cfe29c9c0f..089dce94cf 100644 --- a/test/functions.coffee +++ b/test/functions.coffee @@ -98,7 +98,7 @@ test "self-referencing functions", -> changeMe = -> changeMe = 2 - changeMe() + changeMe = changeMe() eq changeMe, 2 diff --git a/test/modules.coffee b/test/modules.coffee index c26dabfb3e..e237c2dd04 100644 --- a/test/modules.coffee +++ b/test/modules.coffee @@ -400,7 +400,7 @@ test "export assignment function", -> export foo = (bar) -> console.log bar""" output = """ - export var foo = function(bar) { + export var foo = function foo(bar) { return console.log(bar); };""" eq toJS(input), output @@ -411,7 +411,7 @@ test "export assignment function which contains assignments in its body", -> baz = '!' console.log bar + baz""" output = """ - export var foo = function(bar) { + export var foo = function foo(bar) { var baz; baz = '!'; return console.log(bar + baz); @@ -426,7 +426,7 @@ test "export default predefined function", -> output = """ var foo; - foo = function(bar) { + foo = function foo(bar) { return console.log(bar); }; @@ -658,7 +658,7 @@ test "CoffeeScript keywords can be used as imported names in import lists", -> test "`*` can be used in an expression on the same line as an export keyword", -> input = "export foo = (x) -> x * x" output = """ - export var foo = function(x) { + export var foo = function foo(x) { return x * x; };""" eq toJS(input), output @@ -666,7 +666,7 @@ test "`*` can be used in an expression on the same line as an export keyword", - output = """ var foo; - export default foo = function(x) { + export default foo = function foo(x) { return x * x; };""" eq toJS(input), output @@ -679,7 +679,7 @@ test "`*` and `from` can be used in an export default expression", -> from = from * 3""" output = """ export default foo.extend({ - bar: function() { + bar: function bar() { var from; from = 5; return from = from * 3;