file-report.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. /**
  2. * @fileoverview A class to track messages reported by the linter for a file.
  3. * @author Nicholas C. Zakas
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const assert = require("../shared/assert");
  10. const { RuleFixer } = require("./rule-fixer");
  11. const { interpolate } = require("./interpolate");
  12. const ruleReplacements = require("../../conf/replacements.json");
  13. //------------------------------------------------------------------------------
  14. // Typedefs
  15. //------------------------------------------------------------------------------
  16. /** @typedef {import("../types").Linter.LintMessage} LintMessage */
  17. /** @typedef {import("../types").Linter.LintSuggestion} SuggestionResult */
  18. /** @typedef {import("@eslint/core").Language} Language */
  19. /** @typedef {import("@eslint/core").SourceLocation} SourceLocation */
  20. /**
  21. * An error message description
  22. * @typedef {Object} MessageDescriptor
  23. * @property {ASTNode} [node] The reported node
  24. * @property {Location} loc The location of the problem.
  25. * @property {string} message The problem message.
  26. * @property {Object} [data] Optional data to use to fill in placeholders in the
  27. * message.
  28. * @property {Function} [fix] The function to call that creates a fix command.
  29. * @property {Array<{desc?: string, messageId?: string, fix: Function}>} suggest Suggestion descriptions and functions to create a the associated fixes.
  30. */
  31. /**
  32. * @typedef {Object} LintProblem
  33. * @property {string} ruleId The rule ID that reported the problem.
  34. * @property {string} message The problem message.
  35. * @property {SourceLocation} loc The location of the problem.
  36. */
  37. //------------------------------------------------------------------------------
  38. // Helpers
  39. //------------------------------------------------------------------------------
  40. const DEFAULT_ERROR_LOC = {
  41. start: { line: 1, column: 0 },
  42. end: { line: 1, column: 1 },
  43. };
  44. /**
  45. * Updates a given location based on the language offsets. This allows us to
  46. * change 0-based locations to 1-based locations. We always want ESLint
  47. * reporting lines and columns starting from 1.
  48. * @todo Potentially this should be moved into a shared utility file.
  49. * @param {Object} location The location to update.
  50. * @param {number} location.line The starting line number.
  51. * @param {number} location.column The starting column number.
  52. * @param {number} [location.endLine] The ending line number.
  53. * @param {number} [location.endColumn] The ending column number.
  54. * @param {Language} language The language to use to adjust the location information.
  55. * @returns {Object} The updated location.
  56. */
  57. function updateLocationInformation(
  58. { line, column, endLine, endColumn },
  59. language,
  60. ) {
  61. const columnOffset = language.columnStart === 1 ? 0 : 1;
  62. const lineOffset = language.lineStart === 1 ? 0 : 1;
  63. // calculate separately to account for undefined
  64. const finalEndLine = endLine === void 0 ? endLine : endLine + lineOffset;
  65. const finalEndColumn =
  66. endColumn === void 0 ? endColumn : endColumn + columnOffset;
  67. return {
  68. line: line + lineOffset,
  69. column: column + columnOffset,
  70. endLine: finalEndLine,
  71. endColumn: finalEndColumn,
  72. };
  73. }
  74. /**
  75. * creates a missing-rule message.
  76. * @param {string} ruleId the ruleId to create
  77. * @returns {string} created error message
  78. * @private
  79. */
  80. function createMissingRuleMessage(ruleId) {
  81. return Object.hasOwn(ruleReplacements.rules, ruleId)
  82. ? `Rule '${ruleId}' was removed and replaced by: ${ruleReplacements.rules[ruleId].join(", ")}`
  83. : `Definition for rule '${ruleId}' was not found.`;
  84. }
  85. /**
  86. * creates a linting problem
  87. * @param {LintProblem} options to create linting error
  88. * @param {RuleSeverity} severity the error message to report
  89. * @param {Language} language the language to use to adjust the location information.
  90. * @returns {LintMessage} created problem, returns a missing-rule problem if only provided ruleId.
  91. * @private
  92. */
  93. function createLintingProblem(options, severity, language) {
  94. const {
  95. ruleId = null,
  96. loc = DEFAULT_ERROR_LOC,
  97. message = createMissingRuleMessage(options.ruleId),
  98. } = options;
  99. return {
  100. ruleId,
  101. message,
  102. ...updateLocationInformation(
  103. {
  104. line: loc.start.line,
  105. column: loc.start.column,
  106. endLine: loc.end.line,
  107. endColumn: loc.end.column,
  108. },
  109. language,
  110. ),
  111. severity,
  112. nodeType: null,
  113. };
  114. }
  115. /**
  116. * Translates a multi-argument context.report() call into a single object argument call
  117. * @param {...*} args A list of arguments passed to `context.report`
  118. * @returns {MessageDescriptor} A normalized object containing report information
  119. */
  120. function normalizeMultiArgReportCall(...args) {
  121. // If there is one argument, it is considered to be a new-style call already.
  122. if (args.length === 1) {
  123. // Shallow clone the object to avoid surprises if reusing the descriptor
  124. return Object.assign({}, args[0]);
  125. }
  126. // If the second argument is a string, the arguments are interpreted as [node, message, data, fix].
  127. if (typeof args[1] === "string") {
  128. return {
  129. node: args[0],
  130. message: args[1],
  131. data: args[2],
  132. fix: args[3],
  133. };
  134. }
  135. // Otherwise, the arguments are interpreted as [node, loc, message, data, fix].
  136. return {
  137. node: args[0],
  138. loc: args[1],
  139. message: args[2],
  140. data: args[3],
  141. fix: args[4],
  142. };
  143. }
  144. /**
  145. * Asserts that either a loc or a node was provided, and the node is valid if it was provided.
  146. * @param {MessageDescriptor} descriptor A descriptor to validate
  147. * @returns {void}
  148. * @throws AssertionError if neither a node nor a loc was provided, or if the node is not an object
  149. */
  150. function assertValidNodeInfo(descriptor) {
  151. if (descriptor.node) {
  152. assert(typeof descriptor.node === "object", "Node must be an object");
  153. } else {
  154. assert(
  155. descriptor.loc,
  156. "Node must be provided when reporting error if location is not provided",
  157. );
  158. }
  159. }
  160. /**
  161. * Normalizes a MessageDescriptor to always have a `loc` with `start` and `end` properties
  162. * @param {MessageDescriptor} descriptor A descriptor for the report from a rule.
  163. * @returns {{start: Location, end: (Location|null)}} An updated location that infers the `start` and `end` properties
  164. * from the `node` of the original descriptor, or infers the `start` from the `loc` of the original descriptor.
  165. */
  166. function normalizeReportLoc(descriptor) {
  167. if (descriptor.loc.start) {
  168. return descriptor.loc;
  169. }
  170. return { start: descriptor.loc, end: null };
  171. }
  172. /**
  173. * Clones the given fix object.
  174. * @param {Fix|null} fix The fix to clone.
  175. * @returns {Fix|null} Deep cloned fix object or `null` if `null` or `undefined` was passed in.
  176. */
  177. function cloneFix(fix) {
  178. if (!fix) {
  179. return null;
  180. }
  181. return {
  182. range: [fix.range[0], fix.range[1]],
  183. text: fix.text,
  184. };
  185. }
  186. /**
  187. * Check that a fix has a valid range.
  188. * @param {Fix|null} fix The fix to validate.
  189. * @returns {void}
  190. */
  191. function assertValidFix(fix) {
  192. if (fix) {
  193. assert(
  194. fix.range &&
  195. typeof fix.range[0] === "number" &&
  196. typeof fix.range[1] === "number",
  197. `Fix has invalid range: ${JSON.stringify(fix, null, 2)}`,
  198. );
  199. }
  200. }
  201. /**
  202. * Compares items in a fixes array by range.
  203. * @param {Fix} a The first message.
  204. * @param {Fix} b The second message.
  205. * @returns {number} -1 if a comes before b, 1 if a comes after b, 0 if equal.
  206. * @private
  207. */
  208. function compareFixesByRange(a, b) {
  209. return a.range[0] - b.range[0] || a.range[1] - b.range[1];
  210. }
  211. /**
  212. * Merges the given fixes array into one.
  213. * @param {Fix[]} fixes The fixes to merge.
  214. * @param {SourceCode} sourceCode The source code object to get the text between fixes.
  215. * @returns {{text: string, range: number[]}} The merged fixes
  216. */
  217. function mergeFixes(fixes, sourceCode) {
  218. for (const fix of fixes) {
  219. assertValidFix(fix);
  220. }
  221. if (fixes.length === 0) {
  222. return null;
  223. }
  224. if (fixes.length === 1) {
  225. return cloneFix(fixes[0]);
  226. }
  227. fixes.sort(compareFixesByRange);
  228. const originalText = sourceCode.text;
  229. const start = fixes[0].range[0];
  230. const end = fixes.at(-1).range[1];
  231. let text = "";
  232. let lastPos = Number.MIN_SAFE_INTEGER;
  233. for (const fix of fixes) {
  234. assert(
  235. fix.range[0] >= lastPos,
  236. "Fix objects must not be overlapped in a report.",
  237. );
  238. if (fix.range[0] >= 0) {
  239. text += originalText.slice(
  240. Math.max(0, start, lastPos),
  241. fix.range[0],
  242. );
  243. }
  244. text += fix.text;
  245. lastPos = fix.range[1];
  246. }
  247. text += originalText.slice(Math.max(0, start, lastPos), end);
  248. return { range: [start, end], text };
  249. }
  250. /**
  251. * Gets one fix object from the given descriptor.
  252. * If the descriptor retrieves multiple fixes, this merges those to one.
  253. * @param {MessageDescriptor} descriptor The report descriptor.
  254. * @param {SourceCode} sourceCode The source code object to get text between fixes.
  255. * @returns {({text: string, range: number[]}|null)} The fix for the descriptor
  256. */
  257. function normalizeFixes(descriptor, sourceCode) {
  258. if (typeof descriptor.fix !== "function") {
  259. return null;
  260. }
  261. const ruleFixer = new RuleFixer({ sourceCode });
  262. // @type {null | Fix | Fix[] | IterableIterator<Fix>}
  263. const fix = descriptor.fix(ruleFixer);
  264. // Merge to one.
  265. if (fix && Symbol.iterator in fix) {
  266. return mergeFixes(Array.from(fix), sourceCode);
  267. }
  268. assertValidFix(fix);
  269. return cloneFix(fix);
  270. }
  271. /**
  272. * Gets an array of suggestion objects from the given descriptor.
  273. * @param {MessageDescriptor} descriptor The report descriptor.
  274. * @param {SourceCode} sourceCode The source code object to get text between fixes.
  275. * @param {Object} messages Object of meta messages for the rule.
  276. * @returns {Array<SuggestionResult>} The suggestions for the descriptor
  277. */
  278. function mapSuggestions(descriptor, sourceCode, messages) {
  279. if (!descriptor.suggest || !Array.isArray(descriptor.suggest)) {
  280. return [];
  281. }
  282. return (
  283. descriptor.suggest
  284. .map(suggestInfo => {
  285. const computedDesc =
  286. suggestInfo.desc || messages[suggestInfo.messageId];
  287. return {
  288. ...suggestInfo,
  289. desc: interpolate(computedDesc, suggestInfo.data),
  290. fix: normalizeFixes(suggestInfo, sourceCode),
  291. };
  292. })
  293. // Remove suggestions that didn't provide a fix
  294. .filter(({ fix }) => fix)
  295. );
  296. }
  297. /**
  298. * Creates information about the report from a descriptor
  299. * @param {Object} options Information about the problem
  300. * @param {string} options.ruleId Rule ID
  301. * @param {(0|1|2)} options.severity Rule severity
  302. * @param {(ASTNode|null)} options.node Node
  303. * @param {string} options.message Error message
  304. * @param {string} [options.messageId] The error message ID.
  305. * @param {{start: SourceLocation, end: (SourceLocation|null)}} options.loc Start and end location
  306. * @param {{text: string, range: (number[]|null)}} options.fix The fix object
  307. * @param {Array<{text: string, range: (number[]|null)}>} options.suggestions The array of suggestions objects
  308. * @param {Language} [options.language] The language to use to adjust line and column offsets.
  309. * @returns {LintMessage} Information about the report
  310. */
  311. function createProblem(options) {
  312. const { language } = options;
  313. // calculate offsets based on the language in use
  314. const columnOffset = language.columnStart === 1 ? 0 : 1;
  315. const lineOffset = language.lineStart === 1 ? 0 : 1;
  316. const problem = {
  317. ruleId: options.ruleId,
  318. severity: options.severity,
  319. message: options.message,
  320. line: options.loc.start.line + lineOffset,
  321. column: options.loc.start.column + columnOffset,
  322. nodeType: (options.node && options.node.type) || null,
  323. };
  324. /*
  325. * If this isn’t in the conditional, some of the tests fail
  326. * because `messageId` is present in the problem object
  327. */
  328. if (options.messageId) {
  329. problem.messageId = options.messageId;
  330. }
  331. if (options.loc.end) {
  332. problem.endLine = options.loc.end.line + lineOffset;
  333. problem.endColumn = options.loc.end.column + columnOffset;
  334. }
  335. if (options.fix) {
  336. problem.fix = options.fix;
  337. }
  338. if (options.suggestions && options.suggestions.length > 0) {
  339. problem.suggestions = options.suggestions;
  340. }
  341. return problem;
  342. }
  343. /**
  344. * Validates that suggestions are properly defined. Throws if an error is detected.
  345. * @param {Array<{ desc?: string, messageId?: string }>} suggest The incoming suggest data.
  346. * @param {Object} messages Object of meta messages for the rule.
  347. * @returns {void}
  348. */
  349. function validateSuggestions(suggest, messages) {
  350. if (suggest && Array.isArray(suggest)) {
  351. suggest.forEach(suggestion => {
  352. if (suggestion.messageId) {
  353. const { messageId } = suggestion;
  354. if (!messages) {
  355. throw new TypeError(
  356. `context.report() called with a suggest option with a messageId '${messageId}', but no messages were present in the rule metadata.`,
  357. );
  358. }
  359. if (!messages[messageId]) {
  360. throw new TypeError(
  361. `context.report() called with a suggest option with a messageId '${messageId}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`,
  362. );
  363. }
  364. if (suggestion.desc) {
  365. throw new TypeError(
  366. "context.report() called with a suggest option that defines both a 'messageId' and an 'desc'. Please only pass one.",
  367. );
  368. }
  369. } else if (!suggestion.desc) {
  370. throw new TypeError(
  371. "context.report() called with a suggest option that doesn't have either a `desc` or `messageId`",
  372. );
  373. }
  374. if (typeof suggestion.fix !== "function") {
  375. throw new TypeError(
  376. `context.report() called with a suggest option without a fix function. See: ${JSON.stringify(suggestion, null, 2)}`,
  377. );
  378. }
  379. });
  380. }
  381. }
  382. /**
  383. * Computes the message from a report descriptor.
  384. * @param {MessageDescriptor} descriptor The report descriptor.
  385. * @param {Object} messages Object of meta messages for the rule.
  386. * @returns {string} The computed message.
  387. * @throws {TypeError} If messageId is not found or both message and messageId are provided.
  388. */
  389. function computeMessageFromDescriptor(descriptor, messages) {
  390. if (descriptor.messageId) {
  391. if (!messages) {
  392. throw new TypeError(
  393. "context.report() called with a messageId, but no messages were present in the rule metadata.",
  394. );
  395. }
  396. const id = descriptor.messageId;
  397. if (descriptor.message) {
  398. throw new TypeError(
  399. "context.report() called with a message and a messageId. Please only pass one.",
  400. );
  401. }
  402. if (!messages || !Object.hasOwn(messages, id)) {
  403. throw new TypeError(
  404. `context.report() called with a messageId of '${id}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`,
  405. );
  406. }
  407. return messages[id];
  408. }
  409. if (descriptor.message) {
  410. return descriptor.message;
  411. }
  412. throw new TypeError(
  413. "Missing `message` property in report() call; add a message that describes the linting problem.",
  414. );
  415. }
  416. /**
  417. * A report object that contains the messages reported the linter
  418. * for a file.
  419. */
  420. class FileReport {
  421. /**
  422. * The messages reported by the linter for this file.
  423. * @type {LintMessage[]}
  424. */
  425. messages = [];
  426. /**
  427. * A rule mapper that maps rule IDs to their metadata.
  428. * @type {(string) => RuleDefinition}
  429. */
  430. #ruleMapper;
  431. /**
  432. * The source code object for the file.
  433. * @type {SourceCode}
  434. */
  435. #sourceCode;
  436. /**
  437. * The language to use to adjust line and column offsets.
  438. * @type {Language}
  439. */
  440. #language;
  441. /**
  442. * Whether to disable fixes for this report.
  443. * @type {boolean}
  444. */
  445. #disableFixes;
  446. /**
  447. * Creates a new FileReport instance.
  448. * @param {Object} options The options for the file report
  449. * @param {(string) => RuleDefinition} options.ruleMapper A rule mapper that maps rule IDs to their metadata.
  450. * @param {SourceCode} options.sourceCode The source code object for the file.
  451. * @param {Language} options.language The language to use to adjust line and column offsets.
  452. * @param {boolean} [options.disableFixes=false] Whether to disable fixes for this report.
  453. */
  454. constructor({ ruleMapper, sourceCode, language, disableFixes = false }) {
  455. this.#ruleMapper = ruleMapper;
  456. this.#sourceCode = sourceCode;
  457. this.#language = language;
  458. this.#disableFixes = disableFixes;
  459. }
  460. /**
  461. * Adds a rule-generated message to the report.
  462. * @param {string} ruleId The rule ID that reported the problem.
  463. * @param {0|1|2} severity The severity of the problem (0 = off, 1 = warning, 2 = error).
  464. * @param {...*} args The arguments passed to `context.report()`.
  465. * @returns {LintMessage} The created message object.
  466. * @throws {TypeError} If the messageId is not found or both message and messageId are provided.
  467. * @throws {AssertionError} If the node is not an object or neither a node nor a loc is provided.
  468. */
  469. addRuleMessage(ruleId, severity, ...args) {
  470. const descriptor = normalizeMultiArgReportCall(...args);
  471. const ruleDefinition = this.#ruleMapper(ruleId);
  472. const messages = ruleDefinition?.meta?.messages;
  473. assertValidNodeInfo(descriptor);
  474. const computedMessage = computeMessageFromDescriptor(
  475. descriptor,
  476. messages,
  477. );
  478. validateSuggestions(descriptor.suggest, messages);
  479. this.messages.push(
  480. createProblem({
  481. ruleId,
  482. severity,
  483. node: descriptor.node,
  484. message: interpolate(computedMessage, descriptor.data),
  485. messageId: descriptor.messageId,
  486. loc: descriptor.loc
  487. ? normalizeReportLoc(descriptor)
  488. : this.#sourceCode.getLoc(descriptor.node),
  489. fix: this.#disableFixes
  490. ? null
  491. : normalizeFixes(descriptor, this.#sourceCode),
  492. suggestions: this.#disableFixes
  493. ? []
  494. : mapSuggestions(descriptor, this.#sourceCode, messages),
  495. language: this.#language,
  496. }),
  497. );
  498. return this.messages.at(-1);
  499. }
  500. /**
  501. * Adds an error message to the report. Meant to be called outside of rules.
  502. * @param {LintProblem} descriptor The descriptor for the error message.
  503. * @returns {LintMessage} The created message object.
  504. */
  505. addError(descriptor) {
  506. const message = createLintingProblem(descriptor, 2, this.#language);
  507. this.messages.push(message);
  508. return message;
  509. }
  510. /**
  511. * Adds a fatal error message to the report. Meant to be called outside of rules.
  512. * @param {LintProblem} descriptor The descriptor for the fatal error message.
  513. * @returns {LintMessage} The created message object.
  514. */
  515. addFatal(descriptor) {
  516. const message = createLintingProblem(descriptor, 2, this.#language);
  517. message.fatal = true;
  518. this.messages.push(message);
  519. return message;
  520. }
  521. /**
  522. * Adds a warning message to the report. Meant to be called outside of rules.
  523. * @param {LintProblem} descriptor The descriptor for the warning message.
  524. * @returns {LintMessage} The created message object.
  525. */
  526. addWarning(descriptor) {
  527. const message = createLintingProblem(descriptor, 1, this.#language);
  528. this.messages.push(message);
  529. return message;
  530. }
  531. }
  532. module.exports = {
  533. FileReport,
  534. updateLocationInformation,
  535. };