more classes!

This commit is contained in:
Sebastian McKenzie 2015-02-26 12:19:28 +11:00
parent f7186980e5
commit 553eb2d45e
13 changed files with 2125 additions and 2117 deletions

View File

@ -1,173 +1,173 @@
module.exports = Buffer;
var repeating = require("repeating"); var repeating = require("repeating");
var trimRight = require("trim-right"); var trimRight = require("trim-right");
var isBoolean = require("lodash/lang/isBoolean"); var isBoolean = require("lodash/lang/isBoolean");
var includes = require("lodash/collection/includes"); var includes = require("lodash/collection/includes");
var isNumber = require("lodash/lang/isNumber"); var isNumber = require("lodash/lang/isNumber");
function Buffer(position, format) { export default class Buffer {
this.position = position; constructor(position, format) {
this._indent = format.indent.base; this.position = position;
this.format = format; this._indent = format.indent.base;
this.buf = ""; this.format = format;
} this.buf = "";
Buffer.prototype.get = function () {
return trimRight(this.buf);
};
Buffer.prototype.getIndent = function () {
if (this.format.compact || this.format.concise) {
return "";
} else {
return repeating(this.format.indent.style, this._indent);
} }
};
Buffer.prototype.indentSize = function () { get() {
return this.getIndent().length; return trimRight(this.buf);
};
Buffer.prototype.indent = function () {
this._indent++;
};
Buffer.prototype.dedent = function () {
this._indent--;
};
Buffer.prototype.semicolon = function () {
this.push(";");
};
Buffer.prototype.ensureSemicolon = function () {
if (!this.isLast(";")) this.semicolon();
};
Buffer.prototype.rightBrace = function () {
this.newline(true);
this.push("}");
};
Buffer.prototype.keyword = function (name) {
this.push(name);
this.space();
};
Buffer.prototype.space = function () {
if (this.format.compact) return;
if (this.buf && !this.isLast(" ") && !this.isLast("\n")) {
this.push(" ");
} }
};
Buffer.prototype.removeLast = function (cha) { getIndent() {
if (this.format.compact) return; if (this.format.compact || this.format.concise) {
if (!this.isLast(cha)) return; return "";
} else {
return repeating(this.format.indent.style, this._indent);
}
}
this.buf = this.buf.substr(0, this.buf.length - 1); indentSize() {
this.position.unshift(cha); return this.getIndent().length;
}; }
Buffer.prototype.newline = function (i, removeLast) { indent() {
if (this.format.compact) return; this._indent++;
}
if (this.format.concise) { dedent() {
this._indent--;
}
semicolon() {
this.push(";");
}
ensureSemicolon() {
if (!this.isLast(";")) this.semicolon();
}
rightBrace() {
this.newline(true);
this.push("}");
}
keyword(name) {
this.push(name);
this.space(); this.space();
return;
} }
removeLast ||= false; space() {
if (this.format.compact) return;
if (isNumber(i)) { if (this.buf && !this.isLast(" ") && !this.isLast("\n")) {
i = Math.min(2, i); this.push(" ");
if (this.endsWith("{\n") || this.endsWith(":\n")) i--;
if (i <= 0) return;
while (i > 0) {
this._newline(removeLast);
i--;
} }
return;
} }
if (isBoolean(i)) { removeLast(cha) {
removeLast = i; if (this.format.compact) return;
if (!this.isLast(cha)) return;
this.buf = this.buf.substr(0, this.buf.length - 1);
this.position.unshift(cha);
} }
this._newline(removeLast); newline(i, removeLast) {
}; if (this.format.compact) return;
Buffer.prototype._newline = function (removeLast) { if (this.format.concise) {
// never allow more than two lines this.space();
if (this.endsWith("\n\n")) return; return;
// remove the last newline
if (removeLast && this.isLast("\n")) this.removeLast("\n");
this.removeLast(" ");
this._removeSpacesAfterLastNewline();
this._push("\n");
};
/**
* If buffer ends with a newline and some spaces after it, trim those spaces.
*/
Buffer.prototype._removeSpacesAfterLastNewline = function () {
var lastNewlineIndex = this.buf.lastIndexOf("\n");
if (lastNewlineIndex === -1)
return;
var index = this.buf.length - 1;
while (index > lastNewlineIndex) {
if (this.buf[index] !== " ") {
break;
} }
index--; removeLast ||= false;
if (isNumber(i)) {
i = Math.min(2, i);
if (this.endsWith("{\n") || this.endsWith(":\n")) i--;
if (i <= 0) return;
while (i > 0) {
this._newline(removeLast);
i--;
}
return;
}
if (isBoolean(i)) {
removeLast = i;
}
this._newline(removeLast);
} }
if (index === lastNewlineIndex) { _newline(removeLast) {
this.buf = this.buf.substring(0, index + 1); // never allow more than two lines
} if (this.endsWith("\n\n")) return;
};
Buffer.prototype.push = function (str, noIndent) { // remove the last newline
if (!this.format.compact && this._indent && !noIndent && str !== "\n") { if (removeLast && this.isLast("\n")) this.removeLast("\n");
// we have an indent level and we aren't pushing a newline
var indent = this.getIndent();
// replace all newlines with newlines with the indentation this.removeLast(" ");
str = str.replace(/\n/g, "\n" + indent); this._removeSpacesAfterLastNewline();
this._push("\n");
// we've got a newline before us so prepend on the indentation
if (this.isLast("\n")) this._push(indent);
} }
this._push(str); /**
}; * If buffer ends with a newline and some spaces after it, trim those spaces.
*/
Buffer.prototype._push = function (str) { _removeSpacesAfterLastNewline() {
this.position.push(str); var lastNewlineIndex = this.buf.lastIndexOf("\n");
this.buf += str; if (lastNewlineIndex === -1)
}; return;
Buffer.prototype.endsWith = function (str) { var index = this.buf.length - 1;
return this.buf.slice(-str.length) === str; while (index > lastNewlineIndex) {
}; if (this.buf[index] !== " ") {
break;
}
Buffer.prototype.isLast = function (cha) { index--;
if (this.format.compact) return false; }
var buf = this.buf; if (index === lastNewlineIndex) {
var last = buf[buf.length - 1]; this.buf = this.buf.substring(0, index + 1);
}
if (Array.isArray(cha)) {
return includes(cha, last);
} else {
return cha === last;
} }
};
push(str, noIndent) {
if (!this.format.compact && this._indent && !noIndent && str !== "\n") {
// we have an indent level and we aren't pushing a newline
var indent = this.getIndent();
// replace all newlines with newlines with the indentation
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);
}
this._push(str);
}
_push(str) {
this.position.push(str);
this.buf += str;
}
endsWith(str) {
return this.buf.slice(-str.length) === str;
}
isLast(cha) {
if (this.format.compact) return false;
var buf = this.buf;
var last = buf[buf.length - 1];
if (Array.isArray(cha)) {
return includes(cha, last);
} else {
return cha === last;
}
}
}

View File

