Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

source-code.js 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. /**
  2. * @fileoverview Abstraction of JavaScript source code.
  3. * @author Nicholas C. Zakas
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const TokenStore = require("../token-store"),
  10. Traverser = require("./traverser"),
  11. astUtils = require("../util/ast-utils"),
  12. lodash = require("lodash");
  13. //------------------------------------------------------------------------------
  14. // Private
  15. //------------------------------------------------------------------------------
  16. /**
  17. * Validates that the given AST has the required information.
  18. * @param {ASTNode} ast The Program node of the AST to check.
  19. * @throws {Error} If the AST doesn't contain the correct information.
  20. * @returns {void}
  21. * @private
  22. */
  23. function validate(ast) {
  24. if (!ast.tokens) {
  25. throw new Error("AST is missing the tokens array.");
  26. }
  27. if (!ast.comments) {
  28. throw new Error("AST is missing the comments array.");
  29. }
  30. if (!ast.loc) {
  31. throw new Error("AST is missing location information.");
  32. }
  33. if (!ast.range) {
  34. throw new Error("AST is missing range information");
  35. }
  36. }
  37. /**
  38. * Check to see if its a ES6 export declaration.
  39. * @param {ASTNode} astNode An AST node.
  40. * @returns {boolean} whether the given node represents an export declaration.
  41. * @private
  42. */
  43. function looksLikeExport(astNode) {
  44. return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" ||
  45. astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier";
  46. }
  47. /**
  48. * Merges two sorted lists into a larger sorted list in O(n) time.
  49. * @param {Token[]} tokens The list of tokens.
  50. * @param {Token[]} comments The list of comments.
  51. * @returns {Token[]} A sorted list of tokens and comments.
  52. * @private
  53. */
  54. function sortedMerge(tokens, comments) {
  55. const result = [];
  56. let tokenIndex = 0;
  57. let commentIndex = 0;
  58. while (tokenIndex < tokens.length || commentIndex < comments.length) {
  59. if (commentIndex >= comments.length || tokenIndex < tokens.length && tokens[tokenIndex].range[0] < comments[commentIndex].range[0]) {
  60. result.push(tokens[tokenIndex++]);
  61. } else {
  62. result.push(comments[commentIndex++]);
  63. }
  64. }
  65. return result;
  66. }
  67. //------------------------------------------------------------------------------
  68. // Public Interface
  69. //------------------------------------------------------------------------------
  70. class SourceCode extends TokenStore {
  71. /**
  72. * Represents parsed source code.
  73. * @param {string|Object} textOrConfig - The source code text or config object.
  74. * @param {string} textOrConfig.text - The source code text.
  75. * @param {ASTNode} textOrConfig.ast - The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped.
  76. * @param {Object|null} textOrConfig.parserServices - The parser srevices.
  77. * @param {ScopeManager|null} textOrConfig.scopeManager - The scope of this source code.
  78. * @param {Object|null} textOrConfig.visitorKeys - The visitor keys to traverse AST.
  79. * @param {ASTNode} [astIfNoConfig] - The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped.
  80. * @constructor
  81. */
  82. constructor(textOrConfig, astIfNoConfig) {
  83. let text, ast, parserServices, scopeManager, visitorKeys;
  84. // Process overloading.
  85. if (typeof textOrConfig === "string") {
  86. text = textOrConfig;
  87. ast = astIfNoConfig;
  88. } else if (typeof textOrConfig === "object" && textOrConfig !== null) {
  89. text = textOrConfig.text;
  90. ast = textOrConfig.ast;
  91. parserServices = textOrConfig.parserServices;
  92. scopeManager = textOrConfig.scopeManager;
  93. visitorKeys = textOrConfig.visitorKeys;
  94. }
  95. validate(ast);
  96. super(ast.tokens, ast.comments);
  97. /**
  98. * The flag to indicate that the source code has Unicode BOM.
  99. * @type boolean
  100. */
  101. this.hasBOM = (text.charCodeAt(0) === 0xFEFF);
  102. /**
  103. * The original text source code.
  104. * BOM was stripped from this text.
  105. * @type string
  106. */
  107. this.text = (this.hasBOM ? text.slice(1) : text);
  108. /**
  109. * The parsed AST for the source code.
  110. * @type ASTNode
  111. */
  112. this.ast = ast;
  113. /**
  114. * The parser services of this source code.
  115. * @type {Object}
  116. */
  117. this.parserServices = parserServices || {};
  118. /**
  119. * The scope of this source code.
  120. * @type {ScopeManager|null}
  121. */
  122. this.scopeManager = scopeManager || null;
  123. /**
  124. * The visitor keys to traverse AST.
  125. * @type {Object}
  126. */
  127. this.visitorKeys = visitorKeys || Traverser.DEFAULT_VISITOR_KEYS;
  128. // Check the source text for the presence of a shebang since it is parsed as a standard line comment.
  129. const shebangMatched = this.text.match(astUtils.SHEBANG_MATCHER);
  130. const hasShebang = shebangMatched && ast.comments.length && ast.comments[0].value === shebangMatched[1];
  131. if (hasShebang) {
  132. ast.comments[0].type = "Shebang";
  133. }
  134. this.tokensAndComments = sortedMerge(ast.tokens, ast.comments);
  135. /**
  136. * The source code split into lines according to ECMA-262 specification.
  137. * This is done to avoid each rule needing to do so separately.
  138. * @type string[]
  139. */
  140. this.lines = [];
  141. this.lineStartIndices = [0];
  142. const lineEndingPattern = astUtils.createGlobalLinebreakMatcher();
  143. let match;
  144. /*
  145. * Previously, this was implemented using a regex that
  146. * matched a sequence of non-linebreak characters followed by a
  147. * linebreak, then adding the lengths of the matches. However,
  148. * this caused a catastrophic backtracking issue when the end
  149. * of a file contained a large number of non-newline characters.
  150. * To avoid this, the current implementation just matches newlines
  151. * and uses match.index to get the correct line start indices.
  152. */
  153. while ((match = lineEndingPattern.exec(this.text))) {
  154. this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1], match.index));
  155. this.lineStartIndices.push(match.index + match[0].length);
  156. }
  157. this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1]));
  158. // Cache for comments found using getComments().
  159. this._commentCache = new WeakMap();
  160. // don't allow modification of this object
  161. Object.freeze(this);
  162. Object.freeze(this.lines);
  163. }
  164. /**
  165. * Split the source code into multiple lines based on the line delimiters.
  166. * @param {string} text Source code as a string.
  167. * @returns {string[]} Array of source code lines.
  168. * @public
  169. */
  170. static splitLines(text) {
  171. return text.split(astUtils.createGlobalLinebreakMatcher());
  172. }
  173. /**
  174. * Gets the source code for the given node.
  175. * @param {ASTNode=} node The AST node to get the text for.
  176. * @param {int=} beforeCount The number of characters before the node to retrieve.
  177. * @param {int=} afterCount The number of characters after the node to retrieve.
  178. * @returns {string} The text representing the AST node.
  179. * @public
  180. */
  181. getText(node, beforeCount, afterCount) {
  182. if (node) {
  183. return this.text.slice(Math.max(node.range[0] - (beforeCount || 0), 0),
  184. node.range[1] + (afterCount || 0));
  185. }
  186. return this.text;
  187. }
  188. /**
  189. * Gets the entire source text split into an array of lines.
  190. * @returns {Array} The source text as an array of lines.
  191. * @public
  192. */
  193. getLines() {
  194. return this.lines;
  195. }
  196. /**
  197. * Retrieves an array containing all comments in the source code.
  198. * @returns {ASTNode[]} An array of comment nodes.
  199. * @public
  200. */
  201. getAllComments() {
  202. return this.ast.comments;
  203. }
  204. /**
  205. * Gets all comments for the given node.
  206. * @param {ASTNode} node The AST node to get the comments for.
  207. * @returns {Object} An object containing a leading and trailing array
  208. * of comments indexed by their position.
  209. * @public
  210. */
  211. getComments(node) {
  212. if (this._commentCache.has(node)) {
  213. return this._commentCache.get(node);
  214. }
  215. const comments = {
  216. leading: [],
  217. trailing: []
  218. };
  219. /*
  220. * Return all comments as leading comments of the Program node when
  221. * there is no executable code.
  222. */
  223. if (node.type === "Program") {
  224. if (node.body.length === 0) {
  225. comments.leading = node.comments;
  226. }
  227. } else {
  228. /*
  229. * Return comments as trailing comments of nodes that only contain
  230. * comments (to mimic the comment attachment behavior present in Espree).
  231. */
  232. if ((node.type === "BlockStatement" || node.type === "ClassBody") && node.body.length === 0 ||
  233. node.type === "ObjectExpression" && node.properties.length === 0 ||
  234. node.type === "ArrayExpression" && node.elements.length === 0 ||
  235. node.type === "SwitchStatement" && node.cases.length === 0
  236. ) {
  237. comments.trailing = this.getTokens(node, {
  238. includeComments: true,
  239. filter: astUtils.isCommentToken
  240. });
  241. }
  242. /*
  243. * Iterate over tokens before and after node and collect comment tokens.
  244. * Do not include comments that exist outside of the parent node
  245. * to avoid duplication.
  246. */
  247. let currentToken = this.getTokenBefore(node, { includeComments: true });
  248. while (currentToken && astUtils.isCommentToken(currentToken)) {
  249. if (node.parent && (currentToken.start < node.parent.start)) {
  250. break;
  251. }
  252. comments.leading.push(currentToken);
  253. currentToken = this.getTokenBefore(currentToken, { includeComments: true });
  254. }
  255. comments.leading.reverse();
  256. currentToken = this.getTokenAfter(node, { includeComments: true });
  257. while (currentToken && astUtils.isCommentToken(currentToken)) {
  258. if (node.parent && (currentToken.end > node.parent.end)) {
  259. break;
  260. }
  261. comments.trailing.push(currentToken);
  262. currentToken = this.getTokenAfter(currentToken, { includeComments: true });
  263. }
  264. }
  265. this._commentCache.set(node, comments);
  266. return comments;
  267. }
  268. /**
  269. * Retrieves the JSDoc comment for a given node.
  270. * @param {ASTNode} node The AST node to get the comment for.
  271. * @returns {Token|null} The Block comment token containing the JSDoc comment
  272. * for the given node or null if not found.
  273. * @public
  274. */
  275. getJSDocComment(node) {
  276. /**
  277. * Checks for the presence of a JSDoc comment for the given node and returns it.
  278. * @param {ASTNode} astNode The AST node to get the comment for.
  279. * @returns {Token|null} The Block comment token containing the JSDoc comment
  280. * for the given node or null if not found.
  281. * @private
  282. */
  283. const findJSDocComment = astNode => {
  284. const tokenBefore = this.getTokenBefore(astNode, { includeComments: true });
  285. if (
  286. tokenBefore &&
  287. astUtils.isCommentToken(tokenBefore) &&
  288. tokenBefore.type === "Block" &&
  289. tokenBefore.value.charAt(0) === "*" &&
  290. astNode.loc.start.line - tokenBefore.loc.end.line <= 1
  291. ) {
  292. return tokenBefore;
  293. }
  294. return null;
  295. };
  296. let parent = node.parent;
  297. switch (node.type) {
  298. case "ClassDeclaration":
  299. case "FunctionDeclaration":
  300. return findJSDocComment(looksLikeExport(parent) ? parent : node);
  301. case "ClassExpression":
  302. return findJSDocComment(parent.parent);
  303. case "ArrowFunctionExpression":
  304. case "FunctionExpression":
  305. if (parent.type !== "CallExpression" && parent.type !== "NewExpression") {
  306. while (
  307. !this.getCommentsBefore(parent).length &&
  308. !/Function/.test(parent.type) &&
  309. parent.type !== "MethodDefinition" &&
  310. parent.type !== "Property"
  311. ) {
  312. parent = parent.parent;
  313. if (!parent) {
  314. break;
  315. }
  316. }
  317. if (parent && parent.type !== "FunctionDeclaration" && parent.type !== "Program") {
  318. return findJSDocComment(parent);
  319. }
  320. }
  321. return findJSDocComment(node);
  322. // falls through
  323. default:
  324. return null;
  325. }
  326. }
  327. /**
  328. * Gets the deepest node containing a range index.
  329. * @param {int} index Range index of the desired node.
  330. * @returns {ASTNode} The node if found or null if not found.
  331. * @public
  332. */
  333. getNodeByRangeIndex(index) {
  334. let result = null;
  335. Traverser.traverse(this.ast, {
  336. visitorKeys: this.visitorKeys,
  337. enter(node) {
  338. if (node.range[0] <= index && index < node.range[1]) {
  339. result = node;
  340. } else {
  341. this.skip();
  342. }
  343. },
  344. leave(node) {
  345. if (node === result) {
  346. this.break();
  347. }
  348. }
  349. });
  350. return result;
  351. }
  352. /**
  353. * Determines if two tokens have at least one whitespace character
  354. * between them. This completely disregards comments in making the
  355. * determination, so comments count as zero-length substrings.
  356. * @param {Token} first The token to check after.
  357. * @param {Token} second The token to check before.
  358. * @returns {boolean} True if there is only space between tokens, false
  359. * if there is anything other than whitespace between tokens.
  360. * @public
  361. */
  362. isSpaceBetweenTokens(first, second) {
  363. const text = this.text.slice(first.range[1], second.range[0]);
  364. return /\s/.test(text.replace(/\/\*.*?\*\//g, ""));
  365. }
  366. /**
  367. * Converts a source text index into a (line, column) pair.
  368. * @param {number} index The index of a character in a file
  369. * @returns {Object} A {line, column} location object with a 0-indexed column
  370. * @public
  371. */
  372. getLocFromIndex(index) {
  373. if (typeof index !== "number") {
  374. throw new TypeError("Expected `index` to be a number.");
  375. }
  376. if (index < 0 || index > this.text.length) {
  377. throw new RangeError(`Index out of range (requested index ${index}, but source text has length ${this.text.length}).`);
  378. }
  379. /*
  380. * For an argument of this.text.length, return the location one "spot" past the last character
  381. * of the file. If the last character is a linebreak, the location will be column 0 of the next
  382. * line; otherwise, the location will be in the next column on the same line.
  383. *
  384. * See getIndexFromLoc for the motivation for this special case.
  385. */
  386. if (index === this.text.length) {
  387. return { line: this.lines.length, column: this.lines[this.lines.length - 1].length };
  388. }
  389. /*
  390. * To figure out which line rangeIndex is on, determine the last index at which rangeIndex could
  391. * be inserted into lineIndices to keep the list sorted.
  392. */
  393. const lineNumber = lodash.sortedLastIndex(this.lineStartIndices, index);
  394. return { line: lineNumber, column: index - this.lineStartIndices[lineNumber - 1] };
  395. }
  396. /**
  397. * Converts a (line, column) pair into a range index.
  398. * @param {Object} loc A line/column location
  399. * @param {number} loc.line The line number of the location (1-indexed)
  400. * @param {number} loc.column The column number of the location (0-indexed)
  401. * @returns {number} The range index of the location in the file.
  402. * @public
  403. */
  404. getIndexFromLoc(loc) {
  405. if (typeof loc !== "object" || typeof loc.line !== "number" || typeof loc.column !== "number") {
  406. throw new TypeError("Expected `loc` to be an object with numeric `line` and `column` properties.");
  407. }
  408. if (loc.line <= 0) {
  409. throw new RangeError(`Line number out of range (line ${loc.line} requested). Line numbers should be 1-based.`);
  410. }
  411. if (loc.line > this.lineStartIndices.length) {
  412. throw new RangeError(`Line number out of range (line ${loc.line} requested, but only ${this.lineStartIndices.length} lines present).`);
  413. }
  414. const lineStartIndex = this.lineStartIndices[loc.line - 1];
  415. const lineEndIndex = loc.line === this.lineStartIndices.length ? this.text.length : this.lineStartIndices[loc.line];
  416. const positionIndex = lineStartIndex + loc.column;
  417. /*
  418. * By design, getIndexFromLoc({ line: lineNum, column: 0 }) should return the start index of
  419. * the given line, provided that the line number is valid element of this.lines. Since the
  420. * last element of this.lines is an empty string for files with trailing newlines, add a
  421. * special case where getting the index for the first location after the end of the file
  422. * will return the length of the file, rather than throwing an error. This allows rules to
  423. * use getIndexFromLoc consistently without worrying about edge cases at the end of a file.
  424. */
  425. if (
  426. loc.line === this.lineStartIndices.length && positionIndex > lineEndIndex ||
  427. loc.line < this.lineStartIndices.length && positionIndex >= lineEndIndex
  428. ) {
  429. throw new RangeError(`Column number out of range (column ${loc.column} requested, but the length of line ${loc.line} is ${lineEndIndex - lineStartIndex}).`);
  430. }
  431. return positionIndex;
  432. }
  433. }
  434. module.exports = SourceCode;