report-translator.js 13 KB

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