@ -1,10 +1,3 @@
module.exports = function (ast, opts, code) {
var gen = new CodeGenerator(ast, opts, code);
return gen.generate();
};
module.exports.CodeGenerator = CodeGenerator;
var detectIndent = require("detect-indent"); var detectIndent = require("detect-indent");
var Whitespace = require("./whitespace"); var Whitespace = require("./whitespace");
var repeating = require("repeating"); var repeating = require("repeating");
@ -17,19 +10,336 @@ var each = require("lodash/collection/each");
var n = require("./node"); var n = require("./node");
var t = require("../types"); var t = require("../types");
function CodeGenerator(ast, opts, code) { class CodeGenerator {
opts ||= {}; constructor(ast, opts, code) {
opts ||= {};
this.comments = ast.comments || []; this.comments = ast.comments || [];
this.tokens = ast.tokens || []; this.tokens = ast.tokens || [];
this.format = CodeGenerator.normalizeOptions(code, opts); this.format = CodeGenerator.normalizeOptions(code, opts);
this.opts = opts; this.opts = opts;
this.ast = ast; this.ast = ast;
this.whitespace = new Whitespace(this.tokens, this.comments, this.format); this.whitespace = new Whitespace(this.tokens, this.comments, this.format);
this.position = new Position; this.position = new Position;
this.map = new SourceMap(this.position, opts, code); this.map = new SourceMap(this.position, opts, code);
this.buffer = new Buffer(this.position, this.format); this.buffer = new Buffer(this.position, this.format);
}
static normalizeOptions(code, opts) {
var style = " ";
if (code) {
var indent = detectIndent(code).indent;
if (indent && indent !== " ") style = indent;
}
var format = {
comments: opts.comments == null || opts.comments,
compact: opts.compact,
indent: {
adjustMultilineComment: true,
style: style,
base: 0
}
};
if (format.compact === "auto") {
format.compact = code.length > 100000; // 100KB
if (format.compact) {
console.error(messages.get("codeGeneratorDeopt", opts.filename, "100KB"));
}
}
return format;
}
static generators = {
templateLiterals: require("./generators/template-literals"),
comprehensions: require("./generators/comprehensions"),
expressions: require("./generators/expressions"),
statements: require("./generators/statements"),
playground: require("./generators/playground"),
classes: require("./generators/classes"),
methods: require("./generators/methods"),
modules: require("./generators/modules"),
types: require("./generators/types"),
flow: require("./generators/flow"),
base: require("./generators/base"),
jsx: require("./generators/jsx")
};
generate() {
var ast = this.ast;
this.print(ast);
var comments = [];
each(ast.comments, function (comment) {
if (!comment._displayed) comments.push(comment);
});
this._printComments(comments);
return {
map: this.map.get(),
code: this.buffer.get()
};
}
buildPrint(parent) {
var print = (node, opts) => {
return this.print(node, parent, opts);
};
print.sequence = (nodes, opts) => {
opts ||= {};
opts.statement = true;
return this.printJoin(print, nodes, opts);
};
print.join = (nodes, opts) => {
return this.printJoin(print, nodes, opts);
};
print.list = function (items, opts) {
opts ||= {};
opts.separator ||= ", ";
print.join(items, opts);
};
print.block = (node) => {
return this.printBlock(print, node);
};
print.indentOnComments = (node) => {
return this.printAndIndentOnComments(print, node);
};
return print;
}
print(node, parent, opts) {
if (!node) return "";
if (parent && parent._compact) {
node._compact = true;
}
var oldConcise = this.format.concise;
if (node._compact) {
this.format.concise = true;
}
opts ||= {};
var newline = (leading) => {
if (!opts.statement && !n.isUserWhitespacable(node, parent)) {
return;
}
var lines = 0;
if (node.start != null && !node._ignoreUserWhitespace) {
// user node
if (leading) {
lines = this.whitespace.getNewlinesBefore(node);
} else {
lines = this.whitespace.getNewlinesAfter(node);
}
} else {
// generated node
if (!leading) lines++; // always include at least a single line after
if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
var needs = n.needsWhitespaceAfter;
if (leading) needs = n.needsWhitespaceBefore;
if (needs(node, parent)) lines++;
// generated nodes can't add starting file whitespace
if (!this.buffer.buf) lines = 0;
}
this.newline(lines);
};
if (this[node.type]) {
var needsNoLineTermParens = n.needsParensNoLineTerminator(node, parent);
var needsParens = needsNoLineTermParens || n.needsParens(node, parent);
if (needsParens) this.push("(");
if (needsNoLineTermParens) this.indent();
this.printLeadingComments(node, parent);
newline(true);
if (opts.before) opts.before();
this.map.mark(node, "start");
this[node.type](node, this.buildPrint(node), parent);
if (needsNoLineTermParens) {
this.newline();
this.dedent();
}
if (needsParens) this.push(")");
this.map.mark(node, "end");
if (opts.after) opts.after();
newline(false);
this.printTrailingComments(node, parent);
} else {
throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name));
}
this.format.concise = oldConcise;
}
printJoin(print, nodes, opts) {
if (!nodes || !nodes.length) return;
opts ||= {};
var len = nodes.length;
if (opts.indent) this.indent();
each(nodes, (node, i) => {
print(node, {
statement: opts.statement,
addNewlines: opts.addNewlines,
after: () => {
if (opts.iterator) {
opts.iterator(node, i);
}
if (opts.separator && i < len - 1) {
this.push(opts.separator);
}
}
});
});
if (opts.indent) this.dedent();
}
printAndIndentOnComments(print, node) {
var indent = !!node.leadingComments;
if (indent) this.indent();
print(node);
if (indent) this.dedent();
}
printBlock(print, node) {
if (t.isEmptyStatement(node)) {
this.semicolon();
} else {
this.push(" ");
print(node);
}
}
generateComment(comment) {
var val = comment.value;
if (comment.type === "Line") {
val = "//" + val;
} else {
val = "/*" + val + "*/";
}
return val;
}
printTrailingComments(node, parent) {
this._printComments(this.getComments("trailingComments", node, parent));
}
printLeadingComments(node, parent) {
this._printComments(this.getComments("leadingComments", node, parent));
}
getComments(key, node, parent) {
if (t.isExpressionStatement(parent)) {
return [];
}
var comments = [];
var nodes = [node];
if (t.isExpressionStatement(node)) {
nodes.push(node.argument);
}
each(nodes, (node) => {
comments = comments.concat(this._getComments(key, node));
});
return comments;
}
_getComments(key, node) {
return (node && node[key]) || [];
}
_printComments(comments) {
if (this.format.compact) return;
if (!this.format.comments) return;
if (!comments || !comments.length) return;
each(comments, (comment) => {
var skip = false;
// find the original comment in the ast and set it as displayed
each(this.ast.comments, function (origComment) {
if (origComment.start === comment.start) {
// comment has already been output
if (origComment._displayed) skip = true;
origComment._displayed = true;
return false;
}
});
if (skip) return;
// whitespace before
this.newline(this.whitespace.getNewlinesBefore(comment));
var column = this.position.column;
var val = this.generateComment(comment);
if (column && !this.isLast(["\n", " ", "[", "{"])) {
this._push(" ");
column++;
}
//
if (comment.type === "Block" && this.format.indent.adjustMultilineComment) {
var offset = comment.loc.start.column;
if (offset) {
var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
val = val.replace(newlineRegex, "\n");
}
var indent = Math.max(this.indentSize(), column);
val = val.replace(/\n/g, "\n" + repeating(" ", indent));
}
if (column === 0) {
val = this.getIndent() + val;
}
//
this._push(val);
// whitespace after
this.newline(this.whitespace.getNewlinesAfter(comment));
});
}
} }
each(Buffer.prototype, function (fn, key) { each(Buffer.prototype, function (fn, key) {
@ -38,321 +348,13 @@ each(Buffer.prototype, function (fn, key) {
}; };
}); });
CodeGenerator.normalizeOptions = function (code, opts) {
var style = " ";
if (code) {
var indent = detectIndent(code).indent;
if (indent && indent !== " ") style = indent;
}
var format = {
comments: opts.comments == null || opts.comments,
compact: opts.compact,
indent: {
adjustMultilineComment: true,
style: style,
base: 0
}
};
if (format.compact === "auto") {
format.compact = code.length > 100000; // 100KB
if (format.compact) {
console.error(messages.get("codeGeneratorDeopt", opts.filename, "100KB"));
}
}
return format;
};
CodeGenerator.generators = {
templateLiterals: require("./generators/template-literals"),
comprehensions: require("./generators/comprehensions"),
expressions: require("./generators/expressions"),
statements: require("./generators/statements"),
playground: require("./generators/playground"),
classes: require("./generators/classes"),
methods: require("./generators/methods"),
modules: require("./generators/modules"),
types: require("./generators/types"),
flow: require("./generators/flow"),
base: require("./generators/base"),
jsx: require("./generators/jsx")
};
each(CodeGenerator.generators, function (generator) { each(CodeGenerator.generators, function (generator) {
extend(CodeGenerator.prototype, generator); extend(CodeGenerator.prototype, generator);
}); });
CodeGenerator.prototype.generate = function () { module.exports = function (ast, opts, code) {
var ast = this.ast; var gen = new CodeGenerator(ast, opts, code);
return gen.generate();
this.print(ast);
var comments = [];
each(ast.comments, function (comment) {
if (!comment._displayed) comments.push(comment);
});
this._printComments(comments);
return {
map: this.map.get(),
code: this.buffer.get()
};
}; };
CodeGenerator.prototype.buildPrint = function (parent) { module.exports.CodeGenerator = CodeGenerator;
var print = (node, opts) => {
return this.print(node, parent, opts);
};
print.sequence = (nodes, opts) => {
opts ||= {};
opts.statement = true;
return this.printJoin(print, nodes, opts);
};
print.join = (nodes, opts) => {
return this.printJoin(print, nodes, opts);
};
print.list = function (items, opts) {
opts ||= {};
opts.separator ||= ", ";
print.join(items, opts);
};
print.block = (node) => {
return this.printBlock(print, node);
};
print.indentOnComments = (node) => {
return this.printAndIndentOnComments(print, node);
};
return print;
};
CodeGenerator.prototype.print = function (node, parent, opts) {
if (!node) return "";
if (parent && parent._compact) {
node._compact = true;
}
var oldConcise = this.format.concise;
if (node._compact) {
this.format.concise = true;
}
opts ||= {};
var newline = (leading) => {
if (!opts.statement && !n.isUserWhitespacable(node, parent)) {
return;
}
var lines = 0;
if (node.start != null && !node._ignoreUserWhitespace) {
// user node
if (leading) {
lines = this.whitespace.getNewlinesBefore(node);
} else {
lines = this.whitespace.getNewlinesAfter(node);
}
} else {
// generated node
if (!leading) lines++; // always include at least a single line after
if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
var needs = n.needsWhitespaceAfter;
if (leading) needs = n.needsWhitespaceBefore;
if (needs(node, parent)) lines++;
// generated nodes can't add starting file whitespace
if (!this.buffer.buf) lines = 0;
}
this.newline(lines);
};
if (this[node.type]) {
var needsNoLineTermParens = n.needsParensNoLineTerminator(node, parent);
var needsParens = needsNoLineTermParens || n.needsParens(node, parent);
if (needsParens) this.push("(");
if (needsNoLineTermParens) this.indent();
this.printLeadingComments(node, parent);
newline(true);
if (opts.before) opts.before();
this.map.mark(node, "start");
this[node.type](node, this.buildPrint(node), parent);
if (needsNoLineTermParens) {
this.newline();
this.dedent();
}
if (needsParens) this.push(")");
this.map.mark(node, "end");
if (opts.after) opts.after();
newline(false);
this.printTrailingComments(node, parent);
} else {
throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name));
}
this.format.concise = oldConcise;
};
CodeGenerator.prototype.printJoin = function (print, nodes, opts) {
if (!nodes || !nodes.length) return;
opts ||= {};
var len = nodes.length;
if (opts.indent) this.indent();
each(nodes, (node, i) => {
print(node, {
statement: opts.statement,
addNewlines: opts.addNewlines,
after: () => {
if (opts.iterator) {
opts.iterator(node, i);
}
if (opts.separator && i < len - 1) {
this.push(opts.separator);
}
}
});
});
if (opts.indent) this.dedent();
};
CodeGenerator.prototype.printAndIndentOnComments = function (print, node) {
var indent = !!node.leadingComments;
if (indent) this.indent();
print(node);
if (indent) this.dedent();
};
CodeGenerator.prototype.printBlock = function (print, node) {
if (t.isEmptyStatement(node)) {
this.semicolon();
} else {
this.push(" ");
print(node);
}
};
CodeGenerator.prototype.generateComment = function (comment) {
var val = comment.value;
if (comment.type === "Line") {
val = "//" + val;
} else {
val = "/*" + val + "*/";
}
return val;
};
CodeGenerator.prototype.printTrailingComments = function (node, parent) {
this._printComments(this.getComments("trailingComments", node, parent));
};
CodeGenerator.prototype.printLeadingComments = function (node, parent) {
this._printComments(this.getComments("leadingComments", node, parent));
};
CodeGenerator.prototype.getComments = function (key, node, parent) {
if (t.isExpressionStatement(parent)) {
return [];
}
var comments = [];
var nodes = [node];
if (t.isExpressionStatement(node)) {
nodes.push(node.argument);
}
each(nodes, (node) => {
comments = comments.concat(this._getComments(key, node));
});
return comments;
};
CodeGenerator.prototype._getComments = function (key, node) {
return (node && node[key]) || [];
};
CodeGenerator.prototype._printComments = function (comments) {
if (this.format.compact) return;
if (!this.format.comments) return;
if (!comments || !comments.length) return;
each(comments, (comment) => {
var skip = false;
// find the original comment in the ast and set it as displayed
each(this.ast.comments, function (origComment) {
if (origComment.start === comment.start) {
// comment has already been output
if (origComment._displayed) skip = true;
origComment._displayed = true;
return false;
}
});
if (skip) return;
// whitespace before
this.newline(this.whitespace.getNewlinesBefore(comment));
var column = this.position.column;
var val = this.generateComment(comment);
if (column && !this.isLast(["\n", " ", "[", "{"])) {
this._push(" ");
column++;
}
//
if (comment.type === "Block" && this.format.indent.adjustMultilineComment) {
var offset = comment.loc.start.column;
if (offset) {
var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
val = val.replace(newlineRegex, "\n");
}
var indent = Math.max(this.indentSize(), column);
val = val.replace(/\n/g, "\n" + repeating(" ", indent));
}
if (column === 0) {
val = this.getIndent() + val;
}
//
this._push(val);
// whitespace after
this.newline(this.whitespace.getNewlinesAfter(comment));
});
};

