report-translator.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. /**
  2. * @fileoverview A helper that translates context.report() calls from the rule API into generic problem objects
  3. * @author Teddy Katz
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const assert = require("node:assert");
  10. const { RuleFixer } = require("./rule-fixer");
  11. const { interpolate } = require("./interpolate");
  12. //------------------------------------------------------------------------------
  13. // Typedefs
  14. //------------------------------------------------------------------------------
  15. /** @typedef {import("../shared/types").LintMessage} LintMessage */
  16. /**
  17. * An error message description
  18. * @typedef {Object} MessageDescriptor
  19. * @property {ASTNode} [node] The reported node
  20. * @property {Location} loc The location of the problem.
  21. * @property {string} message The problem message.
  22. * @property {Object} [data] Optional data to use to fill in placeholders in the
  23. * message.
  24. * @property {Function} [fix] The function to call that creates a fix command.
  25. * @property {Array<{desc?: string, messageId?: string, fix: Function}>} suggest Suggestion descriptions and functions to create a the associated fixes.
  26. */
  27. //------------------------------------------------------------------------------
  28. // Module Definition
  29. //------------------------------------------------------------------------------
  30. /**
  31. * Translates a multi-argument context.report() call into a single object argument call
  32. * @param {...*} args A list of arguments passed to `context.report`
  33. * @returns {MessageDescriptor} A normalized object containing report information
  34. */
  35. function normalizeMultiArgReportCall(...args) {
  36. // If there is one argument, it is considered to be a new-style call already.
  37. if (args.length === 1) {
  38. // Shallow clone the object to avoid surprises if reusing the descriptor
  39. return Object.assign({}, args[0]);
  40. }
  41. // If the second argument is a string, the arguments are interpreted as [node, message, data, fix].
  42. if (typeof args[1] === "string") {
  43. return {
  44. node: args[0],
  45. message: args[1],
  46. data: args[2],
  47. fix: args[3]
  48. };
  49. }
  50. // Otherwise, the arguments are interpreted as [node, loc, message, data, fix].
  51. return {
  52. node: args[0],
  53. loc: args[1],
  54. message: args[2],
  55. data: args[3],
  56. fix: args[4]
  57. };
  58. }
  59. /**
  60. * Asserts that either a loc or a node was provided, and the node is valid if it was provided.
  61. * @param {MessageDescriptor} descriptor A descriptor to validate
  62. * @returns {void}
  63. * @throws AssertionError if neither a node nor a loc was provided, or if the node is not an object
  64. */
  65. function assertValidNodeInfo(descriptor) {
  66. if (descriptor.node) {
  67. assert(typeof descriptor.node === "object", "Node must be an object");
  68. } else {
  69. assert(descriptor.loc, "Node must be provided when reporting error if location is not provided");
  70. }
  71. }
  72. /**
  73. * Normalizes a MessageDescriptor to always have a `loc` with `start` and `end` properties
  74. * @param {MessageDescriptor} descriptor A descriptor for the report from a rule.
  75. * @returns {{start: Location, end: (Location|null)}} An updated location that infers the `start` and `end` properties
  76. * from the `node` of the original descriptor, or infers the `start` from the `loc` of the original descriptor.
  77. */
  78. function normalizeReportLoc(descriptor) {
  79. if (descriptor.loc.start) {
  80. return descriptor.loc;
  81. }
  82. return { start: descriptor.loc, end: null };
  83. }
  84. /**
  85. * Clones the given fix object.
  86. * @param {Fix|null} fix The fix to clone.
  87. * @returns {Fix|null} Deep cloned fix object or `null` if `null` or `undefined` was passed in.
  88. */
  89. function cloneFix(fix) {
  90. if (!fix) {
  91. return null;
  92. }
  93. return {
  94. range: [fix.range[0], fix.range[1]],
  95. text: fix.text
  96. };
  97. }
  98. /**
  99. * Check that a fix has a valid range.
  100. * @param {Fix|null} fix The fix to validate.
  101. * @returns {void}
  102. */
  103. function assertValidFix(fix) {
  104. if (fix) {
  105. assert(fix.range && typeof fix.range[0] === "number" && typeof fix.range[1] === "number", `Fix has invalid range: ${JSON.stringify(fix, null, 2)}`);
  106. }
  107. }
  108. /**
  109. * Compares items in a fixes array by range.
  110. * @param {Fix} a The first message.
  111. * @param {Fix} b The second message.
  112. * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal.
  113. * @private
  114. */
  115. function compareFixesByRange(a, b) {
  116. return a.range[0] - b.range[0] || a.range[1] - b.range[1];
  117. }
  118. /**
  119. * Merges the given fixes array into one.
  120. * @param {Fix[]} fixes The fixes to merge.
  121. * @param {SourceCode} sourceCode The source code object to get the text between fixes.
  122. * @returns {{text: string, range: number[]}} The merged fixes
  123. */
  124. function mergeFixes(fixes, sourceCode) {
  125. for (const fix of fixes) {
  126. assertValidFix(fix);
  127. }
  128. if (fixes.length === 0) {
  129. return null;
  130. }
  131. if (fixes.length === 1) {
  132. return cloneFix(fixes[0]);
  133. }
  134. fixes.sort(compareFixesByRange);
  135. const originalText = sourceCode.text;
  136. const start = fixes[0].range[0];
  137. const end = fixes.at(-1).range[1];
  138. let text = "";
  139. let lastPos = Number.MIN_SAFE_INTEGER;
  140. for (const fix of fixes) {
  141. assert(fix.range[0] >= lastPos, "Fix objects must not be overlapped in a report.");
  142. if (fix.range[0] >= 0) {
  143. text += originalText.slice(Math.max(0, start, lastPos), fix.range[0]);
  144. }
  145. text += fix.text;
  146. lastPos = fix.range[1];
  147. }
  148. text += originalText.slice(Math.max(0, start, lastPos), end);
  149. return { range: [start, end], text };
  150. }
  151. /**
  152. * Gets one fix object from the given descriptor.
  153. * If the descriptor retrieves multiple fixes, this merges those to one.
  154. * @param {MessageDescriptor} descriptor The report descriptor.
  155. * @param {SourceCode} sourceCode The source code object to get text between fixes.
  156. * @returns {({text: string, range: number[]}|null)} The fix for the descriptor
  157. */
  158. function normalizeFixes(descriptor, sourceCode) {
  159. if (typeof descriptor.fix !== "function") {
  160. return null;
  161. }
  162. const ruleFixer = new RuleFixer({ sourceCode });
  163. // @type {null | Fix | Fix[] | IterableIterator<Fix>}
  164. const fix = descriptor.fix(ruleFixer);
  165. // Merge to one.
  166. if (fix && Symbol.iterator in fix) {
  167. return mergeFixes(Array.from(fix), sourceCode);
  168. }
  169. assertValidFix(fix);
  170. return cloneFix(fix);
  171. }
  172. /**
  173. * Gets an array of suggestion objects from the given descriptor.
  174. * @param {MessageDescriptor} descriptor The report descriptor.
  175. * @param {SourceCode} sourceCode The source code object to get text between fixes.
  176. * @param {Object} messages Object of meta messages for the rule.
  177. * @returns {Array<SuggestionResult>} The suggestions for the descriptor
  178. */
  179. function mapSuggestions(descriptor, sourceCode, messages) {
  180. if (!descriptor.suggest || !Array.isArray(descriptor.suggest)) {
  181. return [];
  182. }
  183. return descriptor.suggest
  184. .map(suggestInfo => {
  185. const computedDesc = suggestInfo.desc || messages[suggestInfo.messageId];
  186. return {
  187. ...suggestInfo,
  188. desc: interpolate(computedDesc, suggestInfo.data),
  189. fix: normalizeFixes(suggestInfo, sourceCode)
  190. };
  191. })
  192. // Remove suggestions that didn't provide a fix
  193. .filter(({ fix }) => fix);
  194. }
  195. /**
  196. * Creates information about the report from a descriptor
  197. * @param {Object} options Information about the problem
  198. * @param {string} options.ruleId Rule ID
  199. * @param {(0|1|2)} options.severity Rule severity
  200. * @param {(ASTNode|null)} options.node Node
  201. * @param {string} options.message Error message
  202. * @param {string} [options.messageId] The error message ID.
  203. * @param {{start: SourceLocation, end: (SourceLocation|null)}} options.loc Start and end location
  204. * @param {{text: string, range: (number[]|null)}} options.fix The fix object
  205. * @param {Array<{text: string, range: (number[]|null)}>} options.suggestions The array of suggestions objects
  206. * @param {Language} [options.language] The language to use to adjust line and column offsets.
  207. * @returns {LintMessage} Information about the report
  208. */
  209. function createProblem(options) {
  210. const { language } = options;
  211. // calculate offsets based on the language in use
  212. const columnOffset = language.columnStart === 1 ? 0 : 1;
  213. const lineOffset = language.lineStart === 1 ? 0 : 1;
  214. const problem = {
  215. ruleId: options.ruleId,
  216. severity: options.severity,
  217. message: options.message,
  218. line: options.loc.start.line + lineOffset,
  219. column: options.loc.start.column + columnOffset,
  220. nodeType: options.node && options.node.type || null
  221. };
  222. /*
  223. * If this isn’t in the conditional, some of the tests fail
  224. * because `messageId` is present in the problem object
  225. */
  226. if (options.messageId) {
  227. problem.messageId = options.messageId;
  228. }
  229. if (options.loc.end) {
  230. problem.endLine = options.loc.end.line + lineOffset;
  231. problem.endColumn = options.loc.end.column + columnOffset;
  232. }
  233. if (options.fix) {
  234. problem.fix = options.fix;
  235. }
  236. if (options.suggestions && options.suggestions.length > 0) {
  237. problem.suggestions = options.suggestions;
  238. }
  239. return problem;
  240. }
  241. /**
  242. * Validates that suggestions are properly defined. Throws if an error is detected.
  243. * @param {Array<{ desc?: string, messageId?: string }>} suggest The incoming suggest data.
  244. * @param {Object} messages Object of meta messages for the rule.
  245. * @returns {void}
  246. */
  247. function validateSuggestions(suggest, messages) {
  248. if (suggest && Array.isArray(suggest)) {
  249. suggest.forEach(suggestion => {
  250. if (suggestion.messageId) {
  251. const { messageId } = suggestion;
  252. if (!messages) {
  253. throw new TypeError(`context.report() called with a suggest option with a messageId '${messageId}', but no messages were present in the rule metadata.`);
  254. }
  255. if (!messages[messageId]) {
  256. throw new TypeError(`context.report() called with a suggest option with a messageId '${messageId}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`);
  257. }
  258. if (suggestion.desc) {
  259. throw new TypeError("context.report() called with a suggest option that defines both a 'messageId' and an 'desc'. Please only pass one.");
  260. }
  261. } else if (!suggestion.desc) {
  262. throw new TypeError("context.report() called with a suggest option that doesn't have either a `desc` or `messageId`");
  263. }
  264. if (typeof suggestion.fix !== "function") {
  265. throw new TypeError(`context.report() called with a suggest option without a fix function. See: ${suggestion}`);
  266. }
  267. });
  268. }
  269. }
  270. /**
  271. * Returns a function that converts the arguments of a `context.report` call from a rule into a reported
  272. * problem for the Node.js API.
  273. * @param {{ruleId: string, severity: number, sourceCode: SourceCode, messageIds: Object, disableFixes: boolean, language:Language}} metadata Metadata for the reported problem
  274. * @returns {function(...args): LintMessage} Function that returns information about the report
  275. */
  276. module.exports = function createReportTranslator(metadata) {
  277. /*
  278. * `createReportTranslator` gets called once per enabled rule per file. It needs to be very performant.
  279. * The report translator itself (i.e. the function that `createReportTranslator` returns) gets
  280. * called every time a rule reports a problem, which happens much less frequently (usually, the vast
  281. * majority of rules don't report any problems for a given file).
  282. */
  283. return (...args) => {
  284. const descriptor = normalizeMultiArgReportCall(...args);
  285. const messages = metadata.messageIds;
  286. const { sourceCode } = metadata;
  287. assertValidNodeInfo(descriptor);
  288. let computedMessage;
  289. if (descriptor.messageId) {
  290. if (!messages) {
  291. throw new TypeError("context.report() called with a messageId, but no messages were present in the rule metadata.");
  292. }
  293. const id = descriptor.messageId;
  294. if (descriptor.message) {
  295. throw new TypeError("context.report() called with a message and a messageId. Please only pass one.");
  296. }
  297. if (!messages || !Object.hasOwn(messages, id)) {
  298. throw new TypeError(`context.report() called with a messageId of '${id}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`);
  299. }
  300. computedMessage = messages[id];
  301. } else if (descriptor.message) {
  302. computedMessage = descriptor.message;
  303. } else {
  304. throw new TypeError("Missing `message` property in report() call; add a message that describes the linting problem.");
  305. }
  306. validateSuggestions(descriptor.suggest, messages);
  307. return createProblem({
  308. ruleId: metadata.ruleId,
  309. severity: metadata.severity,
  310. node: descriptor.node,
  311. message: interpolate(computedMessage, descriptor.data),
  312. messageId: descriptor.messageId,
  313. loc: descriptor.loc ? normalizeReportLoc(descriptor) : sourceCode.getLoc(descriptor.node),
  314. fix: metadata.disableFixes ? null : normalizeFixes(descriptor, sourceCode),
  315. suggestions: metadata.disableFixes ? [] : mapSuggestions(descriptor, sourceCode, messages),
  316. language: metadata.language
  317. });
  318. };
  319. };