more es6, template literals and modules

This commit is contained in:
Sebastian McKenzie 2015-03-03 22:31:49 +11:00
parent 73062ae240
commit ed40ec03d1
29 changed files with 146 additions and 73 deletions

View File

@ -25,7 +25,7 @@ transform.load = function (url, callback, opts = {}, hold) {
if (!hold) transform.run.apply(transform, param);
if (callback) callback(param);
} else {
throw new Error("Could not load " + url);
throw new Error(`Could not load ${url}`);
}
};

View File

@ -46,7 +46,7 @@ var compile = function (filename) {
var opts = extend({}, transformOpts);
resolveRc(filename, opts);
var cacheKey = filename + ":" + JSON.stringify(opts);
var cacheKey = `${filename}:${JSON.stringify(opts)}`;
if (cache) {
var cached = cache[cacheKey];

View File

@ -23,7 +23,7 @@ export default function (loc, opts = {}) {
try {
json = JSON.parse(content);
} catch (err) {
err.message = file + ": " + err.message;
err.message = `${file}: ${err.message}`;
throw err;
}

View File

@ -140,7 +140,7 @@ export default class Buffer {
var indent = this.getIndent();
// replace all newlines with newlines with the indentation
str = str.replace(/\n/g, "\n" + indent);
str = str.replace(/\n/g, `\n${indent}`);
// we've got a newline before us so prepend on the indentation
if (this.isLast("\n")) this._push(indent);

View File

@ -109,16 +109,19 @@ export function ExpressionStatement(node, print) {
this.semicolon();
}
exports.BinaryExpression =
exports.LogicalExpression =
exports.AssignmentPattern =
exports.AssignmentExpression = function (node, print) {
export function AssignmentExpression(node, print) {
// todo: add cases where the spaces can be dropped when in compact mode
print(node.left);
this.push(" ");
this.push(node.operator);
this.push(" ");
print(node.right);
}
export {
AssignmentExpression as BinaryExpression,
AssignmentExpression as LogicalExpression,
AssignmentExpression as AssignmentPattern
};
var SCIENTIFIC_NOTATION = /e/i;

View File

@ -44,8 +44,7 @@ export function _method(node, print) {
print(value.body);
}
exports.FunctionDeclaration =
exports.FunctionExpression = function (node, print) {
export function FunctionExpression(node, print) {
if (node.async) this.push("async ");
this.push("function");
if (node.generator) this.push("*");
@ -60,7 +59,9 @@ exports.FunctionExpression = function (node, print) {
this._params(node, print);
this.space();
print(node.body);
};
}
export { FunctionExpression as FunctionDeclaration };
export function ArrowFunctionExpression(node, print) {
if (node.async) this.push("async ");

View File

@ -5,7 +5,7 @@ export function ImportSpecifier(node, print) {
if (t.isSpecifierDefault(node)) {
print(t.getSpecifierName(node));
} else {
return exports.ExportSpecifier.apply(this, arguments);
return ExportSpecifier.apply(this, arguments);
}
}

View File

@ -2,6 +2,6 @@ import each from "lodash/collection/each";
each(["BindMemberExpression", "BindFunctionExpression"], function (type) {
exports[type] = function () {
throw new ReferenceError("Trying to render non-standard playground node " + JSON.stringify(type));
throw new ReferenceError(`Trying to render non-standard playground node ${JSON.stringify(type)}`);
};
});

View File

@ -60,7 +60,7 @@ var buildForXStatement = function (op) {
this.keyword("for");
this.push("(");
print(node.left);
this.push(" " + op + " ");
this.push(` ${op} `);
print(node.right);
this.push(")");
print.block(node.body);
@ -192,7 +192,7 @@ export function VariableDeclaration(node, print, parent) {
var sep = ",";
if (!this.format.compact && hasInits) {
sep += "\n" + repeating(" ", node.kind.length + 1);
sep += `\n${repeating(" ", node.kind.length + 1)}`;
} else {
sep += " ";
}

View File

@ -4,12 +4,12 @@ export function Identifier(node) {
this.push(node.name);
}
exports.RestElement =
exports.SpreadElement =
exports.SpreadProperty = function (node, print) {
export function RestElement(node, print) {
this.push("...");
print(node.argument);
};
}
export { RestElement as SpreadElement, RestElement as SpreadProperty };
export function VirtualPropertyExpression(node, print) {
print(node.object);
@ -17,8 +17,7 @@ export function VirtualPropertyExpression(node, print) {
print(node.property);
}
exports.ObjectExpression =
exports.ObjectPattern = function (node, print) {
export function ObjectExpression(node, print) {
var props = node.properties;
if (props.length) {
@ -32,7 +31,9 @@ exports.ObjectPattern = function (node, print) {
} else {
this.push("{}");
}
};
}
export { ObjectExpression as ObjectPattern };
export function Property(node, print) {
if (node.method || node.kind === "get" || node.kind === "set") {
@ -53,8 +54,7 @@ export function Property(node, print) {
}
}
exports.ArrayExpression =
exports.ArrayPattern = function (node, print) {
export function ArrayExpression(node, print) {
var elems = node.elements;
var len = elems.length;
@ -76,7 +76,9 @@ exports.ArrayPattern = function (node, print) {
});
this.push("]");
};
}
export { ArrayExpression as ArrayPattern };
export function Literal(node) {
var val = node.value;
@ -89,7 +91,7 @@ export function Literal(node) {
} else if (type === "boolean") {
this.push(val ? "true" : "false");
} else if (node.regex) {
this.push("/" + node.regex.pattern + "/" + node.regex.flags);
this.push(`/${node.regex.pattern}/${node.regex.flags}`);
} else if (val === null) {
this.push("null");
}

View File

@ -187,7 +187,7 @@ class CodeGenerator {
this.printTrailingComments(node, parent);
} else {
throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name));
throw new ReferenceError(`unknown node of type ${JSON.stringify(node.type)} with constructor ${JSON.stringify(node && node.constructor.name)}`);
}
this.format.concise = oldConcise;
@ -238,9 +238,9 @@ class CodeGenerator {
generateComment(comment) {
var val = comment.value;
if (comment.type === "Line") {
val = "//" + val;
val = `//${val}`;
} else {
val = "/*" + val + "*/";
val = `/*${val}*/`;
}
return val;
}
@ -319,7 +319,7 @@ class CodeGenerator {
}
var indent = Math.max(this.indentSize(), column);
val = val.replace(/\n/g, "\n" + repeating(" ", indent));
val = val.replace(/\n/g, `\n${repeating(" ", indent)}`);
}
if (column === 0) {

View File

@ -81,8 +81,7 @@ module.exports = function (lines, lineNumber, colNumber) {
return;
}
if (colNumber) {
params.line += "\n" + params.before + repeating(" ", params.width) +
params.after + repeating(" ", colNumber - 1) + "^";
params.line += `\n${params.before}${repeating(" ", params.width)}${params.after}${repeating(" ", colNumber - 1)}^`;
}
params.before = params.before.replace(/^./, ">");
}

View File

@ -32,7 +32,7 @@ module.exports = function (opts, code, callback) {
} catch (err) {
if (!err._babel) {
err._babel = true;
var message = opts.filename + ": " + err.message;
var message = `${opts.filename}: ${err.message}`;
var loc = err.loc;
if (loc) {

View File

@ -22,14 +22,14 @@ export var messages = {
};
export function get(key) {
var msg = exports.messages[key];
if (!msg) throw new ReferenceError("Unknown message `" + key + "`");
var msg = messages[key];
if (!msg) throw new ReferenceError(`Unknown message ${JSON.stringify(key)}`);
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
args = exports.parseArgs(args);
args = parseArgs(args);
return msg.replace(/\$(\d+)/g, function (str, i) {
return args[--i];

View File

@ -10,7 +10,7 @@ export function push(mutatorMap, key, kind, computed, value) {
if (t.isIdentifier(key)) {
alias = key.name;
if (computed) alias = "computed:" + alias;
if (computed) alias = `computed:${alias}`;
} else if (t.isLiteral(key)) {
alias = String(key.value);
} else {

View File

@ -23,7 +23,7 @@ var getObjRef = function (node, nodes, file, scope) {
return ref;
}
} else {
throw new Error("We can't explode this node type " + node.type);
throw new Error(`We can't explode this node type ${node.type}`);
}
var temp = scope.generateUidBasedOnNode(ref);

View File

@ -7,7 +7,7 @@ export function has(node) {
export function wrap(node, callback) {
var useStrictNode;
if (exports.has(node)) {
if (has(node)) {
useStrictNode = node.body.shift();
}

View File

@ -30,7 +30,7 @@ transform._ensureTransformerNames = function (type, rawKeys) {
keys.push(aliasKey);
} else if (deprecatedKey) {
// deprecated key, remap it to the new one
console.error("The transformer " + key + " has been renamed to " + deprecatedKey);
console.error(`The transformer ${key} has been renamed to ${deprecatedKey}`);
rawKeys.push(deprecatedKey);
} else if (transform.transformers[key]) {
// valid key
@ -40,7 +40,7 @@ transform._ensureTransformerNames = function (type, rawKeys) {
keys = keys.concat(transform.namespaces[key]);
} else {
// invalid key
throw new ReferenceError("Unknown transformer " + key + " specified in " + type);
throw new ReferenceError(`Unknown transformer ${key} specified in ${type}`);
}
}

View File

@ -56,7 +56,7 @@ export default class TransformerPass {
var file = this.file;
file.debug("Running transformer " + this.transformer.key);
file.debug(`Running transformer ${this.transformer.key}`);
file.scope.traverse(file.ast, this.handlers, file);
}

View File

@ -32,12 +32,10 @@ export function BlockStatement(node, parent, scope, file) {
var letRefs = node._letReferences;
if (!letRefs) return;
var state = {
scope.traverse(node, visitor, {
letRefs: letRefs,
file: file
};
scope.traverse(node, visitor, state);
});
}
export { BlockStatement as Program, BlockStatement as Loop };

View File

@ -189,7 +189,7 @@ var loopVisitor = {
return;
}
loopText = loopText + "|" + node.label.name;
loopText = `${loopText}|${node.label.name}`;
} else {
// we shouldn't be transforming these statements because
// they don't refer to the actual loop we're scopifying

View File

@ -182,7 +182,7 @@ class ClassTransformer {
}
// we have no constructor, we have a super, and the super doesn't appear to be falsy
if (!this.hasConstructor && this.hasSuper && t.evaluateTruthy(superName) !== false) {
if (!this.hasConstructor && this.hasSuper && t.evaluateTruthy(superName, this.scope) !== false) {
var helperName = "class-super-constructor-call";
if (this.isLoose) helperName += "-loose";
constructor.body.body.push(util.template(helperName, {

View File

@ -229,7 +229,7 @@ class TailCallTransformer {
subTransform(node) {
if (!node) return;
var handler = this["subTransform" + node.type];
var handler = this[`subTransform${node.type}`];
if (handler) return handler.call(this, node);
}

View File

@ -19,8 +19,8 @@ function toStatements(node) {
export var optional = true;
export function ConditionalExpression(node) {
var evaluateTest = t.evaluateTruthy(node.test);
export function ConditionalExpression(node, parent, scope) {
var evaluateTest = t.evaluateTruthy(node.test, scope);
if (evaluateTest === true) {
return node.consequent;
} else if (evaluateTest === false) {
@ -29,12 +29,12 @@ export function ConditionalExpression(node) {
}
export var IfStatement = {
exit(node) {
exit(node, parent, scope) {
var consequent = node.consequent;
var alternate = node.alternate;
var test = node.test;
var evaluateTest = t.evaluateTruthy(test);
var evaluateTest = t.evaluateTruthy(test, scope);
// we can check if a test will be truthy 100% and if so then we can inline
// the consequent and completely ignore the alternate

View File

@ -2,7 +2,11 @@ import t from "../../../types";
export var optional = true;
export function Expression(node) {
var res = t.evaluate(node);
export function Expression(node, parent, scope) {
var res = t.evaluate(node, scope);
if (res.confident) return t.valueToNode(res.value);
}
export function Identifier() {
// override Expression
}

View File

@ -9,7 +9,7 @@ function traverse(parent, opts, scope, state) {
if (!opts.noScope && !scope) {
if (parent.type !== "Program" && parent.type !== "File") {
throw new Error("Must pass a scope unless traversing a Program/File got a " + parent.type + " node");
throw new Error(`Must pass a scope unless traversing a Program/File got a ${parent.type} node`);
}
}

View File

@ -143,7 +143,7 @@ export default class Scope {
_generateUid(name, i) {
var id = name;
if (i > 1) id += i;
return "_" + id;
return `_${id}`;
}
/*
@ -415,7 +415,7 @@ export default class Scope {
registerVariableDeclaration(declar) {
var declars = declar.declarations;
for (var i = 0; i < declars.length; i++) {
this.registerBinding(declars[i], declar.kind);
this.registerBinding(declar.kind, declars[i]);
}
}
@ -538,7 +538,7 @@ export default class Scope {
init: opts.init
};
} else {
throw new TypeError("cannot add a declaration here in node type " + block.type);
throw new TypeError(`cannot add a declaration here in node type ${block.type}`);
}
}
@ -626,6 +626,37 @@ export default class Scope {
return binding && binding.identifier;
}
getOwnImmutableBindingValue(name) {
return this._immutableBindingInfoToValue(this.getOwnBindingInfo(name));
}
getImmutableBindingValue(name) {
return this._immutableBindingInfoToValue(this.getBindingInfo(name));
}
_immutableBindingInfoToValue(info) {
if (!info) return;
// can't guarantee this value is the same
if (info.reassigned) return;
var node = info.node;
if (t.isVariableDeclarator(node)) {
if (t.isIdentifier(node.id)) {
node = node.init;
} else {
// otherwise it's probably a destructuring like:
// var { foo } = "foo";
return;
}
}
if (t.isImmutable(node)) {
return node;
}
}
// has
hasOwnBinding(name) {

View File

@ -21,14 +21,14 @@ export default t;
*/
function registerType(type, skipAliasCheck) {
var is = t["is" + type] = function (node, opts) {
var is = t[`is${type}`] = function (node, opts) {
return t.is(type, node, opts, skipAliasCheck);
};
t["assert" + type] = function (node, opts) {
t[`assert${type}`] = function (node, opts) {
opts ||= {};
if (!is(node, opts)) {
throw new Error("Expected type " + JSON.stringify(type) + " with option " + JSON.stringify(opts));
throw new Error(`Expected type ${JSON.stringify(type)} with option ${JSON.stringify(opts)}`);
}
};
}
@ -395,7 +395,7 @@ t.toIdentifier = function (name) {
});
if (!t.isValidIdentifier(name)) {
name = "_" + name;
name = `_${name}`;
}
return name || "_";
@ -506,7 +506,7 @@ t.toStatement = function (node, ignore) {
if (ignore) {
return false;
} else {
throw new Error("cannot turn " + node.type + " to a statement");
throw new Error(`cannot turn ${node.type} to a statement`);
}
}
@ -536,7 +536,7 @@ t.toExpression = function (node) {
if (t.isExpression(node)) {
return node;
} else {
throw new Error("cannot turn " + node.type + " to an expression");
throw new Error(`cannot turn ${node.type} to an expression`);
}
};
@ -807,6 +807,35 @@ t.isScope = function (node, parent) {
return t.isScopable(node);
};
/**
* Description
*
* @param {Node} node
* @returns {Boolean}
*/
t.isImmutable = function (node) {
if (t.isLiteral(node)) {
if (node.regex) {
// regexes are mutable
return false;
} else {
// immutable!
return true;
}
} else if (t.isIdentifier(node)) {
if (node.name === "undefined") {
// immutable!
return true;
} else {
// no idea...
return false;
}
}
return false;
};
/**
* Walk the input `node` and statically evaluate if it's truthy.
*
@ -824,11 +853,12 @@ t.isScope = function (node, parent) {
* if (!t.evaluateTruthy(node)) falsyLogic();
*
* @param {Node} node
* @param {Scope} scope
* @returns {Boolean}
*/
t.evaluateTruthy = function (node) {
var res = t.evaluate(node);
t.evaluateTruthy = function (node, scope) {
var res = t.evaluate(node, scope);
if (res.confident) return !!res.value;
};
@ -846,10 +876,11 @@ t.evaluateTruthy = function (node) {
* t.evaluate(parse("foo + foo")) // { confident: false, value: undefined }
*
* @param {Node} node
* @param {Scope} scope
* @returns {Object}
*/
t.evaluate = function (node) {
t.evaluate = function (node, scope) {
var confident = true;
var value = evaluate(node);
@ -882,8 +913,12 @@ t.evaluate = function (node) {
}
}
if (t.isIdentifier(node, { name: "undefined" })) {
if (t.isIdentifier(node)) {
if (node.name === "undefined") {
return undefined;
} else {
return evaluate(scope.getImmutableBindingValue(node.name));
}
}
if (t.isUnaryExpression(node, { prefix: true })) {

View File

@ -20,7 +20,7 @@ export { inherits, inspect } from "util";
export var debug = buildDebug("babel");
export function canCompile(filename, altExts) {
var exts = altExts || exports.canCompile.EXTENSIONS;
var exts = altExts || canCompile.EXTENSIONS;
var ext = path.extname(filename);
return contains(exts, ext);
}
@ -50,7 +50,7 @@ export function regexify(val) {
export function arrayify(val) {
if (!val) return [];
if (isBoolean(val)) return [val];
if (isString(val)) return exports.list(val);
if (isString(val)) return list(val);
if (Array.isArray(val)) return val;
throw new TypeError("illegal type for arrayify");
}
@ -75,7 +75,7 @@ var templateVisitor = {
export function template(name, nodes, keepExpression) {
var ast = exports.templates[name];
if (!ast) throw new ReferenceError("unknown template " + name);
if (!ast) throw new ReferenceError(`unknown template ${name}`);
if (nodes === true) {
keepExpression = true;