View File

@ -1,5 +1,3 @@
module.exports = Node;
var whitespace = require("./whitespace"); var whitespace = require("./whitespace");
var parens = require("./parentheses"); var parens = require("./parentheses");
var each = require("lodash/collection/each"); var each = require("lodash/collection/each");
@ -24,79 +22,81 @@ var find = function (obj, node, parent) {
return result; return result;
}; };
function Node(node, parent) { export default class Node {
this.parent = parent; constructor(node, parent) {
this.node = node; this.parent = parent;
} this.node = node;
Node.isUserWhitespacable = function (node) {
return t.isUserWhitespacable(node);
};
Node.needsWhitespace = function (node, parent, type) {
if (!node) return 0;
if (t.isExpressionStatement(node)) {
node = node.expression;
} }
var linesInfo = find(whitespace.nodes, node, parent); static isUserWhitespacable(node) {
return t.isUserWhitespacable(node);
}
if (!linesInfo) { static needsWhitespace(node, parent, type) {
var items = find(whitespace.list, node, parent); if (!node) return 0;
if (items) {
for (var i = 0; i < items.length; i++) { if (t.isExpressionStatement(node)) {
linesInfo = Node.needsWhitespace(items[i], node, type); node = node.expression;
if (linesInfo) break; }
var linesInfo = find(whitespace.nodes, node, parent);
if (!linesInfo) {
var items = find(whitespace.list, node, parent);
if (items) {
for (var i = 0; i < items.length; i++) {
linesInfo = Node.needsWhitespace(items[i], node, type);
if (linesInfo) break;
}
} }
} }
return (linesInfo && linesInfo[type]) || 0;
} }
return (linesInfo && linesInfo[type]) || 0; static needsWhitespaceBefore(node, parent) {
}; return Node.needsWhitespace(node, parent, "before");
Node.needsWhitespaceBefore = function (node, parent) {
return Node.needsWhitespace(node, parent, "before");
};
Node.needsWhitespaceAfter = function (node, parent) {
return Node.needsWhitespace(node, parent, "after");
};
Node.needsParens = function (node, parent) {
if (!parent) return false;
if (t.isNewExpression(parent) && parent.callee === node) {
if (t.isCallExpression(node)) return true;
var hasCall = some(node, function (val) {
return t.isCallExpression(val);
});
if (hasCall) return true;
} }
return find(parens, node, parent); static needsWhitespaceAfter(node, parent) {
}; return Node.needsWhitespace(node, parent, "after");
}
Node.needsParensNoLineTerminator = function (node, parent) { static needsParens(node, parent) {
if (!parent) return false; if (!parent) return false;
if (t.isNewExpression(parent) && parent.callee === node) {
if (t.isCallExpression(node)) return true;
var hasCall = some(node, function (val) {
return t.isCallExpression(val);
});
if (hasCall) return true;
}
return find(parens, node, parent);
}
static needsParensNoLineTerminator(node, parent) {
if (!parent) return false;
// no comments
if (!node.leadingComments || !node.leadingComments.length) {
return false;
}
if (t.isYieldExpression(parent) || t.isAwaitExpression(parent)) {
return true;
}
if (t.isContinueStatement(parent) || t.isBreakStatement(parent) ||
t.isReturnStatement(parent) || t.isThrowStatement(parent)) {
return true;
}
// no comments
if (!node.leadingComments || !node.leadingComments.length) {
return false; return false;
} }
}
if (t.isYieldExpression(parent) || t.isAwaitExpression(parent)) {
return true;
}
if (t.isContinueStatement(parent) || t.isBreakStatement(parent) ||
t.isReturnStatement(parent) || t.isThrowStatement(parent)) {
return true;
}
return false;
};
each(Node, function (fn, key) { each(Node, function (fn, key) {
Node.prototype[key] = function () { Node.prototype[key] = function () {

View File

@ -1,27 +1,27 @@
module.exports = Position; export default class Position {
constructor() {
this.line = 1;
this.column = 0;
}
function Position() { push(str) {
this.line = 1; for (var i = 0; i < str.length; i++) {
this.column = 0; if (str[i] === "\n") {
this.line++;
this.column = 0;
} else {
this.column++;
}
}
}
unshift(str) {
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this.line--;
} else {
this.column--;
}
}
}
} }
Position.prototype.push = function (str) {
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this.line++;
this.column = 0;
} else {
this.column++;
}
}
};
Position.prototype.unshift = function (str) {
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this.line--;
} else {
this.column--;
}
}
};

View File

@ -1,54 +1,54 @@
module.exports = SourceMap;
var sourceMap = require("source-map"); var sourceMap = require("source-map");
var t = require("../types"); var t = require("../types");
function SourceMap(position, opts, code) { export default class SourceMap {
this.position = position; constructor(position, opts, code) {
this.opts = opts; this.position = position;
this.opts = opts;
if (opts.sourceMap) { if (opts.sourceMap) {
this.map = new sourceMap.SourceMapGenerator({ this.map = new sourceMap.SourceMapGenerator({
file: opts.sourceMapName, file: opts.sourceMapName,
sourceRoot: opts.sourceRoot sourceRoot: opts.sourceRoot
});
this.map.setSourceContent(opts.sourceFileName, code);
} else {
this.map = null;
}
}
get() {
var map = this.map;
if (map) {
return map.toJSON();
} else {
return map;
}
}
mark(node, type) {
var loc = node.loc;
if (!loc) return; // no location info
var map = this.map;
if (!map) return; // no source map
if (t.isProgram(node) || t.isFile(node)) return; // illegal mapping nodes
var position = this.position;
var generated = {
line: position.line,
column: position.column
};
var original = loc[type];
map.addMapping({
source: this.opts.sourceFileName,
generated: generated,
original: original
}); });
this.map.setSourceContent(opts.sourceFileName, code);
} else {
this.map = null;
} }
} }
SourceMap.prototype.get = function () {
var map = this.map;
if (map) {
return map.toJSON();
} else {
return map;
}
};
SourceMap.prototype.mark = function (node, type) {
var loc = node.loc;
if (!loc) return; // no location info
var map = this.map;
if (!map) return; // no source map
if (t.isProgram(node) || t.isFile(node)) return; // illegal mapping nodes
var position = this.position;
var generated = {
line: position.line,
column: position.column
};
var original = loc[type];
map.addMapping({
source: this.opts.sourceFileName,
generated: generated,
original: original
});
};

View File

