项目原始demo,不改动
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
 
 
 
 

287 lines
10 KiB

  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 {...*} arguments A list of arguments passed to `context.report`
  46. * @returns {MessageDescriptor} A normalized object containing report information
  47. */
  48. function normalizeMultiArgReportCall() {
  49. // If there is one argument, it is considered to be a new-style call already.
  50. if (arguments.length === 1) {
  51. // Shallow clone the object to avoid surprises if reusing the descriptor
  52. return Object.assign({}, arguments[0]);
  53. }
  54. // If the second argument is a string, the arguments are interpreted as [node, message, data, fix].
  55. if (typeof arguments[1] === "string") {
  56. return {
  57. node: arguments[0],
  58. message: arguments[1],
  59. data: arguments[2],
  60. fix: arguments[3]
  61. };
  62. }
  63. // Otherwise, the arguments are interpreted as [node, loc, message, data, fix].
  64. return {
  65. node: arguments[0],
  66. loc: arguments[1],
  67. message: arguments[2],
  68. data: arguments[3],
  69. fix: arguments[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. * Interpolates data placeholders in report messages
  102. * @param {MessageDescriptor} descriptor The report message descriptor.
  103. * @returns {string} The interpolated message for the descriptor
  104. */
  105. function normalizeMessagePlaceholders(descriptor) {
  106. return interpolate(descriptor.message, descriptor.data);
  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. if (fixes.length === 0) {
  126. return null;
  127. }
  128. if (fixes.length === 1) {
  129. return fixes[0];
  130. }
  131. fixes.sort(compareFixesByRange);
  132. const originalText = sourceCode.text;
  133. const start = fixes[0].range[0];
  134. const end = fixes[fixes.length - 1].range[1];
  135. let text = "";
  136. let lastPos = Number.MIN_SAFE_INTEGER;
  137. for (const fix of fixes) {
  138. assert(fix.range[0] >= lastPos, "Fix objects must not be overlapped in a report.");
  139. if (fix.range[0] >= 0) {
  140. text += originalText.slice(Math.max(0, start, lastPos), fix.range[0]);
  141. }
  142. text += fix.text;
  143. lastPos = fix.range[1];
  144. }
  145. text += originalText.slice(Math.max(0, start, lastPos), end);
  146. return { range: [start, end], text };
  147. }
  148. /**
  149. * Gets one fix object from the given descriptor.
  150. * If the descriptor retrieves multiple fixes, this merges those to one.
  151. * @param {MessageDescriptor} descriptor The report descriptor.
  152. * @param {SourceCode} sourceCode The source code object to get text between fixes.
  153. * @returns {({text: string, range: number[]}|null)} The fix for the descriptor
  154. */
  155. function normalizeFixes(descriptor, sourceCode) {
  156. if (typeof descriptor.fix !== "function") {
  157. return null;
  158. }
  159. // @type {null | Fix | Fix[] | IterableIterator<Fix>}
  160. const fix = descriptor.fix(ruleFixer);
  161. // Merge to one.
  162. if (fix && Symbol.iterator in fix) {
  163. return mergeFixes(Array.from(fix), sourceCode);
  164. }
  165. return fix;
  166. }
  167. /**
  168. * Creates information about the report from a descriptor
  169. * @param {Object} options Information about the problem
  170. * @param {string} options.ruleId Rule ID
  171. * @param {(0|1|2)} options.severity Rule severity
  172. * @param {(ASTNode|null)} options.node Node
  173. * @param {string} options.message Error message
  174. * @param {{start: SourceLocation, end: (SourceLocation|null)}} options.loc Start and end location
  175. * @param {{text: string, range: (number[]|null)}} options.fix The fix object
  176. * @param {string[]} options.sourceLines Source lines
  177. * @returns {function(...args): ReportInfo} Function that returns information about the report
  178. */
  179. function createProblem(options) {
  180. const problem = {
  181. ruleId: options.ruleId,
  182. severity: options.severity,
  183. message: options.message,
  184. line: options.loc.start.line,
  185. column: options.loc.start.column + 1,
  186. nodeType: options.node && options.node.type || null,
  187. source: options.sourceLines[options.loc.start.line - 1] || ""
  188. };
  189. /*
  190. * If this isn’t in the conditional, some of the tests fail
  191. * because `messageId` is present in the problem object
  192. */
  193. if (options.messageId) {
  194. problem.messageId = options.messageId;
  195. }
  196. if (options.loc.end) {
  197. problem.endLine = options.loc.end.line;
  198. problem.endColumn = options.loc.end.column + 1;
  199. }
  200. if (options.fix) {
  201. problem.fix = options.fix;
  202. }
  203. return problem;
  204. }
  205. /**
  206. * Returns a function that converts the arguments of a `context.report` call from a rule into a reported
  207. * problem for the Node.js API.
  208. * @param {{ruleId: string, severity: number, sourceCode: SourceCode, messageIds: Object}} metadata Metadata for the reported problem
  209. * @param {SourceCode} sourceCode The `SourceCode` instance for the text being linted
  210. * @returns {function(...args): ReportInfo} Function that returns information about the report
  211. */
  212. module.exports = function createReportTranslator(metadata) {
  213. /*
  214. * `createReportTranslator` gets called once per enabled rule per file. It needs to be very performant.
  215. * The report translator itself (i.e. the function that `createReportTranslator` returns) gets
  216. * called every time a rule reports a problem, which happens much less frequently (usually, the vast
  217. * majority of rules don't report any problems for a given file).
  218. */
  219. return function() {
  220. const descriptor = normalizeMultiArgReportCall.apply(null, arguments);
  221. assertValidNodeInfo(descriptor);
  222. if (descriptor.messageId) {
  223. if (!metadata.messageIds) {
  224. throw new TypeError("context.report() called with a messageId, but no messages were present in the rule metadata.");
  225. }
  226. const id = descriptor.messageId;
  227. const messages = metadata.messageIds;
  228. if (descriptor.message) {
  229. throw new TypeError("context.report() called with a message and a messageId. Please only pass one.");
  230. }
  231. if (!messages || !Object.prototype.hasOwnProperty.call(messages, id)) {
  232. throw new TypeError(`context.report() called with a messageId of '${id}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`);
  233. }
  234. descriptor.message = messages[id];
  235. }
  236. return createProblem({
  237. ruleId: metadata.ruleId,
  238. severity: metadata.severity,
  239. node: descriptor.node,
  240. message: normalizeMessagePlaceholders(descriptor),
  241. messageId: descriptor.messageId,
  242. loc: normalizeReportLoc(descriptor),
  243. fix: normalizeFixes(descriptor, metadata.sourceCode),
  244. sourceLines: metadata.sourceCode.lines
  245. });
  246. };
  247. };