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.

report-translator.js 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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("./util/rule-fixer");
  11. const interpolate = require("./util/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. */
  25. /**
  26. * Information about the report
  27. * @typedef {Object} ReportInfo
  28. * @property {string} ruleId
  29. * @property {(0|1|2)} severity
  30. * @property {(string|undefined)} message
  31. * @property {(string|undefined)} messageId
  32. * @property {number} line
  33. * @property {number} column
  34. * @property {(number|undefined)} endLine
  35. * @property {(number|undefined)} endColumn
  36. * @property {(string|null)} nodeType
  37. * @property {string} source
  38. * @property {({text: string, range: (number[]|null)}|null)} fix
  39. */
  40. //------------------------------------------------------------------------------
  41. // Module Definition
  42. //------------------------------------------------------------------------------
  43. /**
  44. * Translates a multi-argument context.report() call into a single object argument call
  45. * @param {...*} args A list of arguments passed to `context.report`
  46. * @returns {MessageDescriptor} A normalized object containing report information
  47. */
  48. function normalizeMultiArgReportCall(...args) {
  49. // If there is one argument, it is considered to be a new-style call already.
  50. if (args.length === 1) {
  51. // Shallow clone the object to avoid surprises if reusing the descriptor
  52. return Object.assign({}, args[0]);
  53. }
  54. // If the second argument is a string, the arguments are interpreted as [node, message, data, fix].
  55. if (typeof args[1] === "string") {
  56. return {
  57. node: args[0],
  58. message: args[1],
  59. data: args[2],
  60. fix: args[3]
  61. };
  62. }
  63. // Otherwise, the arguments are interpreted as [node, loc, message, data, fix].
  64. return {
  65. node: args[0],
  66. loc: args[1],
  67. message: args[2],
  68. data: args[3],
  69. fix: args[4]
  70. };
  71. }
  72. /**
  73. * Asserts that either a loc or a node was provided, and the node is valid if it was provided.
  74. * @param {MessageDescriptor} descriptor A descriptor to validate
  75. * @returns {void}
  76. * @throws AssertionError if neither a node nor a loc was provided, or if the node is not an object
  77. */
  78. function assertValidNodeInfo(descriptor) {
  79. if (descriptor.node) {
  80. assert(typeof descriptor.node === "object", "Node must be an object");
  81. } else {
  82. assert(descriptor.loc, "Node must be provided when reporting error if location is not provided");
  83. }
  84. }
  85. /**
  86. * Normalizes a MessageDescriptor to always have a `loc` with `start` and `end` properties
  87. * @param {MessageDescriptor} descriptor A descriptor for the report from a rule.
  88. * @returns {{start: Location, end: (Location|null)}} An updated location that infers the `start` and `end` properties
  89. * from the `node` of the original descriptor, or infers the `start` from the `loc` of the original descriptor.
  90. */
  91. function normalizeReportLoc(descriptor) {
  92. if (descriptor.loc) {
  93. if (descriptor.loc.start) {
  94. return descriptor.loc;
  95. }
  96. return { start: descriptor.loc, end: null };
  97. }
  98. return descriptor.node.loc;
  99. }
  100. /**
  101. * Compares items in a fixes array by range.
  102. * @param {Fix} a The first message.
  103. * @param {Fix} b The second message.
  104. * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal.
  105. * @private
  106. */
  107. function compareFixesByRange(a, b) {
  108. return a.range[0] - b.range[0] || a.range[1] - b.range[1];
  109. }
  110. /**
  111. * Merges the given fixes array into one.
  112. * @param {Fix[]} fixes The fixes to merge.
  113. * @param {SourceCode} sourceCode The source code object to get the text between fixes.
  114. * @returns {{text: string, range: number[]}} The merged fixes
  115. */
  116. function mergeFixes(fixes, sourceCode) {
  117. if (fixes.length === 0) {
  118. return null;
  119. }
  120. if (fixes.length === 1) {
  121. return fixes[0];
  122. }
  123. fixes.sort(compareFixesByRange);
  124. const originalText = sourceCode.text;
  125. const start = fixes[0].range[0];
  126. const end = fixes[fixes.length - 1].range[1];
  127. let text = "";
  128. let lastPos = Number.MIN_SAFE_INTEGER;
  129. for (const fix of fixes) {
  130. assert(fix.range[0] >= lastPos, "Fix objects must not be overlapped in a report.");
  131. if (fix.range[0] >= 0) {
  132. text += originalText.slice(Math.max(0, start, lastPos), fix.range[0]);
  133. }
  134. text += fix.text;
  135. lastPos = fix.range[1];
  136. }
  137. text += originalText.slice(Math.max(0, start, lastPos), end);
  138. return { range: [start, end], text };
  139. }
  140. /**
  141. * Gets one fix object from the given descriptor.
  142. * If the descriptor retrieves multiple fixes, this merges those to one.
  143. * @param {MessageDescriptor} descriptor The report descriptor.
  144. * @param {SourceCode} sourceCode The source code object to get text between fixes.
  145. * @returns {({text: string, range: number[]}|null)} The fix for the descriptor
  146. */
  147. function normalizeFixes(descriptor, sourceCode) {
  148. if (typeof descriptor.fix !== "function") {
  149. return null;
  150. }
  151. // @type {null | Fix | Fix[] | IterableIterator<Fix>}
  152. const fix = descriptor.fix(ruleFixer);
  153. // Merge to one.
  154. if (fix && Symbol.iterator in fix) {
  155. return mergeFixes(Array.from(fix), sourceCode);
  156. }
  157. return fix;
  158. }
  159. /**
  160. * Creates information about the report from a descriptor
  161. * @param {Object} options Information about the problem
  162. * @param {string} options.ruleId Rule ID
  163. * @param {(0|1|2)} options.severity Rule severity
  164. * @param {(ASTNode|null)} options.node Node
  165. * @param {string} options.message Error message
  166. * @param {string} [options.messageId] The error message ID.
  167. * @param {{start: SourceLocation, end: (SourceLocation|null)}} options.loc Start and end location
  168. * @param {{text: string, range: (number[]|null)}} options.fix The fix object
  169. * @returns {function(...args): ReportInfo} Function that returns information about the report
  170. */
  171. function createProblem(options) {
  172. const problem = {
  173. ruleId: options.ruleId,
  174. severity: options.severity,
  175. message: options.message,
  176. line: options.loc.start.line,
  177. column: options.loc.start.column + 1,
  178. nodeType: options.node && options.node.type || null
  179. };
  180. /*
  181. * If this isn’t in the conditional, some of the tests fail
  182. * because `messageId` is present in the problem object
  183. */
  184. if (options.messageId) {
  185. problem.messageId = options.messageId;
  186. }
  187. if (options.loc.end) {
  188. problem.endLine = options.loc.end.line;
  189. problem.endColumn = options.loc.end.column + 1;
  190. }
  191. if (options.fix) {
  192. problem.fix = options.fix;
  193. }
  194. return problem;
  195. }
  196. /**
  197. * Returns a function that converts the arguments of a `context.report` call from a rule into a reported
  198. * problem for the Node.js API.
  199. * @param {{ruleId: string, severity: number, sourceCode: SourceCode, messageIds: Object}} metadata Metadata for the reported problem
  200. * @param {SourceCode} sourceCode The `SourceCode` instance for the text being linted
  201. * @returns {function(...args): ReportInfo} Function that returns information about the report
  202. */
  203. module.exports = function createReportTranslator(metadata) {
  204. /*
  205. * `createReportTranslator` gets called once per enabled rule per file. It needs to be very performant.
  206. * The report translator itself (i.e. the function that `createReportTranslator` returns) gets
  207. * called every time a rule reports a problem, which happens much less frequently (usually, the vast
  208. * majority of rules don't report any problems for a given file).
  209. */
  210. return (...args) => {
  211. const descriptor = normalizeMultiArgReportCall(...args);
  212. assertValidNodeInfo(descriptor);
  213. let computedMessage;
  214. if (descriptor.messageId) {
  215. if (!metadata.messageIds) {
  216. throw new TypeError("context.report() called with a messageId, but no messages were present in the rule metadata.");
  217. }
  218. const id = descriptor.messageId;
  219. const messages = metadata.messageIds;
  220. if (descriptor.message) {
  221. throw new TypeError("context.report() called with a message and a messageId. Please only pass one.");
  222. }
  223. if (!messages || !Object.prototype.hasOwnProperty.call(messages, id)) {
  224. throw new TypeError(`context.report() called with a messageId of '${id}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`);
  225. }
  226. computedMessage = messages[id];
  227. } else if (descriptor.message) {
  228. computedMessage = descriptor.message;
  229. } else {
  230. throw new TypeError("Missing `message` property in report() call; add a message that describes the linting problem.");
  231. }
  232. return createProblem({
  233. ruleId: metadata.ruleId,
  234. severity: metadata.severity,
  235. node: descriptor.node,
  236. message: interpolate(computedMessage, descriptor.data),
  237. messageId: descriptor.messageId,
  238. loc: normalizeReportLoc(descriptor),
  239. fix: normalizeFixes(descriptor, metadata.sourceCode)
  240. });
  241. };
  242. };