@ -1,5 +1,3 @@
module.exports = Whitespace;
var sortBy = require("lodash/collection/sortBy"); var sortBy = require("lodash/collection/sortBy");
/** /**
@ -22,92 +20,94 @@ function getLookupIndex(i, base, max) {
return i; return i;
} }
function Whitespace(tokens, comments) { export default class Whitespace {
this.tokens = sortBy(tokens.concat(comments), "start"); constructor(tokens, comments) {
this.used = {}; this.tokens = sortBy(tokens.concat(comments), "start");
this.used = {};
// Profiling this code shows that while generator passes over it, indexes // Profiling this code shows that while generator passes over it, indexes
// returned by `getNewlinesBefore` and `getNewlinesAfter` are always increasing. // returned by `getNewlinesBefore` and `getNewlinesAfter` are always increasing.
// We use this implementation detail for an optimization: instead of always // We use this implementation detail for an optimization: instead of always
// starting to look from `this.tokens[0]`, we will start `for` loops from the // starting to look from `this.tokens[0]`, we will start `for` loops from the
// previous successful match. We will enumerate all tokens—but the common // previous successful match. We will enumerate all tokens—but the common
// case will be much faster. // case will be much faster.
this._lastFoundIndex = 0; this._lastFoundIndex = 0;
}
Whitespace.prototype.getNewlinesBefore = function (node) {
var startToken;
var endToken;
var tokens = this.tokens;
var token;
for (var j = 0; j < tokens.length; j++) {
// optimize for forward traversal by shifting for loop index
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
token = tokens[i];
// this is the token this node starts with
if (node.start === token.start) {
startToken = tokens[i - 1];
endToken = token;
this._lastFoundIndex = i;
break;
}
} }
return this.getNewlinesBetween(startToken, endToken); getNewlinesBefore(node) {
}; var startToken;
var endToken;
var tokens = this.tokens;
var token;
Whitespace.prototype.getNewlinesAfter = function (node) { for (var j = 0; j < tokens.length; j++) {
var startToken; // optimize for forward traversal by shifting for loop index
var endToken; var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
var tokens = this.tokens; token = tokens[i];
var token;
for (var j = 0; j < tokens.length; j++) { // this is the token this node starts with
// optimize for forward traversal by shifting for loop index if (node.start === token.start) {
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length); startToken = tokens[i - 1];
token = tokens[i]; endToken = token;
// this is the token this node ends with this._lastFoundIndex = i;
if (node.end === token.end) { break;
startToken = token; }
endToken = tokens[i + 1];
this._lastFoundIndex = i;
break;
} }
return this.getNewlinesBetween(startToken, endToken);
} }
if (endToken && endToken.type.type === "eof") { getNewlinesAfter(node) {
return 1; var startToken;
} else { var endToken;
var lines = this.getNewlinesBetween(startToken, endToken); var tokens = this.tokens;
if (node.type === "Line" && !lines) { var token;
// line comment
for (var j = 0; j < tokens.length; j++) {
// optimize for forward traversal by shifting for loop index
var i = getLookupIndex(j, this._lastFoundIndex, this.tokens.length);
token = tokens[i];
// this is the token this node ends with
if (node.end === token.end) {
startToken = token;
endToken = tokens[i + 1];
this._lastFoundIndex = i;
break;
}
}
if (endToken && endToken.type.type === "eof") {
return 1; return 1;
} else { } else {
return lines; var lines = this.getNewlinesBetween(startToken, endToken);
} if (node.type === "Line" && !lines) {
} // line comment
}; return 1;
} else {
Whitespace.prototype.getNewlinesBetween = function (startToken, endToken) { return lines;
if (!endToken || !endToken.loc) return 0; }
var start = startToken ? startToken.loc.end.line : 1;
var end = endToken.loc.start.line;
var lines = 0;
for (var line = start; line < end; line++) {
if (typeof this.used[line] === "undefined") {
this.used[line] = true;
lines++;
} }
} }
return lines; getNewlinesBetween(startToken, endToken) {
}; if (!endToken || !endToken.loc) return 0;
var start = startToken ? startToken.loc.end.line : 1;
var end = endToken.loc.start.line;
var lines = 0;
for (var line = start; line < end; line++) {
if (typeof this.used[line] === "undefined") {
this.used[line] = true;
lines++;
}
}
return lines;
}
}

View File

@ -1,5 +1,3 @@
module.exports = File;
var sourceMapToComment = require("source-map-to-comment"); var sourceMapToComment = require("source-map-to-comment");
var shebangRegex = require("shebang-regex"); var shebangRegex = require("shebang-regex");
var isFunction = require("lodash/lang/isFunction"); var isFunction = require("lodash/lang/isFunction");
@ -16,409 +14,6 @@ var path = require("path");
var each = require("lodash/collection/each"); var each = require("lodash/collection/each");
var t = require("../types"); var t = require("../types");
function File(opts) {
this.dynamicImportedNoDefault = [];
this.dynamicImportIds = {};
this.dynamicImported = [];
this.dynamicImports = [];
this.usedHelpers = {};
this.dynamicData = {};
this.data = {};
this.lastStatements = [];
this.opts = this.normalizeOptions(opts);
this.ast = {};
this.buildTransformers();
}
File.helpers = [
"inherits",
"defaults",
"prototype-properties",
"apply-constructor",
"tagged-template-literal",
"tagged-template-literal-loose",
"interop-require",
"to-array",
"to-consumable-array",
"sliced-to-array",
"object-without-properties",
"has-own",
"slice",
"bind",
"define-property",
"async-to-generator",
"interop-require-wildcard",
"typeof",
"extends",
"get",
"set",
"class-call-check",
"object-destructuring-empty",
"temporal-undefined",
"temporal-assert-defined",
"self-global"
];
File.validOptions = [
"filename",
"filenameRelative",
"blacklist",
"whitelist",
"loose",
"optional",
"modules",
"sourceMap",
"sourceMapName",
"sourceFileName",
"sourceRoot",
"moduleRoot",
"moduleIds",
"comments",
"reactCompat",
"keepModuleIdExtensions",
"code",
"ast",
"playground",
"experimental",
"externalHelpers",
"auxiliaryComment",
"compact",
"returnUsedHelpers",
"resolveModuleSource",
"moduleId",
// legacy
"format",
// these are used by plugins
"ignore",
"only",
"extensions",
"accept"
];
File.prototype.normalizeOptions = function (opts) {
opts = assign({}, opts);
for (var key in opts) {
if (key[0] !== "_" && File.validOptions.indexOf(key) < 0) {
throw new ReferenceError("Unknown option: " + key);
}
}
defaults(opts, {
keepModuleIdExtensions: false,
resolveModuleSource: null,
returnUsedHelpers: false,
externalHelpers: false,
auxilaryComment: "",
experimental: false,
reactCompat: false,
playground: false,
moduleIds: false,
blacklist: [],
whitelist: [],
sourceMap: false,
optional: [],
comments: true,
filename: "unknown",
modules: "common",
compact: "auto",
loose: [],
code: true,
ast: true
});
// normalize windows path separators to unix
opts.filename = slash(opts.filename);
if (opts.sourceRoot) {
opts.sourceRoot = slash(opts.sourceRoot);
}
if (opts.moduleId) {
opts.moduleIds = true;
}
opts.basename = path.basename(opts.filename, path.extname(opts.filename));
opts.blacklist = util.arrayify(opts.blacklist);
opts.whitelist = util.arrayify(opts.whitelist);
opts.optional = util.arrayify(opts.optional);
opts.compact = util.booleanify(opts.compact);
opts.loose = util.arrayify(opts.loose);
if (includes(opts.loose, "all") || includes(opts.loose, true)) {
opts.loose = Object.keys(transform.transformers);
}
defaults(opts, {
moduleRoot: opts.sourceRoot
});
defaults(opts, {
sourceRoot: opts.moduleRoot
});
defaults(opts, {
filenameRelative: opts.filename
});
defaults(opts, {
sourceFileName: opts.filenameRelative,
sourceMapName: opts.filenameRelative
});
if (opts.playground) {
opts.experimental = true;
}
if (opts.externalHelpers) {
this.set("helpersNamespace", t.identifier("babelHelpers"));
}
opts.blacklist = transform._ensureTransformerNames("blacklist", opts.blacklist);
opts.whitelist = transform._ensureTransformerNames("whitelist", opts.whitelist);
opts.optional = transform._ensureTransformerNames("optional", opts.optional);
opts.loose = transform._ensureTransformerNames("loose", opts.loose);
if (opts.reactCompat) {
opts.optional.push("reactCompat");
console.error("The reactCompat option has been moved into the optional transformer `reactCompat`");
}
var ensureEnabled = function (key) {
var namespace = transform.transformerNamespaces[key];
if (namespace === "es7") opts.experimental = true;
if (namespace === "playground") opts.playground = true;
};
each(opts.whitelist, ensureEnabled);
each(opts.optional, ensureEnabled);
return opts;
};
File.prototype.isLoose = function (key) {
return includes(this.opts.loose, key);
};
File.prototype.buildTransformers = function () {
var file = this;
var transformers = {};
var secondaryStack = [];
var stack = [];
each(transform.transformers, function (transformer, key) {
var pass = transformers[key] = transformer.buildPass(file);
if (pass.canRun(file)) {
stack.push(pass);
if (transformer.secondPass) {
secondaryStack.push(pass);
}
if (transformer.manipulateOptions) {
transformer.manipulateOptions(file.opts, file);
}
}
});
this.transformerStack = stack.concat(secondaryStack);
this.transformers = transformers;
};
File.prototype.debug = function (msg) {
var parts = this.opts.filename;
if (msg) parts += ": " + msg;
util.debug(parts);
};
File.prototype.getModuleFormatter = function (type) {
var ModuleFormatter = isFunction(type) ? type : transform.moduleFormatters[type];
if (!ModuleFormatter) {
var loc = util.resolve(type);
if (loc) ModuleFormatter = require(loc);
}
if (!ModuleFormatter) {
throw new ReferenceError("Unknown module formatter type " + JSON.stringify(type));
}
return new ModuleFormatter(this);
};
File.prototype.parseShebang = function (code) {
var shebangMatch = shebangRegex.exec(code);
if (shebangMatch) {
this.shebang = shebangMatch[0];
// remove shebang
code = code.replace(shebangRegex, "");
}
return code;
};
File.prototype.set = function (key, val) {
return this.data[key] = val;
};
File.prototype.setDynamic = function (key, fn) {
this.dynamicData[key] = fn;
};
File.prototype.get = function (key) {
var data = this.data[key];
if (data) {
return data;
} else {
var dynamic = this.dynamicData[key];
if (dynamic) {
return this.set(key, dynamic());
}
}
};
File.prototype.addImport = function (source, name, noDefault) {
name ||= source;
var id = this.dynamicImportIds[name];
if (!id) {
id = this.dynamicImportIds[name] = this.scope.generateUidIdentifier(name);
var specifiers = [t.importSpecifier(t.identifier("default"), id)];
var declar = t.importDeclaration(specifiers, t.literal(source));
declar._blockHoist = 3;
this.dynamicImported.push(declar);
if (noDefault) this.dynamicImportedNoDefault.push(declar);
this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports);
}
return id;
};
File.prototype.isConsequenceExpressionStatement = function (node) {
return t.isExpressionStatement(node) && this.lastStatements.indexOf(node) >= 0;
};
File.prototype.attachAuxiliaryComment = function (node) {
var comment = this.opts.auxiliaryComment;
if (comment) {
node.leadingComments ||= [];
node.leadingComments.push({
type: "Line",
value: " " + comment
});
}
return node;
};
File.prototype.addHelper = function (name) {
if (!includes(File.helpers, name)) {
throw new ReferenceError("Unknown helper " + name);
}
var program = this.ast.program;
var declar = program._declarations && program._declarations[name];
if (declar) return declar.id;
this.usedHelpers[name] = true;
var runtime = this.get("helpersNamespace");
if (runtime) {
name = t.identifier(t.toIdentifier(name));
return t.memberExpression(runtime, name);
} else {
var ref = util.template(name);
ref._compact = true;
var uid = this.scope.generateUidIdentifier(name);
this.scope.push({
key: name,
id: uid,
init: ref
});
return uid;
}
};
File.prototype.logDeopt = function () {
// todo, (node, msg)
};
File.prototype.errorWithNode = function (node, msg, Error) {
Error ||= SyntaxError;
var loc = node.loc.start;
var err = new Error("Line " + loc.line + ": " + msg);
err.loc = loc;
return err;
};
File.prototype.addCode = function (code) {
code = (code || "") + "";
this.code = code;
return this.parseShebang(code);
};
File.prototype.parse = function (code) {
code = this.addCode(code);
var opts = this.opts;
opts.allowImportExportEverywhere = this.isLoose("es6.modules");
opts.strictMode = this.transformers.useStrict.canRun();
return parse(opts, code, (tree) => {
this.transform(tree);
return this.generate();
});
};
File.prototype.transform = function (ast) {
this.debug();
this.ast = ast;
this.lastStatements = t.getLastStatements(ast.program);
this.scope = new Scope(ast.program, ast, null, this);
var modFormatter = this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
if (modFormatter.init && this.transformers["es6.modules"].canRun()) {
modFormatter.init();
}
this.checkNode(ast);
this.call("pre");
each(this.transformerStack, function (pass) {
pass.transform();
});
this.call("post");
};
File.prototype.call = function (key) {
var stack = this.transformerStack;
for (var i = 0; i < stack.length; i++) {
var transformer = stack[i].transformer;
if (transformer[key]) {
transformer[key](this);
}
}
};
var checkTransformerVisitor = { var checkTransformerVisitor = {
enter(node, parent, scope, state) { enter(node, parent, scope, state) {
checkNode(state.stack, node, scope); checkNode(state.stack, node, scope);
@ -432,47 +27,452 @@ var checkNode = function (stack, node, scope) {
}); });
}; };
File.prototype.checkNode = function (node, scope) { export default class File {
var stack = this.transformerStack; constructor(opts) {
scope ||= this.scope; this.dynamicImportedNoDefault = [];
this.dynamicImportIds = {};
this.dynamicImported = [];
this.dynamicImports = [];
checkNode(stack, node, scope); this.usedHelpers = {};
this.dynamicData = {};
this.data = {};
scope.traverse(node, checkTransformerVisitor, { this.lastStatements = [];
stack: stack this.opts = this.normalizeOptions(opts);
}); this.ast = {};
};
File.prototype.generate = function () { this.buildTransformers();
var opts = this.opts; }
var ast = this.ast;
var result = { static helpers = [
code: "", "inherits",
map: null, "defaults",
ast: null "prototype-properties",
"apply-constructor",
"tagged-template-literal",
"tagged-template-literal-loose",
"interop-require",
"to-array",
"to-consumable-array",
"sliced-to-array",
"object-without-properties",
"has-own",
"slice",
"bind",
"define-property",
"async-to-generator",
"interop-require-wildcard",
"typeof",
"extends",
"get",
"set",
"class-call-check",
"object-destructuring-empty",
"temporal-undefined",
"temporal-assert-defined",
"self-global"
];
static validOptions = [
"filename",
"filenameRelative",
"blacklist",
"whitelist",
"loose",
"optional",
"modules",
"sourceMap",
"sourceMapName",
"sourceFileName",
"sourceRoot",
"moduleRoot",
"moduleIds",
"comments",
"reactCompat",
"keepModuleIdExtensions",
"code",
"ast",
"playground",
"experimental",
"externalHelpers",
"auxiliaryComment",
"compact",
"returnUsedHelpers",
"resolveModuleSource",
"moduleId",
// legacy
"format",
// these are used by plugins
"ignore",
"only",
"extensions",
"accept"
];
normalizeOptions(opts) {
opts = assign({}, opts);
for (var key in opts) {
if (key[0] !== "_" && File.validOptions.indexOf(key) < 0) {
throw new ReferenceError("Unknown option: " + key);
}
}
defaults(opts, {
keepModuleIdExtensions: false,
resolveModuleSource: null,
returnUsedHelpers: false,
externalHelpers: false,
auxilaryComment: "",
experimental: false,
reactCompat: false,
playground: false,
moduleIds: false,
blacklist: [],
whitelist: [],
sourceMap: false,
optional: [],
comments: true,
filename: "unknown",
modules: "common",
compact: "auto",
loose: [],
code: true,
ast: true
});
// normalize windows path separators to unix
opts.filename = slash(opts.filename);
if (opts.sourceRoot) {
opts.sourceRoot = slash(opts.sourceRoot);
}
if (opts.moduleId) {
opts.moduleIds = true;
}
opts.basename = path.basename(opts.filename, path.extname(opts.filename));
opts.blacklist = util.arrayify(opts.blacklist);
opts.whitelist = util.arrayify(opts.whitelist);
opts.optional = util.arrayify(opts.optional);
opts.compact = util.booleanify(opts.compact);
opts.loose = util.arrayify(opts.loose);
if (includes(opts.loose, "all") || includes(opts.loose, true)) {
opts.loose = Object.keys(transform.transformers);
}
defaults(opts, {
moduleRoot: opts.sourceRoot
});
defaults(opts, {
sourceRoot: opts.moduleRoot
});
defaults(opts, {
filenameRelative: opts.filename
});
defaults(opts, {
sourceFileName: opts.filenameRelative,
sourceMapName: opts.filenameRelative
});
if (opts.playground) {
opts.experimental = true;
}
if (opts.externalHelpers) {
this.set("helpersNamespace", t.identifier("babelHelpers"));
}
opts.blacklist = transform._ensureTransformerNames("blacklist", opts.blacklist);
opts.whitelist = transform._ensureTransformerNames("whitelist", opts.whitelist);
opts.optional = transform._ensureTransformerNames("optional", opts.optional);
opts.loose = transform._ensureTransformerNames("loose", opts.loose);
if (opts.reactCompat) {
opts.optional.push("reactCompat");
console.error("The reactCompat option has been moved into the optional transformer `reactCompat`");
}
var ensureEnabled = function (key) {
var namespace = transform.transformerNamespaces[key];
if (namespace === "es7") opts.experimental = true;
if (namespace === "playground") opts.playground = true;
};
each(opts.whitelist, ensureEnabled);
each(opts.optional, ensureEnabled);
return opts;
}; };
if (this.opts.returnUsedHelpers) { isLoose(key) {
result.usedHelpers = Object.keys(this.usedHelpers); return includes(this.opts.loose, key);
} }
if (opts.ast) result.ast = ast; buildTransformers() {
if (!opts.code) return result; var file = this;
var _result = generate(ast, opts, this.code); var transformers = {};
result.code = _result.code;
result.map = _result.map;
if (this.shebang) { var secondaryStack = [];
// add back shebang var stack = [];
result.code = this.shebang + "\n" + result.code;
each(transform.transformers, function (transformer, key) {
var pass = transformers[key] = transformer.buildPass(file);
if (pass.canRun(file)) {
stack.push(pass);
if (transformer.secondPass) {
secondaryStack.push(pass);
}
if (transformer.manipulateOptions) {
transformer.manipulateOptions(file.opts, file);
}
}
});
this.transformerStack = stack.concat(secondaryStack);
this.transformers = transformers;
} }
if (opts.sourceMap === "inline") { debug(msg) {
result.code += "\n" + sourceMapToComment(result.map); var parts = this.opts.filename;
result.map = null; if (msg) parts += ": " + msg;
util.debug(parts);
} }
return result; getModuleFormatter(type) {
}; var ModuleFormatter = isFunction(type) ? type : transform.moduleFormatters[type];
if (!ModuleFormatter) {
var loc = util.resolve(type);
if (loc) ModuleFormatter = require(loc);
}
if (!ModuleFormatter) {
throw new ReferenceError("Unknown module formatter type " + JSON.stringify(type));
}
return new ModuleFormatter(this);
}
parseShebang(code) {
var shebangMatch = shebangRegex.exec(code);
if (shebangMatch) {
this.shebang = shebangMatch[0];
// remove shebang
code = code.replace(shebangRegex, "");
}
return code;
}
set(key, val) {
return this.data[key] = val;
};
setDynamic(key, fn) {
this.dynamicData[key] = fn;
}
get(key) {
var data = this.data[key];
if (data) {
return data;
} else {
var dynamic = this.dynamicData[key];
if (dynamic) {
return this.set(key, dynamic());
}
}
}
addImport(source, name, noDefault) {
name ||= source;
var id = this.dynamicImportIds[name];
if (!id) {
id = this.dynamicImportIds[name] = this.scope.generateUidIdentifier(name);
var specifiers = [t.importSpecifier(t.identifier("default"), id)];
var declar = t.importDeclaration(specifiers, t.literal(source));
declar._blockHoist = 3;
this.dynamicImported.push(declar);
if (noDefault) this.dynamicImportedNoDefault.push(declar);
this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports);
}
return id;
}
isConsequenceExpressionStatement(node) {
return t.isExpressionStatement(node) && this.lastStatements.indexOf(node) >= 0;
}
attachAuxiliaryComment(node) {
var comment = this.opts.auxiliaryComment;
if (comment) {
node.leadingComments ||= [];
node.leadingComments.push({
type: "Line",
value: " " + comment
});
}
return node;
}
addHelper(name) {
if (!includes(File.helpers, name)) {
throw new ReferenceError("Unknown helper " + name);
}
var program = this.ast.program;
var declar = program._declarations && program._declarations[name];
if (declar) return declar.id;
this.usedHelpers[name] = true;
var runtime = this.get("helpersNamespace");
if (runtime) {
name = t.identifier(t.toIdentifier(name));
return t.memberExpression(runtime, name);
} else {
var ref = util.template(name);
ref._compact = true;
var uid = this.scope.generateUidIdentifier(name);
this.scope.push({
key: name,
id: uid,
init: ref
});
return uid;
}
}
logDeopt() {
// todo, (node, msg)
}
errorWithNode(node, msg, Error) {
Error ||= SyntaxError;
var loc = node.loc.start;
var err = new Error("Line " + loc.line + ": " + msg);
err.loc = loc;
return err;
}
addCode(code) {
code = (code || "") + "";
this.code = code;
return this.parseShebang(code);
}
parse(code) {
code = this.addCode(code);
var opts = this.opts;
opts.allowImportExportEverywhere = this.isLoose("es6.modules");
opts.strictMode = this.transformers.useStrict.canRun();
return parse(opts, code, (tree) => {
this.transform(tree);
return this.generate();
});
}
transform(ast) {
this.debug();
this.ast = ast;
this.lastStatements = t.getLastStatements(ast.program);
this.scope = new Scope(ast.program, ast, null, this);
var modFormatter = this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
if (modFormatter.init && this.transformers["es6.modules"].canRun()) {
modFormatter.init();
}
this.checkNode(ast);
this.call("pre");
each(this.transformerStack, function (pass) {
pass.transform();
});
this.call("post");
}
call(key) {
var stack = this.transformerStack;
for (var i = 0; i < stack.length; i++) {
var transformer = stack[i].transformer;
if (transformer[key]) {
transformer[key](this);
}
}
}
checkNode(node, scope) {
var stack = this.transformerStack;
scope ||= this.scope;
checkNode(stack, node, scope);
scope.traverse(node, checkTransformerVisitor, {
stack: stack
});
}
generate() {
var opts = this.opts;
var ast = this.ast;
var result = {
code: "",
map: null,
ast: null
};
if (this.opts.returnUsedHelpers) {
result.usedHelpers = Object.keys(this.usedHelpers);
}
if (opts.ast) result.ast = ast;
if (!opts.code) return result;
var _result = generate(ast, opts, this.code);
result.code = _result.code;
result.map = _result.map;
if (this.shebang) {
// add back shebang
result.code = this.shebang + "\n" + result.code;
}
if (opts.sourceMap === "inline") {
result.code += "\n" + sourceMapToComment(result.map);
result.map = null;
}
return result;
}
}

View File

@ -3,94 +3,16 @@ module.exports = ReplaceSupers;
var messages = require("../../messages"); var messages = require("../../messages");
var t = require("../../types"); var t = require("../../types");
/**
* Description
*
* @param {Object} opts
* @param {Boolean} [inClass]
*/
function ReplaceSupers(opts, inClass) { var isIllegalBareSuper = function (node, parent) {
this.topLevelThisReference = opts.topLevelThisReference; if (!isSuper(node, parent)) return false;
this.methodNode = opts.methodNode; if (t.isMemberExpression(parent, { computed: false })) return false;
this.className = opts.className; if (t.isCallExpression(parent, { callee: node })) return false;
this.superName = opts.superName; return true;
this.isStatic = opts.isStatic;
this.hasSuper = false;
this.inClass = inClass;
this.isLoose = opts.isLoose;
this.scope = opts.scope;
this.file = opts.file;
}
/**
* Sets a super class value of the named property.
*
* @example
*
* _set(Object.getPrototypeOf(CLASS.prototype), "METHOD", "VALUE", this)
*
* @param {Node} property
* @param {Node} value
* @param {Boolean} isComputed
* @param {Node} thisExpression
*
* @returns {Node}
*/
ReplaceSupers.prototype.setSuperProperty = function (property, value, isComputed, thisExpression) {
return t.callExpression(
this.file.addHelper("set"),
[
t.callExpression(
t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
[
this.isStatic ? this.className : t.memberExpression(this.className, t.identifier("prototype"))
]
),
isComputed ? property : t.literal(property.name),
value,
thisExpression
]
);
}; };
/** var isSuper = function (node, parent) {
* Gets a node representing the super class value of the named property. return t.isIdentifier(node, { name: "super" }) && t.isReferenced(node, parent);
*
* @example
*
* _get(Object.getPrototypeOf(CLASS.prototype), "METHOD", this)
*
* @param {Node} property
* @param {Boolean} isComputed
* @param {Node} thisExpression
*
* @returns {Node}
*/
ReplaceSupers.prototype.getSuperProperty = function (property, isComputed, thisExpression) {
return t.callExpression(
this.file.addHelper("get"),
[
t.callExpression(
t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
[
this.isStatic ? this.className : t.memberExpression(this.className, t.identifier("prototype"))
]
),
isComputed ? property : t.literal(property.name),
thisExpression
]
);
};
/**
* Description
*/
ReplaceSupers.prototype.replace = function () {
this.traverseLevel(this.methodNode.value, true);
}; };
var visitor = { var visitor = {
@ -121,181 +43,263 @@ var visitor = {
} }
}; };
/** export default class ReplaceSupers {
* Description
*
* @param {Object} node
* @param {Boolean} topLevel
*/
ReplaceSupers.prototype.traverseLevel = function (node, topLevel) { /**
var state = { self: this, topLevel: topLevel }; * Description
this.scope.traverse(node, visitor, state); *
}; * @param {Object} opts
* @param {Boolean} [inClass]
*/
/** constructor(opts, inClass) {
* Description this.topLevelThisReference = opts.topLevelThisReference;
*/ this.methodNode = opts.methodNode;
this.className = opts.className;
ReplaceSupers.prototype.getThisReference = function () { this.superName = opts.superName;
if (this.topLevelThisReference) { this.isStatic = opts.isStatic;
return this.topLevelThisReference; this.hasSuper = false;
} else { this.inClass = inClass;
var ref = this.topLevelThisReference = this.scope.generateUidIdentifier("this"); this.isLoose = opts.isLoose;
this.methodNode.value.body.body.unshift(t.variableDeclaration("var", [ this.scope = opts.scope;
t.variableDeclarator(this.topLevelThisReference, t.thisExpression()) this.file = opts.file;
]));
return ref;
} }
};
/** /**
* Description * Sets a super class value of the named property.
* *
* @param {Object} node * @example
* @param {Object} id *
* @param {Object} parent * _set(Object.getPrototypeOf(CLASS.prototype), "METHOD", "VALUE", this)
* @returns {Object} *
*/ * @param {Node} property
* @param {Node} value
* @param {Boolean} isComputed
* @param {Node} thisExpression
*
* @returns {Node}
*/
ReplaceSupers.prototype.getLooseSuperProperty = function (id, parent) { setSuperProperty(property, value, isComputed, thisExpression) {
var methodNode = this.methodNode; return t.callExpression(
var methodName = methodNode.key; this.file.addHelper("set"),
var superName = this.superName || t.identifier("Function"); [
t.callExpression(
t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
[
this.isStatic ? this.className : t.memberExpression(this.className, t.identifier("prototype"))
]
),
isComputed ? property : t.literal(property.name),
value,
thisExpression
]
);
}
if (parent.property === id) { /**
return; * Gets a node representing the super class value of the named property.
} else if (t.isCallExpression(parent, { callee: id })) { *
// super(); -> ClassName.prototype.MethodName.call(this); * @example
parent.arguments.unshift(t.thisExpression()); *
* _get(Object.getPrototypeOf(CLASS.prototype), "METHOD", this)
*
* @param {Node} property
* @param {Boolean} isComputed
* @param {Node} thisExpression
*
* @returns {Node}
*/
if (methodName.name === "constructor") { getSuperProperty(property, isComputed, thisExpression) {
// constructor() { super(); } return t.callExpression(
return t.memberExpression(superName, t.identifier("call")); this.file.addHelper("get"),
[
t.callExpression(
t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
[
this.isStatic ? this.className : t.memberExpression(this.className, t.identifier("prototype"))
]
),
isComputed ? property : t.literal(property.name),
thisExpression
]
);
}
/**
* Description
*/
replace() {
this.traverseLevel(this.methodNode.value, true);
}
/**
* Description
*
* @param {Object} node
* @param {Boolean} topLevel
*/
traverseLevel(node, topLevel) {
var state = { self: this, topLevel: topLevel };
this.scope.traverse(node, visitor, state);
}
/**
* Description
*/
getThisReference() {
if (this.topLevelThisReference) {
return this.topLevelThisReference;
} else { } else {
id = superName; var ref = this.topLevelThisReference = this.scope.generateUidIdentifier("this");
this.methodNode.value.body.body.unshift(t.variableDeclaration("var", [
// foo() { super(); } t.variableDeclarator(this.topLevelThisReference, t.thisExpression())
if (!methodNode.static) { ]));
id = t.memberExpression(id, t.identifier("prototype")); return ref;
}
id = t.memberExpression(id, methodName, methodNode.computed);
return t.memberExpression(id, t.identifier("call"));
} }
} else if (t.isMemberExpression(parent) && !methodNode.static) {
// super.test -> ClassName.prototype.test
return t.memberExpression(superName, t.identifier("prototype"));
} else {
return superName;
}
};
/**
* Description
*
* @param {Function} getThisReference
* @param {Object} node
* @param {Object} parent
*/
ReplaceSupers.prototype.looseHandle = function (getThisReference, node, parent) {
if (t.isIdentifier(node, { name: "super" })) {
this.hasSuper = true;
return this.getLooseSuperProperty(node, parent);
} else if (t.isCallExpression(node)) {
var callee = node.callee;
if (!t.isMemberExpression(callee)) return;
if (callee.object.name !== "super") return;
// super.test(); -> ClassName.prototype.MethodName.call(this);
this.hasSuper = true;
t.appendToMemberExpression(callee, t.identifier("call"));
node.arguments.unshift(getThisReference());
}
};
/**
* Description
*
* @param {Function} getThisReference
* @param {Object} node
* @param {Object} parent
*/
ReplaceSupers.prototype.specHandle = function (getThisReference, node, parent) {
var methodNode = this.methodNode;
var property;
var computed;
var args;
var thisReference;
if (isIllegalBareSuper(node, parent)) {
throw this.file.errorWithNode(node, messages.get("classesIllegalBareSuper"));
} }
if (t.isCallExpression(node)) { /**
var callee = node.callee; * Description
if (isSuper(callee, node)) { *
// super(); -> _get(Object.getPrototypeOf(ClassName), "MethodName", this).call(this); * @param {Object} node
property = methodNode.key; * @param {Object} id
computed = methodNode.computed; * @param {Object} parent
args = node.arguments; * @returns {Object}
*/
// bare `super` call is illegal inside non-constructors getLooseSuperProperty(id, parent) {
// - https://esdiscuss.org/topic/super-call-in-methods var methodNode = this.methodNode;
// - https://twitter.com/wycats/status/544553184396836864 var methodName = methodNode.key;
if (methodNode.key.name !== "constructor" || !this.inClass) { var superName = this.superName || t.identifier("Function");
var methodName = methodNode.key.name || "METHOD_NAME";
throw this.file.errorWithNode(node, messages.get("classesIllegalSuperCall", methodName)); if (parent.property === id) {
return;
} else if (t.isCallExpression(parent, { callee: id })) {
// super(); -> ClassName.prototype.MethodName.call(this);
parent.arguments.unshift(t.thisExpression());
if (methodName.name === "constructor") {
// constructor() { super(); }
return t.memberExpression(superName, t.identifier("call"));
} else {
id = superName;
// foo() { super(); }
if (!methodNode.static) {
id = t.memberExpression(id, t.identifier("prototype"));
}
id = t.memberExpression(id, methodName, methodNode.computed);
return t.memberExpression(id, t.identifier("call"));
} }
} else if (t.isMemberExpression(callee) && isSuper(callee.object, callee)) { } else if (t.isMemberExpression(parent) && !methodNode.static) {
// super.test(); -> _get(Object.getPrototypeOf(ClassName.prototype), "test", this).call(this); // super.test -> ClassName.prototype.test
property = callee.property; return t.memberExpression(superName, t.identifier("prototype"));
computed = callee.computed;
args = node.arguments;
}
} else if (t.isMemberExpression(node) && isSuper(node.object, node)) {
// super.name; -> _get(Object.getPrototypeOf(ClassName.prototype), "name", this);
property = node.property;
computed = node.computed;
} else if (t.isAssignmentExpression(node) && isSuper(node.left.object, node.left) && methodNode.kind === "set") {
// super.name = "val"; -> _set(Object.getPrototypeOf(ClassName.prototype), "name", this);
this.hasSuper = true;
return this.setSuperProperty(node.left.property, node.right, node.left.computed, getThisReference());
}
if (!property) return;
this.hasSuper = true;
thisReference = getThisReference();
var superProperty = this.getSuperProperty(property, computed, thisReference);
if (args) {
if (args.length === 1 && t.isSpreadElement(args[0])) {
// super(...arguments);
return t.callExpression(
t.memberExpression(superProperty, t.identifier("apply")),
[thisReference, args[0].argument]
);
} else { } else {
return t.callExpression( return superName;
t.memberExpression(superProperty, t.identifier("call")),
[thisReference].concat(args)
);
} }
} else {
return superProperty;
} }
};
var isIllegalBareSuper = function (node, parent) { /**
if (!isSuper(node, parent)) return false; * Description
if (t.isMemberExpression(parent, { computed: false })) return false; *
if (t.isCallExpression(parent, { callee: node })) return false; * @param {Function} getThisReference
return true; * @param {Object} node
}; * @param {Object} parent
*/
var isSuper = function (node, parent) { looseHandle(getThisReference, node, parent) {
return t.isIdentifier(node, { name: "super" }) && t.isReferenced(node, parent); if (t.isIdentifier(node, { name: "super" })) {
}; this.hasSuper = true;
return this.getLooseSuperProperty(node, parent);
} else if (t.isCallExpression(node)) {
var callee = node.callee;
if (!t.isMemberExpression(callee)) return;
if (callee.object.name !== "super") return;
// super.test(); -> ClassName.prototype.MethodName.call(this);
this.hasSuper = true;
t.appendToMemberExpression(callee, t.identifier("call"));
node.arguments.unshift(getThisReference());
}
}
/**
* Description
*
* @param {Function} getThisReference
* @param {Object} node
* @param {Object} parent
*/
specHandle(getThisReference, node, parent) {
var methodNode = this.methodNode;
var property;
var computed;
var args;
var thisReference;
if (isIllegalBareSuper(node, parent)) {
throw this.file.errorWithNode(node, messages.get("classesIllegalBareSuper"));
}
if (t.isCallExpression(node)) {
var callee = node.callee;
if (isSuper(callee, node)) {
// super(); -> _get(Object.getPrototypeOf(ClassName), "MethodName", this).call(this);
property = methodNode.key;
computed = methodNode.computed;
args = node.arguments;
// bare `super` call is illegal inside non-constructors
// - https://esdiscuss.org/topic/super-call-in-methods
// - https://twitter.com/wycats/status/544553184396836864
if (methodNode.key.name !== "constructor" || !this.inClass) {
var methodName = methodNode.key.name || "METHOD_NAME";
throw this.file.errorWithNode(node, messages.get("classesIllegalSuperCall", methodName));
}
} else if (t.isMemberExpression(callee) && isSuper(callee.object, callee)) {
// super.test(); -> _get(Object.getPrototypeOf(ClassName.prototype), "test", this).call(this);
property = callee.property;
computed = callee.computed;
args = node.arguments;
}
} else if (t.isMemberExpression(node) && isSuper(node.object, node)) {
// super.name; -> _get(Object.getPrototypeOf(ClassName.prototype), "name", this);
property = node.property;
computed = node.computed;
} else if (t.isAssignmentExpression(node) && isSuper(node.left.object, node.left) && methodNode.kind === "set") {
// super.name = "val"; -> _set(Object.getPrototypeOf(ClassName.prototype), "name", this);
this.hasSuper = true;
return this.setSuperProperty(node.left.property, node.right, node.left.computed, getThisReference());
}
if (!property) return;
this.hasSuper = true;
thisReference = getThisReference();
var superProperty = this.getSuperProperty(property, computed, thisReference);
if (args) {
if (args.length === 1 && t.isSpreadElement(args[0])) {
// super(...arguments);
return t.callExpression(
t.memberExpression(superProperty, t.identifier("apply")),
[thisReference, args[0].argument]
);
} else {
return t.callExpression(
t.memberExpression(superProperty, t.identifier("call")),
[thisReference].concat(args)
);
}
} else {
return superProperty;
}
}
}

