123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507 |
- "use strict";
- const TokenStore = require("../token-store"),
- Traverser = require("./traverser"),
- astUtils = require("../util/ast-utils"),
- lodash = require("lodash");
- function validate(ast) {
- if (!ast.tokens) {
- throw new Error("AST is missing the tokens array.");
- }
- if (!ast.comments) {
- throw new Error("AST is missing the comments array.");
- }
- if (!ast.loc) {
- throw new Error("AST is missing location information.");
- }
- if (!ast.range) {
- throw new Error("AST is missing range information");
- }
- }
- function looksLikeExport(astNode) {
- return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" ||
- astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier";
- }
- function sortedMerge(tokens, comments) {
- const result = [];
- let tokenIndex = 0;
- let commentIndex = 0;
- while (tokenIndex < tokens.length || commentIndex < comments.length) {
- if (commentIndex >= comments.length || tokenIndex < tokens.length && tokens[tokenIndex].range[0] < comments[commentIndex].range[0]) {
- result.push(tokens[tokenIndex++]);
- } else {
- result.push(comments[commentIndex++]);
- }
- }
- return result;
- }
- class SourceCode extends TokenStore {
-
- constructor(textOrConfig, astIfNoConfig) {
- let text, ast, parserServices, scopeManager, visitorKeys;
-
- if (typeof textOrConfig === "string") {
- text = textOrConfig;
- ast = astIfNoConfig;
- } else if (typeof textOrConfig === "object" && textOrConfig !== null) {
- text = textOrConfig.text;
- ast = textOrConfig.ast;
- parserServices = textOrConfig.parserServices;
- scopeManager = textOrConfig.scopeManager;
- visitorKeys = textOrConfig.visitorKeys;
- }
- validate(ast);
- super(ast.tokens, ast.comments);
-
- this.hasBOM = (text.charCodeAt(0) === 0xFEFF);
-
- this.text = (this.hasBOM ? text.slice(1) : text);
-
- this.ast = ast;
-
- this.parserServices = parserServices || {};
-
- this.scopeManager = scopeManager || null;
-
- this.visitorKeys = visitorKeys || Traverser.DEFAULT_VISITOR_KEYS;
-
- const shebangMatched = this.text.match(astUtils.SHEBANG_MATCHER);
- const hasShebang = shebangMatched && ast.comments.length && ast.comments[0].value === shebangMatched[1];
- if (hasShebang) {
- ast.comments[0].type = "Shebang";
- }
- this.tokensAndComments = sortedMerge(ast.tokens, ast.comments);
-
- this.lines = [];
- this.lineStartIndices = [0];
- const lineEndingPattern = astUtils.createGlobalLinebreakMatcher();
- let match;
-
- while ((match = lineEndingPattern.exec(this.text))) {
- this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1], match.index));
- this.lineStartIndices.push(match.index + match[0].length);
- }
- this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1]));
-
- this._commentCache = new WeakMap();
-
- Object.freeze(this);
- Object.freeze(this.lines);
- }
-
- static splitLines(text) {
- return text.split(astUtils.createGlobalLinebreakMatcher());
- }
-
- getText(node, beforeCount, afterCount) {
- if (node) {
- return this.text.slice(Math.max(node.range[0] - (beforeCount || 0), 0),
- node.range[1] + (afterCount || 0));
- }
- return this.text;
- }
-
- getLines() {
- return this.lines;
- }
-
- getAllComments() {
- return this.ast.comments;
- }
-
- getComments(node) {
- if (this._commentCache.has(node)) {
- return this._commentCache.get(node);
- }
- const comments = {
- leading: [],
- trailing: []
- };
-
- if (node.type === "Program") {
- if (node.body.length === 0) {
- comments.leading = node.comments;
- }
- } else {
-
- if ((node.type === "BlockStatement" || node.type === "ClassBody") && node.body.length === 0 ||
- node.type === "ObjectExpression" && node.properties.length === 0 ||
- node.type === "ArrayExpression" && node.elements.length === 0 ||
- node.type === "SwitchStatement" && node.cases.length === 0
- ) {
- comments.trailing = this.getTokens(node, {
- includeComments: true,
- filter: astUtils.isCommentToken
- });
- }
-
- let currentToken = this.getTokenBefore(node, { includeComments: true });
- while (currentToken && astUtils.isCommentToken(currentToken)) {
- if (node.parent && (currentToken.start < node.parent.start)) {
- break;
- }
- comments.leading.push(currentToken);
- currentToken = this.getTokenBefore(currentToken, { includeComments: true });
- }
- comments.leading.reverse();
- currentToken = this.getTokenAfter(node, { includeComments: true });
- while (currentToken && astUtils.isCommentToken(currentToken)) {
- if (node.parent && (currentToken.end > node.parent.end)) {
- break;
- }
- comments.trailing.push(currentToken);
- currentToken = this.getTokenAfter(currentToken, { includeComments: true });
- }
- }
- this._commentCache.set(node, comments);
- return comments;
- }
-
- getJSDocComment(node) {
-
- const findJSDocComment = astNode => {
- const tokenBefore = this.getTokenBefore(astNode, { includeComments: true });
- if (
- tokenBefore &&
- astUtils.isCommentToken(tokenBefore) &&
- tokenBefore.type === "Block" &&
- tokenBefore.value.charAt(0) === "*" &&
- astNode.loc.start.line - tokenBefore.loc.end.line <= 1
- ) {
- return tokenBefore;
- }
- return null;
- };
- let parent = node.parent;
- switch (node.type) {
- case "ClassDeclaration":
- case "FunctionDeclaration":
- return findJSDocComment(looksLikeExport(parent) ? parent : node);
- case "ClassExpression":
- return findJSDocComment(parent.parent);
- case "ArrowFunctionExpression":
- case "FunctionExpression":
- if (parent.type !== "CallExpression" && parent.type !== "NewExpression") {
- while (
- !this.getCommentsBefore(parent).length &&
- !/Function/u.test(parent.type) &&
- parent.type !== "MethodDefinition" &&
- parent.type !== "Property"
- ) {
- parent = parent.parent;
- if (!parent) {
- break;
- }
- }
- if (parent && parent.type !== "FunctionDeclaration" && parent.type !== "Program") {
- return findJSDocComment(parent);
- }
- }
- return findJSDocComment(node);
-
- default:
- return null;
- }
- }
-
- getNodeByRangeIndex(index) {
- let result = null;
- Traverser.traverse(this.ast, {
- visitorKeys: this.visitorKeys,
- enter(node) {
- if (node.range[0] <= index && index < node.range[1]) {
- result = node;
- } else {
- this.skip();
- }
- },
- leave(node) {
- if (node === result) {
- this.break();
- }
- }
- });
- return result;
- }
-
- isSpaceBetweenTokens(first, second) {
- const text = this.text.slice(first.range[1], second.range[0]);
- return /\s/u.test(text.replace(/\/\*.*?\*\//gu, ""));
- }
-
- getLocFromIndex(index) {
- if (typeof index !== "number") {
- throw new TypeError("Expected `index` to be a number.");
- }
- if (index < 0 || index > this.text.length) {
- throw new RangeError(`Index out of range (requested index ${index}, but source text has length ${this.text.length}).`);
- }
-
- if (index === this.text.length) {
- return { line: this.lines.length, column: this.lines[this.lines.length - 1].length };
- }
-
- const lineNumber = lodash.sortedLastIndex(this.lineStartIndices, index);
- return { line: lineNumber, column: index - this.lineStartIndices[lineNumber - 1] };
- }
-
- getIndexFromLoc(loc) {
- if (typeof loc !== "object" || typeof loc.line !== "number" || typeof loc.column !== "number") {
- throw new TypeError("Expected `loc` to be an object with numeric `line` and `column` properties.");
- }
- if (loc.line <= 0) {
- throw new RangeError(`Line number out of range (line ${loc.line} requested). Line numbers should be 1-based.`);
- }
- if (loc.line > this.lineStartIndices.length) {
- throw new RangeError(`Line number out of range (line ${loc.line} requested, but only ${this.lineStartIndices.length} lines present).`);
- }
- const lineStartIndex = this.lineStartIndices[loc.line - 1];
- const lineEndIndex = loc.line === this.lineStartIndices.length ? this.text.length : this.lineStartIndices[loc.line];
- const positionIndex = lineStartIndex + loc.column;
-
- if (
- loc.line === this.lineStartIndices.length && positionIndex > lineEndIndex ||
- loc.line < this.lineStartIndices.length && positionIndex >= lineEndIndex
- ) {
- throw new RangeError(`Column number out of range (column ${loc.column} requested, but the length of line ${loc.line} is ${lineEndIndex - lineStartIndex}).`);
- }
- return positionIndex;
- }
- }
- module.exports = SourceCode;
|