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/coffeescript.js
Danny McClanahan 4e57ca6833 [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 16:25:06 -07:00

308 lines
9.9 KiB
JavaScript

// Generated by CoffeeScript 2.0.0-beta3
(function() {
var Lexer, SourceMap, base64encode, checkShebangLine, compile, formatSourcePosition, getSourceMap, helpers, lexer, packageJson, parser, sourceMaps, sources, withPrettyErrors;
({Lexer} = require('./lexer'));
({parser} = require('./parser'));
helpers = require('./helpers');
SourceMap = require('./sourcemap');
packageJson = require('../../package.json');
exports.VERSION = packageJson.version;
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(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) {
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);
}
};
};
sources = {};
sourceMaps = {};
exports.compile = compile = withPrettyErrors(function(code, options) {
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;
({merge, extend} = helpers);
options = extend({}, options);
generateSourceMap = options.sourceMap || options.inlineMap || (options.filename == null);
filename = options.filename || '<anonymous>';
checkShebangLine(filename, code);
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;
})();
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);
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 {
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 = exports.eval = exports.register = function() {
throw new Error('require index.coffee, not this file');
};
lexer = new Lexer;
parser.lexer = {
lex: function() {
var tag, token;
token = parser.tokens[this.pos++];
if (token) {
[tag, this.yytext, this.yylloc] = token;
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, {token}) {
var errorLoc, errorTag, errorText, errorToken, tokens;
({errorToken, tokens} = parser);
[errorTag, errorText, errorLoc] = errorToken;
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;
}
};
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)
});
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;
results = [];
for (i = 0, len = stack.length; i < len; i++) {
frame = stack[i];
if (frame.getFunction() === exports.run) {
break;
}
results.push(` at ${formatSourcePosition(frame, getSourceMapping)}`);
}
return results;
})();
return `${err.toString()}\n${frames.join('\n')}\n`;
};
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);