View File

@ -1,5 +1,3 @@
module.exports = TransformerPass;
var includes = require("lodash/collection/includes"); var includes = require("lodash/collection/includes");
/** /**
@ -7,57 +5,59 @@ var includes = require("lodash/collection/includes");
* AST and running it's parent transformers handlers over it. * AST and running it's parent transformers handlers over it.
*/ */
function TransformerPass(file, transformer) { export default class TransformerPass {
this.transformer = transformer; constructor(file, transformer) {
this.shouldRun = !transformer.check; this.transformer = transformer;
this.handlers = transformer.handlers; this.shouldRun = !transformer.check;
this.file = file; this.handlers = transformer.handlers;
} this.file = file;
}
TransformerPass.prototype.canRun = function () { canRun() {
var transformer = this.transformer; var transformer = this.transformer;
var opts = this.file.opts; var opts = this.file.opts;
var key = transformer.key; var key = transformer.key;
// internal // internal
if (key[0] === "_") return true; if (key[0] === "_") return true;
// blacklist // blacklist
var blacklist = opts.blacklist; var blacklist = opts.blacklist;
if (blacklist.length && includes(blacklist, key)) return false; if (blacklist.length && includes(blacklist, key)) return false;
// whitelist // whitelist
var whitelist = opts.whitelist; var whitelist = opts.whitelist;
if (whitelist.length) return includes(whitelist, key); if (whitelist.length) return includes(whitelist, key);
// optional // optional
if (transformer.optional && !includes(opts.optional, key)) return false; if (transformer.optional && !includes(opts.optional, key)) return false;
// experimental // experimental
if (transformer.experimental && !opts.experimental) return false; if (transformer.experimental && !opts.experimental) return false;
// playground // playground
if (transformer.playground && !opts.playground) return false; if (transformer.playground && !opts.playground) return false;
return true;
};
TransformerPass.prototype.checkNode = function (node) {
var check = this.transformer.check;
if (check) {
return this.shouldRun = check(node);
} else {
return true; return true;
} }
};
TransformerPass.prototype.transform = function () { checkNode(node) {
if (!this.shouldRun) return; var check = this.transformer.check;
if (check) {
return this.shouldRun = check(node);
} else {
return true;
}
}
var file = this.file; transform() {
if (!this.shouldRun) return;
file.debug("Running transformer " + this.transformer.key); var file = this.file;
file.scope.traverse(file.ast, this.handlers, file); file.debug("Running transformer " + this.transformer.key);
};
file.scope.traverse(file.ast, this.handlers, file);
}
}

