report-translator.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. * Compares items in a fixes array by range.
  104. * @param {Fix} a The first message.
  105. * @param {Fix} b The second message.
  106. * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal.
  107. * @private
  108. */
  109. function compareFixesByRange(a, b) {
  110. return a.range[0] - b.range[0] || a.range[1] - b.range[1];
  111. }
  112. /**
  113. * Merges the given fixes array into one.
  114. * @param {Fix[]} fixes The fixes to merge.
  115. * @param {SourceCode} sourceCode The source code object to get the text between fixes.
  116. * @returns {{text: string, range: number[]}} The merged fixes
  117. */
  118. function mergeFixes(fixes, sourceCode) {
  119. if (fixes.length === 0) {
  120. return null;
  121. }
  122. if (fixes.length === 1) {
  123. return fixes[0];
  124. }
  125. fixes.sort(compareFixesByRange);
  126. const originalText = sourceCode.text;
  127. const start = fixes[0].range[0];
  128. const end = fixes[fixes.length - 1].range[1];
  129. let text = "";
  130. let lastPos = Number.MIN_SAFE_INTEGER;
  131. for (const fix of fixes) {
  132. assert(fix.range[0] >= lastPos, "Fix objects must not be overlapped in a report.");
  133. if (fix.range[0] >= 0) {
  134. text += originalText.slice(Math.max(0, start, lastPos), fix.range[0]);
  135. }
  136. text += fix.text;
  137. lastPos = fix.range[1];
  138. }
  139. text += originalText.slice(Math.max(0, start, lastPos), end);
  140. return { range: [start, end], text };
  141. }
  142. /**
  143. * Gets one fix object from the given descriptor.
  144. * If the descriptor retrieves multiple fixes, this merges those to one.
  145. * @param {MessageDescriptor} descriptor The report descriptor.
  146. * @param {SourceCode} sourceCode The source code object to get text between fixes.
  147. * @returns {({text: string, range: number[]}|null)} The fix for the descriptor
  148. */
  149. function normalizeFixes(descriptor, sourceCode) {
  150. if (typeof descriptor.fix !== "function") {
  151. return null;
  152. }
  153. // @type {null | Fix | Fix[] | IterableIterator<Fix>}
  154. const fix = descriptor.fix(ruleFixer);
  155. // Merge to one.
  156. if (fix && Symbol.iterator in fix) {
  157. return mergeFixes(Array.from(fix), sourceCode);
  158. }
  159. return fix;
  160. }
  161. /**
  162. * Gets an array of suggestion objects from the given descriptor.
  163. * @param {MessageDescriptor} descriptor The report descriptor.
  164. * @param {SourceCode} sourceCode The source code object to get text between fixes.
  165. * @param {Object} messages Object of meta messages for the rule.
  166. * @returns {Array<SuggestionResult>} The suggestions for the descriptor
  167. */
  168. function mapSuggestions(descriptor, sourceCode, messages) {
  169. if (!descriptor.suggest || !Array.isArray(descriptor.suggest)) {
  170. return [];
  171. }
  172. return descriptor.suggest.map(suggestInfo => {
  173. const computedDesc = suggestInfo.desc || messages[suggestInfo.messageId];
  174. return {
  175. ...suggestInfo,
  176. desc: interpolate(computedDesc, suggestInfo.data),
  177. fix: normalizeFixes(suggestInfo, sourceCode)
  178. };
  179. });
  180. }
  181. /**
  182. * Creates information about the report from a descriptor
  183. * @param {Object} options Information about the problem
  184. * @param {string} options.ruleId Rule ID
  185. * @param {(0|1|2)} options.severity Rule severity
  186. * @param {(ASTNode|null)} options.node Node
  187. * @param {string} options.message Error message
  188. * @param {string} [options.messageId] The error message ID.
  189. * @param {{start: SourceLocation, end: (SourceLocation|null)}} options.loc Start and end location
  190. * @param {{text: string, range: (number[]|null)}} options.fix The fix object
  191. * @param {Array<{text: string, range: (number[]|null)}>} options.suggestions The array of suggestions objects
  192. * @returns {function(...args): ReportInfo} Function that returns information about the report
  193. */
  194. function createProblem(options) {
  195. const problem = {
  196. ruleId: options.ruleId,
  197. severity: options.severity,
  198. message: options.message,
  199. line: options.loc.start.line,
  200. column: options.loc.start.column + 1,
  201. nodeType: options.node && options.node.type || null
  202. };
  203. /*
  204. * If this isn’t in the conditional, some of the tests fail
  205. * because `messageId` is present in the problem object
  206. */
  207. if (options.messageId) {
  208. problem.messageId = options.messageId;
  209. }
  210. if (options.loc.end) {
  211. problem.endLine = options.loc.end.line;
  212. problem.endColumn = options.loc.end.column + 1;
  213. }
  214. if (options.fix) {
  215. problem.fix = options.fix;
  216. }
  217. if (options.suggestions && options.suggestions.length > 0) {
  218. problem.suggestions = options.suggestions;
  219. }
  220. return problem;
  221. }
  222. /**
  223. * Validates that suggestions are properly defined. Throws if an error is detected.
  224. * @param {Array<{ desc?: string, messageId?: string }>} suggest The incoming suggest data.
  225. * @param {Object} messages Object of meta messages for the rule.
  226. * @returns {void}
  227. */
  228. function validateSuggestions(suggest, messages) {
  229. if (suggest && Array.isArray(suggest)) {
  230. suggest.forEach(suggestion => {
  231. if (suggestion.messageId) {
  232. const { messageId } = suggestion;
  233. if (!messages) {
  234. throw new TypeError(`context.report() called with a suggest option with a messageId '${messageId}', but no messages were present in the rule metadata.`);
  235. }
  236. if (!messages[messageId]) {
  237. 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)}`);
  238. }
  239. if (suggestion.desc) {
  240. throw new TypeError("context.report() called with a suggest option that defines both a 'messageId' and an 'desc'. Please only pass one.");
  241. }
  242. } else if (!suggestion.desc) {
  243. throw new TypeError("context.report() called with a suggest option that doesn't have either a `desc` or `messageId`");
  244. }
  245. if (typeof suggestion.fix !== "function") {
  246. throw new TypeError(`context.report() called with a suggest option without a fix function. See: ${suggestion}`);
  247. }
  248. });
  249. }
  250. }
  251. /**
  252. * Returns a function that converts the arguments of a `context.report` call from a rule into a reported
  253. * problem for the Node.js API.
  254. * @param {{ruleId: string, severity: number, sourceCode: SourceCode, messageIds: Object, disableFixes: boolean}} metadata Metadata for the reported problem
  255. * @param {SourceCode} sourceCode The `SourceCode` instance for the text being linted
  256. * @returns {function(...args): ReportInfo} Function that returns information about the report
  257. */
  258. module.exports = function createReportTranslator(metadata) {
  259. /*
  260. * `createReportTranslator` gets called once per enabled rule per file. It needs to be very performant.
  261. * The report translator itself (i.e. the function that `createReportTranslator` returns) gets
  262. * called every time a rule reports a problem, which happens much less frequently (usually, the vast
  263. * majority of rules don't report any problems for a given file).
  264. */
  265. return (...args) => {
  266. const descriptor = normalizeMultiArgReportCall(...args);
  267. const messages = metadata.messageIds;
  268. assertValidNodeInfo(descriptor);
  269. let computedMessage;
  270. if (descriptor.messageId) {
  271. if (!messages) {
  272. throw new TypeError("context.report() called with a messageId, but no messages were present in the rule metadata.");
  273. }
  274. const id = descriptor.messageId;
  275. if (descriptor.message) {
  276. throw new TypeError("context.report() called with a message and a messageId. Please only pass one.");
  277. }
  278. if (!messages || !Object.prototype.hasOwnProperty.call(messages, id)) {
  279. throw new TypeError(`context.report() called with a messageId of '${id}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`);
  280. }
  281. computedMessage = messages[id];
  282. } else if (descriptor.message) {
  283. computedMessage = descriptor.message;
  284. } else {
  285. throw new TypeError("Missing `message` property in report() call; add a message that describes the linting problem.");
  286. }
  287. validateSuggestions(descriptor.suggest, messages);
  288. return createProblem({
  289. ruleId: metadata.ruleId,
  290. severity: metadata.severity,
  291. node: descriptor.node,
  292. message: interpolate(computedMessage, descriptor.data),
  293. messageId: descriptor.messageId,
  294. loc: normalizeReportLoc(descriptor),
  295. fix: metadata.disableFixes ? null : normalizeFixes(descriptor, metadata.sourceCode),
  296. suggestions: metadata.disableFixes ? [] : mapSuggestions(descriptor, metadata.sourceCode, messages)
  297. });
  298. };
  299. };