1
0
Fork 0
mirror of https://github.com/jashkenas/coffeescript.git synced 2022-11-09 12:23:24 -05:00
jashkenas--coffeescript/lib/coffeescript/repl.js
Geoffrey Booth 704924c3cd 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 09:58:05 -07:00

206 lines
6.4 KiB
JavaScript

// Generated by CoffeeScript 2.0.0-beta3
(function() {
var CoffeeScript, addHistory, addMultilineHandler, fs, getCommandId, merge, nodeREPL, path, replDefaults, runInContext, updateSyntaxError, vm;
fs = require('fs');
path = require('path');
vm = require('vm');
nodeREPL = require('repl');
CoffeeScript = require('./');
({merge, updateSyntaxError} = require('./helpers'));
replDefaults = {
prompt: 'coffee> ',
historyFile: (function() {
var historyPath;
historyPath = process.env.XDG_CACHE_HOME || process.env.HOME;
if (historyPath) {
return path.join(historyPath, '.coffee_history');
}
})(),
historyMaxInputSize: 10240,
eval: function(input, context, filename, cb) {
var Assign, Block, Literal, Value, ast, err, js, referencedVars, token, tokens;
input = input.replace(/\uFF00/g, '\n');
input = input.replace(/^\(([\s\S]*)\n\)$/m, '$1');
input = input.replace(/^\s*try\s*{([\s\S]*)}\s*catch.*$/m, '$1');
({Block, Assign, Value, Literal} = require('./nodes'));
try {
tokens = CoffeeScript.tokens(input);
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;
})();
ast = CoffeeScript.nodes(tokens);
ast = new Block([new Assign(new Value(new Literal('__')), ast, '=')]);
js = ast.compile({
bare: true,
locals: Object.keys(context),
referencedVars
});
return cb(null, runInContext(js, context, filename));
} catch (error) {
err = error;
updateSyntaxError(err, input);
return cb(err);
}
}
};
runInContext = function(js, context, filename) {
if (context === global) {
return vm.runInThisContext(js, filename);
} else {
return vm.runInContext(js, context, filename);
}
};
addMultilineHandler = function(repl) {
var inputStream, multiline, nodeLineListener, origPrompt, outputStream, ref, rli;
({rli, inputStream, outputStream} = repl);
origPrompt = (ref = repl._prompt) != null ? ref : repl.prompt;
multiline = {
enabled: false,
initialPrompt: origPrompt.replace(/^[^> ]*/, function(x) {
return x.replace(/./g, '-');
}),
prompt: origPrompt.replace(/^[^> ]*>?/, function(x) {
return x.replace(/./g, '.');
}),
buffer: ''
};
nodeLineListener = rli.listeners('line')[0];
rli.removeListener('line', nodeLineListener);
rli.on('line', function(cmd) {
if (multiline.enabled) {
multiline.buffer += `${cmd}\n`;
rli.setPrompt(multiline.prompt);
rli.prompt(true);
} else {
rli.setPrompt(origPrompt);
nodeLineListener(cmd);
}
});
return inputStream.on('keypress', function(char, key) {
if (!(key && key.ctrl && !key.meta && !key.shift && key.name === 'v')) {
return;
}
if (multiline.enabled) {
if (!multiline.buffer.match(/\n/)) {
multiline.enabled = !multiline.enabled;
rli.setPrompt(origPrompt);
rli.prompt(true);
return;
}
if ((rli.line != null) && !rli.line.match(/^\s*$/)) {
return;
}
multiline.enabled = !multiline.enabled;
rli.line = '';
rli.cursor = 0;
rli.output.cursorTo(0);
rli.output.clearLine(1);
multiline.buffer = multiline.buffer.replace(/\n/g, '\uFF00');
rli.emit('line', multiline.buffer);
multiline.buffer = '';
} else {
multiline.enabled = !multiline.enabled;
rli.setPrompt(multiline.initialPrompt);
rli.prompt(true);
}
});
};
addHistory = function(repl, filename, maxSize) {
var buffer, fd, lastLine, readFd, size, stat;
lastLine = null;
try {
stat = fs.statSync(filename);
size = Math.min(maxSize, stat.size);
readFd = fs.openSync(filename, 'r');
buffer = Buffer.alloc(size);
fs.readSync(readFd, buffer, 0, size, stat.size - size);
fs.closeSync(readFd);
repl.rli.history = buffer.toString().split('\n').reverse();
if (stat.size > maxSize) {
repl.rli.history.pop();
}
if (repl.rli.history[0] === '') {
repl.rli.history.shift();
}
repl.rli.historyIndex = -1;
lastLine = repl.rli.history[0];
} catch (error) {}
fd = fs.openSync(filename, 'a');
repl.rli.addListener('line', function(code) {
if (code && code.length && code !== '.history' && code !== '.exit' && lastLine !== code) {
fs.writeSync(fd, `${code}\n`);
return lastLine = code;
}
});
repl.on('exit', function() {
return fs.closeSync(fd);
});
return repl.commands[getCommandId(repl, 'history')] = {
help: 'Show command history',
action: function() {
repl.outputStream.write(`${repl.rli.history.slice(0).reverse().join('\n')}\n`);
return repl.displayPrompt();
}
};
};
getCommandId = function(repl, commandName) {
var commandsHaveLeadingDot;
commandsHaveLeadingDot = repl.commands['.help'] != null;
if (commandsHaveLeadingDot) {
return `.${commandName}`;
} else {
return commandName;
}
};
module.exports = {
start: function(opts = {}) {
var build, major, minor, repl;
[major, minor, build] = process.versions.node.split('.').map(function(n) {
return parseInt(n, 10);
});
if (major < 6) {
console.warn("Node 6+ required for CoffeeScript REPL");
process.exit(1);
}
CoffeeScript.register();
process.argv = ['coffee'].concat(process.argv.slice(2));
opts = merge(replDefaults, opts);
repl = nodeREPL.start(opts);
if (opts.prelude) {
runInContext(opts.prelude, repl.context, 'prelude');
}
repl.on('exit', function() {
if (!repl.rli.closed) {
return repl.outputStream.write('\n');
}
});
addMultilineHandler(repl);
if (opts.historyFile) {
addHistory(repl, opts.historyFile, opts.historyMaxInputSize);
}
repl.commands[getCommandId(repl, 'load')].help = 'Load code from a file into this REPL session';
return repl;
}
};
}).call(this);