View File

@ -1,5 +1,3 @@
module.exports = Transformer;
var TransformerPass = require("./transformer-pass"); var TransformerPass = require("./transformer-pass");
var isFunction = require("lodash/lang/isFunction"); var isFunction = require("lodash/lang/isFunction");
var traverse = require("../traversal"); var traverse = require("../traversal");
@ -13,59 +11,61 @@ var each = require("lodash/collection/each");
* actually running the transformer over the provided `File`. * actually running the transformer over the provided `File`.
*/ */
function Transformer(key, transformer, opts) { export default class Transformer {
transformer = assign({}, transformer); constructor(key, transformer, opts) {
transformer = assign({}, transformer);
var take = function (key) { var take = function (key) {
var val = transformer[key]; var val = transformer[key];
delete transformer[key]; delete transformer[key];
return val; return val;
}; };
this.manipulateOptions = take("manipulateOptions"); this.manipulateOptions = take("manipulateOptions");
this.check = take("check"); this.check = take("check");
this.post = take("post"); this.post = take("post");
this.pre = take("pre"); this.pre = take("pre");
this.experimental = !!take("experimental"); this.experimental = !!take("experimental");
this.playground = !!take("playground"); this.playground = !!take("playground");
this.secondPass = !!take("secondPass"); this.secondPass = !!take("secondPass");
this.optional = !!take("optional"); this.optional = !!take("optional");
this.handlers = this.normalize(transformer); this.handlers = this.normalize(transformer);
this.opts ||= {}; this.opts ||= {};
this.key = key; this.key = key;
}
Transformer.prototype.normalize = function (transformer) {
if (isFunction(transformer)) {
transformer = { ast: transformer };
} }
traverse.explode(transformer); normalize(transformer) {
if (isFunction(transformer)) {
each(transformer, (fns, type) => { transformer = { ast: transformer };
// hidden property
if (type[0] === "_") {
this[type] = fns;
return;
} }
if (type === "enter" || type === "exit") return; traverse.explode(transformer);
if (isFunction(fns)) fns = { enter: fns }; each(transformer, (fns, type) => {
// hidden property
if (type[0] === "_") {
this[type] = fns;
return;
}
if (!isObject(fns)) return; if (type === "enter" || type === "exit") return;
if (!fns.enter) fns.enter = function () { }; if (isFunction(fns)) fns = { enter: fns };
if (!fns.exit) fns.exit = function () { };
transformer[type] = fns; if (!isObject(fns)) return;
});
return transformer; if (!fns.enter) fns.enter = function () { };
}; if (!fns.exit) fns.exit = function () { };
Transformer.prototype.buildPass = function (file) { transformer[type] = fns;
return new TransformerPass(file, this); });
};
return transformer;
}
buildPass(file) {
return new TransformerPass(file, this);
}
}

