Fix EsLint Brackets (error markup 'const').
This commit is contained in:
+96
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* @fileoverview The AST node types produced by the parser.
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// None!
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = {
|
||||
AssignmentExpression: "AssignmentExpression",
|
||||
AssignmentPattern: "AssignmentPattern",
|
||||
ArrayExpression: "ArrayExpression",
|
||||
ArrayPattern: "ArrayPattern",
|
||||
ArrowFunctionExpression: "ArrowFunctionExpression",
|
||||
AwaitExpression: "AwaitExpression",
|
||||
BlockStatement: "BlockStatement",
|
||||
BinaryExpression: "BinaryExpression",
|
||||
BreakStatement: "BreakStatement",
|
||||
CallExpression: "CallExpression",
|
||||
CatchClause: "CatchClause",
|
||||
ClassBody: "ClassBody",
|
||||
ClassDeclaration: "ClassDeclaration",
|
||||
ClassExpression: "ClassExpression",
|
||||
ConditionalExpression: "ConditionalExpression",
|
||||
ContinueStatement: "ContinueStatement",
|
||||
DoWhileStatement: "DoWhileStatement",
|
||||
DebuggerStatement: "DebuggerStatement",
|
||||
EmptyStatement: "EmptyStatement",
|
||||
ExpressionStatement: "ExpressionStatement",
|
||||
ForStatement: "ForStatement",
|
||||
ForInStatement: "ForInStatement",
|
||||
ForOfStatement: "ForOfStatement",
|
||||
FunctionDeclaration: "FunctionDeclaration",
|
||||
FunctionExpression: "FunctionExpression",
|
||||
Identifier: "Identifier",
|
||||
IfStatement: "IfStatement",
|
||||
Literal: "Literal",
|
||||
LabeledStatement: "LabeledStatement",
|
||||
LogicalExpression: "LogicalExpression",
|
||||
MemberExpression: "MemberExpression",
|
||||
MetaProperty: "MetaProperty",
|
||||
MethodDefinition: "MethodDefinition",
|
||||
NewExpression: "NewExpression",
|
||||
ObjectExpression: "ObjectExpression",
|
||||
ObjectPattern: "ObjectPattern",
|
||||
Program: "Program",
|
||||
Property: "Property",
|
||||
RestElement: "RestElement",
|
||||
ReturnStatement: "ReturnStatement",
|
||||
SequenceExpression: "SequenceExpression",
|
||||
SpreadElement: "SpreadElement",
|
||||
Super: "Super",
|
||||
SwitchCase: "SwitchCase",
|
||||
SwitchStatement: "SwitchStatement",
|
||||
TaggedTemplateExpression: "TaggedTemplateExpression",
|
||||
TemplateElement: "TemplateElement",
|
||||
TemplateLiteral: "TemplateLiteral",
|
||||
ThisExpression: "ThisExpression",
|
||||
ThrowStatement: "ThrowStatement",
|
||||
TryStatement: "TryStatement",
|
||||
UnaryExpression: "UnaryExpression",
|
||||
UpdateExpression: "UpdateExpression",
|
||||
VariableDeclaration: "VariableDeclaration",
|
||||
VariableDeclarator: "VariableDeclarator",
|
||||
WhileStatement: "WhileStatement",
|
||||
WithStatement: "WithStatement",
|
||||
YieldExpression: "YieldExpression",
|
||||
JSXIdentifier: "JSXIdentifier",
|
||||
JSXNamespacedName: "JSXNamespacedName",
|
||||
JSXMemberExpression: "JSXMemberExpression",
|
||||
JSXEmptyExpression: "JSXEmptyExpression",
|
||||
JSXExpressionContainer: "JSXExpressionContainer",
|
||||
JSXElement: "JSXElement",
|
||||
JSXClosingElement: "JSXClosingElement",
|
||||
JSXOpeningElement: "JSXOpeningElement",
|
||||
JSXAttribute: "JSXAttribute",
|
||||
JSXSpreadAttribute: "JSXSpreadAttribute",
|
||||
JSXText: "JSXText",
|
||||
ExportDefaultDeclaration: "ExportDefaultDeclaration",
|
||||
ExportNamedDeclaration: "ExportNamedDeclaration",
|
||||
ExportAllDeclaration: "ExportAllDeclaration",
|
||||
ExportSpecifier: "ExportSpecifier",
|
||||
ImportDeclaration: "ImportDeclaration",
|
||||
ImportSpecifier: "ImportSpecifier",
|
||||
ImportDefaultSpecifier: "ImportDefaultSpecifier",
|
||||
ImportNamespaceSpecifier: "ImportNamespaceSpecifier"
|
||||
};
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* @fileoverview Attaches comments to the AST.
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var astNodeTypes = require("./ast-node-types");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Private
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var extra = {
|
||||
trailingComments: [],
|
||||
leadingComments: [],
|
||||
bottomRightStack: [],
|
||||
previousNode: null
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = {
|
||||
|
||||
reset: function() {
|
||||
extra.trailingComments = [];
|
||||
extra.leadingComments = [];
|
||||
extra.bottomRightStack = [];
|
||||
extra.previousNode = null;
|
||||
},
|
||||
|
||||
addComment: function(comment) {
|
||||
extra.trailingComments.push(comment);
|
||||
extra.leadingComments.push(comment);
|
||||
},
|
||||
|
||||
processComment: function(node) {
|
||||
var lastChild,
|
||||
trailingComments,
|
||||
i,
|
||||
j;
|
||||
|
||||
if (node.type === astNodeTypes.Program) {
|
||||
if (node.body.length > 0) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (extra.trailingComments.length > 0) {
|
||||
|
||||
/*
|
||||
* If the first comment in trailingComments comes after the
|
||||
* current node, then we're good - all comments in the array will
|
||||
* come after the node and so it's safe to add then as official
|
||||
* trailingComments.
|
||||
*/
|
||||
if (extra.trailingComments[0].range[0] >= node.range[1]) {
|
||||
trailingComments = extra.trailingComments;
|
||||
extra.trailingComments = [];
|
||||
} else {
|
||||
|
||||
/*
|
||||
* Otherwise, if the first comment doesn't come after the
|
||||
* current node, that means we have a mix of leading and trailing
|
||||
* comments in the array and that leadingComments contains the
|
||||
* same items as trailingComments. Reset trailingComments to
|
||||
* zero items and we'll handle this by evaluating leadingComments
|
||||
* later.
|
||||
*/
|
||||
extra.trailingComments.length = 0;
|
||||
}
|
||||
} else {
|
||||
if (extra.bottomRightStack.length > 0 &&
|
||||
extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments &&
|
||||
extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments[0].range[0] >= node.range[1]) {
|
||||
trailingComments = extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments;
|
||||
delete extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments;
|
||||
}
|
||||
}
|
||||
|
||||
// Eating the stack.
|
||||
while (extra.bottomRightStack.length > 0 && extra.bottomRightStack[extra.bottomRightStack.length - 1].range[0] >= node.range[0]) {
|
||||
lastChild = extra.bottomRightStack.pop();
|
||||
}
|
||||
|
||||
if (lastChild) {
|
||||
if (lastChild.leadingComments) {
|
||||
if (lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) {
|
||||
node.leadingComments = lastChild.leadingComments;
|
||||
delete lastChild.leadingComments;
|
||||
} else {
|
||||
// A leading comment for an anonymous class had been stolen by its first MethodDefinition,
|
||||
// so this takes back the leading comment.
|
||||
// See Also: https://github.com/eslint/espree/issues/158
|
||||
for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
|
||||
if (lastChild.leadingComments[i].range[1] <= node.range[0]) {
|
||||
node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (extra.leadingComments.length > 0) {
|
||||
if (extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) {
|
||||
if (extra.previousNode) {
|
||||
for (j = 0; j < extra.leadingComments.length; j++) {
|
||||
if (extra.leadingComments[j].end < extra.previousNode.end) {
|
||||
extra.leadingComments.splice(j, 1);
|
||||
j--;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (extra.leadingComments.length > 0) {
|
||||
node.leadingComments = extra.leadingComments;
|
||||
extra.leadingComments = [];
|
||||
}
|
||||
} else {
|
||||
|
||||
// https://github.com/eslint/espree/issues/2
|
||||
|
||||
/*
|
||||
* In special cases, such as return (without a value) and
|
||||
* debugger, all comments will end up as leadingComments and
|
||||
* will otherwise be eliminated. This extra step runs when the
|
||||
* bottomRightStack is empty and there are comments left
|
||||
* in leadingComments.
|
||||
*
|
||||
* This loop figures out the stopping point between the actual
|
||||
* leading and trailing comments by finding the location of the
|
||||
* first comment that comes after the given node.
|
||||
*/
|
||||
for (i = 0; i < extra.leadingComments.length; i++) {
|
||||
if (extra.leadingComments[i].range[1] > node.range[0]) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Split the array based on the location of the first comment
|
||||
* that comes after the node. Keep in mind that this could
|
||||
* result in an empty array, and if so, the array must be
|
||||
* deleted.
|
||||
*/
|
||||
node.leadingComments = extra.leadingComments.slice(0, i);
|
||||
if (node.leadingComments.length === 0) {
|
||||
delete node.leadingComments;
|
||||
}
|
||||
|
||||
/*
|
||||
* Similarly, trailing comments are attached later. The variable
|
||||
* must be reset to null if there are no trailing comments.
|
||||
*/
|
||||
trailingComments = extra.leadingComments.slice(i);
|
||||
if (trailingComments.length === 0) {
|
||||
trailingComments = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extra.previousNode = node;
|
||||
|
||||
if (trailingComments) {
|
||||
node.trailingComments = trailingComments;
|
||||
}
|
||||
|
||||
extra.bottomRightStack.push(node);
|
||||
}
|
||||
|
||||
};
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
"use strict";
|
||||
|
||||
const acorn = require("acorn");
|
||||
const jsx = require("acorn-jsx");
|
||||
const commentAttachment = require("./comment-attachment");
|
||||
const TokenTranslator = require("./token-translator");
|
||||
|
||||
const DEFAULT_ECMA_VERSION = 5;
|
||||
const STATE = Symbol("espree's internal state");
|
||||
const ESPRIMA_FINISH_NODE = Symbol("espree's esprimaFinishNode");
|
||||
const tokTypes = Object.assign({}, acorn.tokTypes, jsx.tokTypes);
|
||||
|
||||
/**
|
||||
* Normalize ECMAScript version from the initial config
|
||||
* @param {number} ecmaVersion ECMAScript version from the initial config
|
||||
* @returns {number} normalized ECMAScript version
|
||||
*/
|
||||
function normalizeEcmaVersion(ecmaVersion) {
|
||||
if (typeof ecmaVersion === "number") {
|
||||
let version = ecmaVersion;
|
||||
|
||||
// Calculate ECMAScript edition number from official year version starting with
|
||||
// ES2015, which corresponds with ES6 (or a difference of 2009).
|
||||
if (version >= 2015) {
|
||||
version -= 2009;
|
||||
}
|
||||
|
||||
switch (version) {
|
||||
case 3:
|
||||
case 5:
|
||||
case 6:
|
||||
case 7:
|
||||
case 8:
|
||||
case 9:
|
||||
case 10:
|
||||
return version;
|
||||
|
||||
default:
|
||||
throw new Error("Invalid ecmaVersion.");
|
||||
}
|
||||
} else {
|
||||
return DEFAULT_ECMA_VERSION;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an Acorn comment to a Esprima comment.
|
||||
* @param {boolean} block True if it's a block comment, false if not.
|
||||
* @param {string} text The text of the comment.
|
||||
* @param {int} start The index at which the comment starts.
|
||||
* @param {int} end The index at which the comment ends.
|
||||
* @param {Location} startLoc The location at which the comment starts.
|
||||
* @param {Location} endLoc The location at which the comment ends.
|
||||
* @returns {Object} The comment object.
|
||||
* @private
|
||||
*/
|
||||
function convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc) {
|
||||
const comment = {
|
||||
type: block ? "Block" : "Line",
|
||||
value: text
|
||||
};
|
||||
|
||||
if (typeof start === "number") {
|
||||
comment.start = start;
|
||||
comment.end = end;
|
||||
comment.range = [start, end];
|
||||
}
|
||||
|
||||
if (typeof startLoc === "object") {
|
||||
comment.loc = {
|
||||
start: startLoc,
|
||||
end: endLoc
|
||||
};
|
||||
}
|
||||
|
||||
return comment;
|
||||
}
|
||||
|
||||
module.exports = () => Parser => class Espree extends Parser {
|
||||
constructor(options, code) {
|
||||
if (typeof options !== "object" || options === null) {
|
||||
options = {};
|
||||
}
|
||||
if (typeof code !== "string" && !(code instanceof String)) {
|
||||
code = String(code);
|
||||
}
|
||||
|
||||
const ecmaFeatures = options.ecmaFeatures || {};
|
||||
const ecmaVersion = normalizeEcmaVersion(options.ecmaVersion);
|
||||
const isModule = options.sourceType === "module";
|
||||
const tokenTranslator =
|
||||
options.tokens === true ?
|
||||
new TokenTranslator(tokTypes, code) :
|
||||
null;
|
||||
|
||||
// Initialize acorn parser.
|
||||
super({
|
||||
ecmaVersion: isModule ? Math.max(6, ecmaVersion) : ecmaVersion,
|
||||
sourceType: isModule ? "module" : "script",
|
||||
ranges: options.range === true || options.attachComment === true,
|
||||
locations: options.loc === true,
|
||||
|
||||
// Truthy value is true for backward compatibility.
|
||||
allowReturnOutsideFunction: Boolean(ecmaFeatures.globalReturn),
|
||||
|
||||
// Collect tokens
|
||||
onToken: (token) => {
|
||||
if (tokenTranslator) {
|
||||
// Use `tokens`, `ecmaVersion`, and `jsxAttrValueToken` in the state.
|
||||
tokenTranslator.onToken(token, this[STATE]);
|
||||
}
|
||||
if (token.type !== tokTypes.eof) {
|
||||
this[STATE].lastToken = token;
|
||||
}
|
||||
},
|
||||
|
||||
// Collect comments
|
||||
onComment: (block, text, start, end, startLoc, endLoc) => {
|
||||
if (this[STATE].comments) {
|
||||
const comment = convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc);
|
||||
this[STATE].comments.push(comment);
|
||||
|
||||
if (options.attachComment === true) {
|
||||
commentAttachment.addComment(comment);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, code);
|
||||
|
||||
// TODO: remove global state.
|
||||
commentAttachment.reset();
|
||||
|
||||
// Initialize internal state.
|
||||
this[STATE] = {
|
||||
tokens: tokenTranslator ? [] : null,
|
||||
comments: options.comment === true || options.attachComment === true ? [] : null,
|
||||
attachComment: options.attachComment === true,
|
||||
impliedStrict: ecmaFeatures.impliedStrict === true && this.options.ecmaVersion >= 5,
|
||||
ecmaVersion: this.options.ecmaVersion,
|
||||
jsxAttrValueToken: false,
|
||||
lastToken: null
|
||||
};
|
||||
}
|
||||
|
||||
tokenize() {
|
||||
do {
|
||||
this.next();
|
||||
} while (this.type !== tokTypes.eof);
|
||||
|
||||
const extra = this[STATE];
|
||||
const tokens = extra.tokens;
|
||||
|
||||
if (extra.comments) {
|
||||
tokens.comments = extra.comments;
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
finishNode(...args) {
|
||||
const result = super.finishNode(...args);
|
||||
return this[ESPRIMA_FINISH_NODE](result);
|
||||
}
|
||||
|
||||
finishNodeAt(...args) {
|
||||
const result = super.finishNodeAt(...args);
|
||||
return this[ESPRIMA_FINISH_NODE](result);
|
||||
}
|
||||
|
||||
parse() {
|
||||
const extra = this[STATE];
|
||||
const program = super.parse();
|
||||
|
||||
program.sourceType = this.options.sourceType;
|
||||
|
||||
if (extra.comments) {
|
||||
program.comments = extra.comments;
|
||||
}
|
||||
if (extra.tokens) {
|
||||
program.tokens = extra.tokens;
|
||||
}
|
||||
|
||||
/*
|
||||
* Adjust opening and closing position of program to match Esprima.
|
||||
* Acorn always starts programs at range 0 whereas Esprima starts at the
|
||||
* first AST node's start (the only real difference is when there's leading
|
||||
* whitespace or leading comments). Acorn also counts trailing whitespace
|
||||
* as part of the program whereas Esprima only counts up to the last token.
|
||||
*/
|
||||
if (program.range) {
|
||||
program.range[0] = program.body.length ? program.body[0].range[0] : program.range[0];
|
||||
program.range[1] = extra.lastToken ? extra.lastToken.range[1] : program.range[1];
|
||||
}
|
||||
if (program.loc) {
|
||||
program.loc.start = program.body.length ? program.body[0].loc.start : program.loc.start;
|
||||
program.loc.end = extra.lastToken ? extra.lastToken.loc.end : program.loc.end;
|
||||
}
|
||||
|
||||
return program;
|
||||
}
|
||||
|
||||
parseTopLevel(node) {
|
||||
if (this[STATE].impliedStrict) {
|
||||
this.strict = true;
|
||||
}
|
||||
return super.parseTopLevel(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Overwrites the default raise method to throw Esprima-style errors.
|
||||
* @param {int} pos The position of the error.
|
||||
* @param {string} message The error message.
|
||||
* @throws {SyntaxError} A syntax error.
|
||||
* @returns {void}
|
||||
*/
|
||||
raise(pos, message) {
|
||||
const loc = acorn.getLineInfo(this.input, pos);
|
||||
const err = new SyntaxError(message);
|
||||
err.index = pos;
|
||||
err.lineNumber = loc.line;
|
||||
err.column = loc.column + 1; // acorn uses 0-based columns
|
||||
throw err;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overwrites the default raise method to throw Esprima-style errors.
|
||||
* @param {int} pos The position of the error.
|
||||
* @param {string} message The error message.
|
||||
* @throws {SyntaxError} A syntax error.
|
||||
* @returns {void}
|
||||
*/
|
||||
raiseRecoverable(pos, message) {
|
||||
this.raise(pos, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Overwrites the default unexpected method to throw Esprima-style errors.
|
||||
* @param {int} pos The position of the error.
|
||||
* @throws {SyntaxError} A syntax error.
|
||||
* @returns {void}
|
||||
*/
|
||||
unexpected(pos) {
|
||||
let message = "Unexpected token";
|
||||
|
||||
if (pos !== null && pos !== void 0) {
|
||||
this.pos = pos;
|
||||
|
||||
if (this.options.locations) {
|
||||
while (this.pos < this.lineStart) {
|
||||
this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1;
|
||||
--this.curLine;
|
||||
}
|
||||
}
|
||||
|
||||
this.nextToken();
|
||||
}
|
||||
|
||||
if (this.end > this.start) {
|
||||
message += " " + this.input.slice(this.start, this.end);
|
||||
}
|
||||
|
||||
this.raise(this.start, message);
|
||||
}
|
||||
|
||||
/*
|
||||
* Esprima-FB represents JSX strings as tokens called "JSXText", but Acorn-JSX
|
||||
* uses regular tt.string without any distinction between this and regular JS
|
||||
* strings. As such, we intercept an attempt to read a JSX string and set a flag
|
||||
* on extra so that when tokens are converted, the next token will be switched
|
||||
* to JSXText via onToken.
|
||||
*/
|
||||
jsx_readString(quote) { // eslint-disable-line camelcase
|
||||
const result = super.jsx_readString(quote);
|
||||
if (this.type === tokTypes.string) {
|
||||
this[STATE].jsxAttrValueToken = true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs last-minute Esprima-specific compatibility checks and fixes.
|
||||
* @param {ASTNode} result The node to check.
|
||||
* @returns {ASTNode} The finished node.
|
||||
*/
|
||||
[ESPRIMA_FINISH_NODE](result) {
|
||||
// Acorn doesn't count the opening and closing backticks as part of templates
|
||||
// so we have to adjust ranges/locations appropriately.
|
||||
if (result.type === "TemplateElement") {
|
||||
|
||||
// additional adjustment needed if ${ is the last token
|
||||
const terminalDollarBraceL = this.input.slice(result.end, result.end + 2) === "${";
|
||||
|
||||
if (result.range) {
|
||||
result.range[0]--;
|
||||
result.range[1] += (terminalDollarBraceL ? 2 : 1);
|
||||
}
|
||||
|
||||
if (result.loc) {
|
||||
result.loc.start.column--;
|
||||
result.loc.end.column += (terminalDollarBraceL ? 2 : 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (this[STATE].attachComment) {
|
||||
commentAttachment.processComment(result);
|
||||
}
|
||||
|
||||
if (result.type.indexOf("Function") > -1 && !result.generator) {
|
||||
result.generator = false;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* @fileoverview The list of feature flags supported by the parser and their default
|
||||
* settings.
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// None!
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = {
|
||||
|
||||
// React JSX parsing
|
||||
jsx: false,
|
||||
|
||||
// allow return statement in global scope
|
||||
globalReturn: false,
|
||||
|
||||
// allow implied strict mode
|
||||
impliedStrict: false
|
||||
};
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
/**
|
||||
* @fileoverview Translates tokens between Acorn format and Esprima format.
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
/* eslint no-underscore-dangle: 0 */
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// none!
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Private
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
|
||||
// Esprima Token Types
|
||||
var Token = {
|
||||
Boolean: "Boolean",
|
||||
EOF: "<end>",
|
||||
Identifier: "Identifier",
|
||||
Keyword: "Keyword",
|
||||
Null: "Null",
|
||||
Numeric: "Numeric",
|
||||
Punctuator: "Punctuator",
|
||||
String: "String",
|
||||
RegularExpression: "RegularExpression",
|
||||
Template: "Template",
|
||||
JSXIdentifier: "JSXIdentifier",
|
||||
JSXText: "JSXText"
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts part of a template into an Esprima token.
|
||||
* @param {AcornToken[]} tokens The Acorn tokens representing the template.
|
||||
* @param {string} code The source code.
|
||||
* @returns {EsprimaToken} The Esprima equivalent of the template token.
|
||||
* @private
|
||||
*/
|
||||
function convertTemplatePart(tokens, code) {
|
||||
var firstToken = tokens[0],
|
||||
lastTemplateToken = tokens[tokens.length - 1];
|
||||
|
||||
var token = {
|
||||
type: Token.Template,
|
||||
value: code.slice(firstToken.start, lastTemplateToken.end)
|
||||
};
|
||||
|
||||
if (firstToken.loc) {
|
||||
token.loc = {
|
||||
start: firstToken.loc.start,
|
||||
end: lastTemplateToken.loc.end
|
||||
};
|
||||
}
|
||||
|
||||
if (firstToken.range) {
|
||||
token.start = firstToken.range[0];
|
||||
token.end = lastTemplateToken.range[1];
|
||||
token.range = [token.start, token.end];
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Contains logic to translate Acorn tokens into Esprima tokens.
|
||||
* @param {Object} acornTokTypes The Acorn token types.
|
||||
* @param {string} code The source code Acorn is parsing. This is necessary
|
||||
* to correct the "value" property of some tokens.
|
||||
* @constructor
|
||||
*/
|
||||
function TokenTranslator(acornTokTypes, code) {
|
||||
|
||||
// token types
|
||||
this._acornTokTypes = acornTokTypes;
|
||||
|
||||
// token buffer for templates
|
||||
this._tokens = [];
|
||||
|
||||
// track the last curly brace
|
||||
this._curlyBrace = null;
|
||||
|
||||
// the source code
|
||||
this._code = code;
|
||||
|
||||
}
|
||||
|
||||
TokenTranslator.prototype = {
|
||||
constructor: TokenTranslator,
|
||||
|
||||
/**
|
||||
* Translates a single Esprima token to a single Acorn token. This may be
|
||||
* inaccurate due to how templates are handled differently in Esprima and
|
||||
* Acorn, but should be accurate for all other tokens.
|
||||
* @param {AcornToken} token The Acorn token to translate.
|
||||
* @param {Object} extra Espree extra object.
|
||||
* @returns {EsprimaToken} The Esprima version of the token.
|
||||
*/
|
||||
translate: function(token, extra) {
|
||||
|
||||
var type = token.type,
|
||||
tt = this._acornTokTypes;
|
||||
|
||||
if (type === tt.name) {
|
||||
token.type = Token.Identifier;
|
||||
|
||||
// TODO: See if this is an Acorn bug
|
||||
if (token.value === "static") {
|
||||
token.type = Token.Keyword;
|
||||
}
|
||||
|
||||
if (extra.ecmaVersion > 5 && (token.value === "yield" || token.value === "let")) {
|
||||
token.type = Token.Keyword;
|
||||
}
|
||||
|
||||
} else if (type === tt.semi || type === tt.comma ||
|
||||
type === tt.parenL || type === tt.parenR ||
|
||||
type === tt.braceL || type === tt.braceR ||
|
||||
type === tt.dot || type === tt.bracketL ||
|
||||
type === tt.colon || type === tt.question ||
|
||||
type === tt.bracketR || type === tt.ellipsis ||
|
||||
type === tt.arrow || type === tt.jsxTagStart ||
|
||||
type === tt.incDec || type === tt.starstar ||
|
||||
type === tt.jsxTagEnd || type === tt.prefix ||
|
||||
(type.binop && !type.keyword) ||
|
||||
type.isAssign) {
|
||||
|
||||
token.type = Token.Punctuator;
|
||||
token.value = this._code.slice(token.start, token.end);
|
||||
} else if (type === tt.jsxName) {
|
||||
token.type = Token.JSXIdentifier;
|
||||
} else if (type.label === "jsxText" || type === tt.jsxAttrValueToken) {
|
||||
token.type = Token.JSXText;
|
||||
} else if (type.keyword) {
|
||||
if (type.keyword === "true" || type.keyword === "false") {
|
||||
token.type = Token.Boolean;
|
||||
} else if (type.keyword === "null") {
|
||||
token.type = Token.Null;
|
||||
} else {
|
||||
token.type = Token.Keyword;
|
||||
}
|
||||
} else if (type === tt.num) {
|
||||
token.type = Token.Numeric;
|
||||
token.value = this._code.slice(token.start, token.end);
|
||||
} else if (type === tt.string) {
|
||||
|
||||
if (extra.jsxAttrValueToken) {
|
||||
extra.jsxAttrValueToken = false;
|
||||
token.type = Token.JSXText;
|
||||
} else {
|
||||
token.type = Token.String;
|
||||
}
|
||||
|
||||
token.value = this._code.slice(token.start, token.end);
|
||||
} else if (type === tt.regexp) {
|
||||
token.type = Token.RegularExpression;
|
||||
var value = token.value;
|
||||
token.regex = {
|
||||
flags: value.flags,
|
||||
pattern: value.pattern
|
||||
};
|
||||
token.value = "/" + value.pattern + "/" + value.flags;
|
||||
}
|
||||
|
||||
return token;
|
||||
},
|
||||
|
||||
/**
|
||||
* Function to call during Acorn's onToken handler.
|
||||
* @param {AcornToken} token The Acorn token.
|
||||
* @param {Object} extra The Espree extra object.
|
||||
* @returns {void}
|
||||
*/
|
||||
onToken: function(token, extra) {
|
||||
|
||||
var that = this,
|
||||
tt = this._acornTokTypes,
|
||||
tokens = extra.tokens,
|
||||
templateTokens = this._tokens;
|
||||
|
||||
/**
|
||||
* Flushes the buffered template tokens and resets the template
|
||||
* tracking.
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function translateTemplateTokens() {
|
||||
tokens.push(convertTemplatePart(that._tokens, that._code));
|
||||
that._tokens = [];
|
||||
}
|
||||
|
||||
if (token.type === tt.eof) {
|
||||
|
||||
// might be one last curlyBrace
|
||||
if (this._curlyBrace) {
|
||||
tokens.push(this.translate(this._curlyBrace, extra));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (token.type === tt.backQuote) {
|
||||
|
||||
// if there's already a curly, it's not part of the template
|
||||
if (this._curlyBrace) {
|
||||
tokens.push(this.translate(this._curlyBrace, extra));
|
||||
this._curlyBrace = null;
|
||||
}
|
||||
|
||||
templateTokens.push(token);
|
||||
|
||||
// it's the end
|
||||
if (templateTokens.length > 1) {
|
||||
translateTemplateTokens();
|
||||
}
|
||||
|
||||
return;
|
||||
} else if (token.type === tt.dollarBraceL) {
|
||||
templateTokens.push(token);
|
||||
translateTemplateTokens();
|
||||
return;
|
||||
} else if (token.type === tt.braceR) {
|
||||
|
||||
// if there's already a curly, it's not part of the template
|
||||
if (this._curlyBrace) {
|
||||
tokens.push(this.translate(this._curlyBrace, extra));
|
||||
}
|
||||
|
||||
// store new curly for later
|
||||
this._curlyBrace = token;
|
||||
return;
|
||||
} else if (token.type === tt.template || token.type === tt.invalidTemplate) {
|
||||
if (this._curlyBrace) {
|
||||
templateTokens.push(this._curlyBrace);
|
||||
this._curlyBrace = null;
|
||||
}
|
||||
|
||||
templateTokens.push(token);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._curlyBrace) {
|
||||
tokens.push(this.translate(this._curlyBrace, extra));
|
||||
this._curlyBrace = null;
|
||||
}
|
||||
|
||||
tokens.push(this.translate(token, extra));
|
||||
}
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = TokenTranslator;
|
||||
Reference in New Issue
Block a user