View File

@ -1,52 +1,52 @@
module.exports = TraversalContext;
var TraversalPath = require("./path"); var TraversalPath = require("./path");
var flatten = require("lodash/array/flatten"); var flatten = require("lodash/array/flatten");
var compact = require("lodash/array/compact"); var compact = require("lodash/array/compact");
function TraversalContext(scope, opts, state, parentPath) { export default class TraversalConext {
this.shouldFlatten = false; constructor(scope, opts, state, parentPath) {
this.parentPath = parentPath; this.shouldFlatten = false;
this.parentPath = parentPath;
this.scope = scope; this.scope = scope;
this.state = state; this.state = state;
this.opts = opts; this.opts = opts;
}
flatten() {
this.shouldFlatten = true;
}
visitNode(node, obj, key) {
var iteration = new TraversalPath(this, node, obj, key);
return iteration.visit();
}
visit(node, key) {
var nodes = node[key];
if (!nodes) return;
if (!Array.isArray(nodes)) {
return this.visitNode(node, node, key);
}
// nothing to traverse!
if (nodes.length === 0) {
return;
}
for (var i = 0; i < nodes.length; i++) {
if (nodes[i] && this.visitNode(node, nodes, i)) {
return true;
}
}
if (this.shouldFlatten) {
node[key] = flatten(node[key]);
if (key === "body") {
// we can safely compact this
node[key] = compact(node[key]);
}
}
}
} }
TraversalContext.prototype.flatten = function () {
this.shouldFlatten = true;
};
TraversalContext.prototype.visitNode = function (node, obj, key) {
var iteration = new TraversalPath(this, node, obj, key);
return iteration.visit();
};
TraversalContext.prototype.visit = function (node, key) {
var nodes = node[key];
if (!nodes) return;
if (!Array.isArray(nodes)) {
return this.visitNode(node, node, key);
}
// nothing to traverse!
if (nodes.length === 0) {
return;
}
for (var i = 0; i < nodes.length; i++) {
if (nodes[i] && this.visitNode(node, nodes, i)) {
return true;
}
}
if (this.shouldFlatten) {
node[key] = flatten(node[key]);
if (key === "body") {
// we can safely compact this
node[key] = compact(node[key]);
}
}
};

View File

@ -1,68 +1,66 @@
module.exports = TraversalPath;
var traverse = require("./index"); var traverse = require("./index");
var includes = require("lodash/collection/includes"); var includes = require("lodash/collection/includes");
var Scope = require("./scope"); var Scope = require("./scope");
var t = require("../types"); var t = require("../types");
function TraversalPath(context, parent, container, key) { export default class TraversalPath {
this.shouldRemove = false; constructor(context, parent, container, key) {
this.shouldSkip = false; this.shouldRemove = false;
this.shouldStop = false; this.shouldSkip = false;
this.shouldStop = false;
this.parentPath = context.parentPath; this.parentPath = context.parentPath;
this.context = context; this.context = context;
this.state = this.context.state; this.state = this.context.state;
this.opts = this.context.opts; this.opts = this.context.opts;
this.container = container; this.container = container;
this.key = key; this.key = key;
this.parent = parent; this.parent = parent;
this.state = context.state; this.state = context.state;
this.setScope(); this.setScope();
}
TraversalPath.getScope = function (node, parent, scope) {
var ourScope = scope;
// we're entering a new scope so let's construct it!
if (t.isScope(node, parent)) {
ourScope = new Scope(node, parent, scope);
} }
return ourScope; static getScope(node, parent, scope) {
}; var ourScope = scope;
TraversalPath.prototype.setScope = function () { // we're entering a new scope so let's construct it!
this.scope = TraversalPath.getScope(this.node, this.parent, this.context.scope); if (t.isScope(node, parent)) {
}; ourScope = new Scope(node, parent, scope);
}
TraversalPath.prototype.remove = function () { return ourScope;
this.shouldRemove = true; }
this.shouldSkip = true;
};
TraversalPath.prototype.skip = function () { setScope() {
this.shouldSkip = true; this.scope = TraversalPath.getScope(this.node, this.parent, this.context.scope);
}; }
TraversalPath.prototype.stop = function () { remove() {
this.shouldStop = true; this.shouldRemove = true;
this.shouldSkip = true; this.shouldSkip = true;
}; }
TraversalPath.prototype.flatten = function () { skip() {
this.context.flatten(); this.shouldSkip = true;
}; }
Object.defineProperty(TraversalPath.prototype, "node", { stop() {
get() { this.shouldStop = true;
this.shouldSkip = true;
}
flatten() {
this.context.flatten();
}
get node() {
return this.container[this.key]; return this.container[this.key];
}, }
set(replacement) { set node(replacement) {
var isArray = Array.isArray(replacement); var isArray = Array.isArray(replacement);
// inherit comments from original node to the first replacement node // inherit comments from original node to the first replacement node
@ -95,59 +93,59 @@ Object.defineProperty(TraversalPath.prototype, "node", {
this.flatten(); this.flatten();
} }
} }
});
TraversalPath.prototype.call = function (key) { call(key) {
var node = this.node; var node = this.node;
if (!node) return; if (!node) return;
var opts = this.opts; var opts = this.opts;
var fn = opts[key] || opts; var fn = opts[key] || opts;
if (opts[node.type]) fn = opts[node.type][key] || fn; if (opts[node.type]) fn = opts[node.type][key] || fn;
var replacement = fn.call(this, node, this.parent, this.scope, this.state); var replacement = fn.call(this, node, this.parent, this.scope, this.state);
if (replacement) { if (replacement) {
this.node = replacement; this.node = replacement;
}
if (this.shouldRemove) {
this.container[this.key] = null;
this.flatten();
}
} }
if (this.shouldRemove) { visit() {
this.container[this.key] = null; var opts = this.opts;
this.flatten(); var node = this.node;
}
};
TraversalPath.prototype.visit = function () { // type is blacklisted
var opts = this.opts; if (opts.blacklist && opts.blacklist.indexOf(node.type) > -1) {
var node = this.node; return;
}
// type is blacklisted this.call("enter");
if (opts.blacklist && opts.blacklist.indexOf(node.type) > -1) {
return;
}
this.call("enter"); if (this.shouldSkip) {
return this.shouldStop;
}
node = this.node;
if (Array.isArray(node)) {
// traverse over these replacement nodes we purposely don't call exitNode
// as the original node has been destroyed
for (var i = 0; i < node.length; i++) {
traverse.node(node[i], opts, this.scope, this.state, this);
}
} else {
traverse.node(node, opts, this.scope, this.state, this);
this.call("exit");
}
if (this.shouldSkip) {
return this.shouldStop; return this.shouldStop;
} }
node = this.node; isReferencedIdentifier() {
return t.isReferencedIdentifier(this.node);
if (Array.isArray(node)) {
// traverse over these replacement nodes we purposely don't call exitNode
// as the original node has been destroyed
for (var i = 0; i < node.length; i++) {
traverse.node(node[i], opts, this.scope, this.state, this);
}
} else {
traverse.node(node, opts, this.scope, this.state, this);
this.call("exit");
} }
}
return this.shouldStop;
};
TraversalPath.prototype.isReferencedIdentifier = function () {
return t.isReferencedIdentifier(this.node);
};

File diff suppressed because it is too large Load Diff