]>
git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/linter/report-translator.js
2 * @fileoverview A helper that translates context.report() calls from the rule API into generic problem objects
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 const assert
= require ( "assert" );
13 const ruleFixer
= require ( "./rule-fixer" );
14 const interpolate
= require ( "./interpolate" );
16 //------------------------------------------------------------------------------
18 //------------------------------------------------------------------------------
21 * An error message description
22 * @typedef {Object} MessageDescriptor
23 * @property {ASTNode} [node] The reported node
24 * @property {Location} loc The location of the problem.
25 * @property {string} message The problem message.
26 * @property {Object} [data] Optional data to use to fill in placeholders in the
28 * @property {Function} [fix] The function to call that creates a fix command.
29 * @property {Array<{desc?: string, messageId?: string, fix: Function}>} suggest Suggestion descriptions and functions to create a the associated fixes.
33 * Information about the report
34 * @typedef {Object} ReportInfo
35 * @property {string} ruleId
36 * @property {(0|1|2)} severity
37 * @property {(string|undefined)} message
38 * @property {(string|undefined)} [messageId]
39 * @property {number} line
40 * @property {number} column
41 * @property {(number|undefined)} [endLine]
42 * @property {(number|undefined)} [endColumn]
43 * @property {(string|null)} nodeType
44 * @property {string} source
45 * @property {({text: string, range: (number[]|null)}|null)} [fix]
46 * @property {Array<{text: string, range: (number[]|null)}|null>} [suggestions]
49 //------------------------------------------------------------------------------
51 //------------------------------------------------------------------------------
55 * Translates a multi-argument context.report() call into a single object argument call
56 * @param {...*} args A list of arguments passed to `context.report`
57 * @returns {MessageDescriptor} A normalized object containing report information
59 function normalizeMultiArgReportCall (... args
) {
61 // If there is one argument, it is considered to be a new-style call already.
62 if ( args
. length
=== 1 ) {
64 // Shallow clone the object to avoid surprises if reusing the descriptor
65 return Object
. assign ({}, args
[ 0 ]);
68 // If the second argument is a string, the arguments are interpreted as [node, message, data, fix].
69 if ( typeof args
[ 1 ] === "string" ) {
78 // Otherwise, the arguments are interpreted as [node, loc, message, data, fix].
89 * Asserts that either a loc or a node was provided, and the node is valid if it was provided.
90 * @param {MessageDescriptor} descriptor A descriptor to validate
92 * @throws AssertionError if neither a node nor a loc was provided, or if the node is not an object
94 function assertValidNodeInfo ( descriptor
) {
95 if ( descriptor
. node
) {
96 assert ( typeof descriptor
. node
=== "object" , "Node must be an object" );
98 assert ( descriptor
. loc
, "Node must be provided when reporting error if location is not provided" );
103 * Normalizes a MessageDescriptor to always have a `loc` with `start` and `end` properties
104 * @param {MessageDescriptor} descriptor A descriptor for the report from a rule.
105 * @returns {{start: Location, end: (Location|null)}} An updated location that infers the `start` and `end` properties
106 * from the `node` of the original descriptor, or infers the `start` from the `loc` of the original descriptor.
108 function normalizeReportLoc ( descriptor
) {
109 if ( descriptor
. loc
) {
110 if ( descriptor
. loc
. start
) {
111 return descriptor
. loc
;
113 return { start
: descriptor
. loc
, end
: null };
115 return descriptor
. node
. loc
;
119 * Compares items in a fixes array by range.
120 * @param {Fix} a The first message.
121 * @param {Fix} b The second message.
122 * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal.
125 function compareFixesByRange ( a
, b
) {
126 return a
. range
[ 0 ] - b
. range
[ 0 ] || a
. range
[ 1 ] - b
. range
[ 1 ];
130 * Merges the given fixes array into one.
131 * @param {Fix[]} fixes The fixes to merge.
132 * @param {SourceCode} sourceCode The source code object to get the text between fixes.
133 * @returns {{text: string, range: number[]}} The merged fixes
135 function mergeFixes ( fixes
, sourceCode
) {
136 if ( fixes
. length
=== 0 ) {
139 if ( fixes
. length
=== 1 ) {
143 fixes
. sort ( compareFixesByRange
);
145 const originalText
= sourceCode
. text
;
146 const start
= fixes
[ 0 ]. range
[ 0 ];
147 const end
= fixes
[ fixes
. length
- 1 ]. range
[ 1 ];
149 let lastPos
= Number
. MIN_SAFE_INTEGER
;
151 for ( const fix
of fixes
) {
152 assert ( fix
. range
[ 0 ] >= lastPos
, "Fix objects must not be overlapped in a report." );
154 if ( fix
. range
[ 0 ] >= 0 ) {
155 text
+= originalText
. slice ( Math
. max ( 0 , start
, lastPos
), fix
. range
[ 0 ]);
158 lastPos
= fix
. range
[ 1 ];
160 text
+= originalText
. slice ( Math
. max ( 0 , start
, lastPos
), end
);
162 return { range
: [ start
, end
], text
};
166 * Gets one fix object from the given descriptor.
167 * If the descriptor retrieves multiple fixes, this merges those to one.
168 * @param {MessageDescriptor} descriptor The report descriptor.
169 * @param {SourceCode} sourceCode The source code object to get text between fixes.
170 * @returns {({text: string, range: number[]}|null)} The fix for the descriptor
172 function normalizeFixes ( descriptor
, sourceCode
) {
173 if ( typeof descriptor
. fix
!== "function" ) {
177 // @type {null | Fix | Fix[] | IterableIterator<Fix>}
178 const fix
= descriptor
. fix ( ruleFixer
);
181 if ( fix
&& Symbol
. iterator
in fix
) {
182 return mergeFixes ( Array
. from ( fix
), sourceCode
);
188 * Gets an array of suggestion objects from the given descriptor.
189 * @param {MessageDescriptor} descriptor The report descriptor.
190 * @param {SourceCode} sourceCode The source code object to get text between fixes.
191 * @param {Object} messages Object of meta messages for the rule.
192 * @returns {Array<SuggestionResult>} The suggestions for the descriptor
194 function mapSuggestions ( descriptor
, sourceCode
, messages
) {
195 if (! descriptor
. suggest
|| ! Array
. isArray ( descriptor
. suggest
)) {
199 return descriptor
. suggest
200 . map ( suggestInfo
=> {
201 const computedDesc
= suggestInfo
. desc
|| messages
[ suggestInfo
. messageId
];
205 desc
: interpolate ( computedDesc
, suggestInfo
. data
),
206 fix
: normalizeFixes ( suggestInfo
, sourceCode
)
210 // Remove suggestions that didn't provide a fix
211 . filter (({ fix
}) => fix
);
215 * Creates information about the report from a descriptor
216 * @param {Object} options Information about the problem
217 * @param {string} options.ruleId Rule ID
218 * @param {(0|1|2)} options.severity Rule severity
219 * @param {(ASTNode|null)} options.node Node
220 * @param {string} options.message Error message
221 * @param {string} [options.messageId] The error message ID.
222 * @param {{start: SourceLocation, end: (SourceLocation|null)}} options.loc Start and end location
223 * @param {{text: string, range: (number[]|null)}} options.fix The fix object
224 * @param {Array<{text: string, range: (number[]|null)}>} options.suggestions The array of suggestions objects
225 * @returns {function(...args): ReportInfo} Function that returns information about the report
227 function createProblem ( options
) {
229 ruleId
: options
. ruleId
,
230 severity
: options
. severity
,
231 message
: options
. message
,
232 line
: options
. loc
. start
. line
,
233 column
: options
. loc
. start
. column
+ 1 ,
234 nodeType
: options
. node
&& options
. node
. type
|| null
238 * If this isn’t in the conditional, some of the tests fail
239 * because `messageId` is present in the problem object
241 if ( options
. messageId
) {
242 problem
. messageId
= options
. messageId
;
245 if ( options
. loc
. end
) {
246 problem
. endLine
= options
. loc
. end
. line
;
247 problem
. endColumn
= options
. loc
. end
. column
+ 1 ;
251 problem
. fix
= options
. fix
;
254 if ( options
. suggestions
&& options
. suggestions
. length
> 0 ) {
255 problem
. suggestions
= options
. suggestions
;
262 * Validates that suggestions are properly defined. Throws if an error is detected.
263 * @param {Array<{ desc?: string, messageId?: string }>} suggest The incoming suggest data.
264 * @param {Object} messages Object of meta messages for the rule.
267 function validateSuggestions ( suggest
, messages
) {
268 if ( suggest
&& Array
. isArray ( suggest
)) {
269 suggest
. forEach ( suggestion
=> {
270 if ( suggestion
. messageId
) {
271 const { messageId
} = suggestion
;
274 throw new TypeError ( `context.report() called with a suggest option with a messageId ' ${messageId} ', but no messages were present in the rule metadata.` );
277 if (! messages
[ messageId
]) {
278 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)} ` );
281 if ( suggestion
. desc
) {
282 throw new TypeError ( "context.report() called with a suggest option that defines both a 'messageId' and an 'desc'. Please only pass one." );
284 } else if (! suggestion
. desc
) {
285 throw new TypeError ( "context.report() called with a suggest option that doesn't have either a `desc` or `messageId`" );
288 if ( typeof suggestion
. fix
!== "function" ) {
289 throw new TypeError ( `context.report() called with a suggest option without a fix function. See: ${suggestion} ` );
296 * Returns a function that converts the arguments of a `context.report` call from a rule into a reported
297 * problem for the Node.js API.
298 * @param {{ruleId: string, severity: number, sourceCode: SourceCode, messageIds: Object, disableFixes: boolean}} metadata Metadata for the reported problem
299 * @param {SourceCode} sourceCode The `SourceCode` instance for the text being linted
300 * @returns {function(...args): ReportInfo} Function that returns information about the report
303 module
. exports
= function createReportTranslator ( metadata
) {
306 * `createReportTranslator` gets called once per enabled rule per file. It needs to be very performant.
307 * The report translator itself (i.e. the function that `createReportTranslator` returns) gets
308 * called every time a rule reports a problem, which happens much less frequently (usually, the vast
309 * majority of rules don't report any problems for a given file).
311 return (... args
) => {
312 const descriptor
= normalizeMultiArgReportCall (... args
);
313 const messages
= metadata
. messageIds
;
315 assertValidNodeInfo ( descriptor
);
319 if ( descriptor
. messageId
) {
321 throw new TypeError ( "context.report() called with a messageId, but no messages were present in the rule metadata." );
323 const id
= descriptor
. messageId
;
325 if ( descriptor
. message
) {
326 throw new TypeError ( "context.report() called with a message and a messageId. Please only pass one." );
328 if (! messages
|| ! Object
. prototype . hasOwnProperty
. call ( messages
, id
)) {
329 throw new TypeError ( `context.report() called with a messageId of ' ${id} ' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)} ` );
331 computedMessage
= messages
[ id
];
332 } else if ( descriptor
. message
) {
333 computedMessage
= descriptor
. message
;
335 throw new TypeError ( "Missing `message` property in report() call; add a message that describes the linting problem." );
338 validateSuggestions ( descriptor
. suggest
, messages
);
340 return createProblem ({
341 ruleId
: metadata
. ruleId
,
342 severity
: metadata
. severity
,
343 node
: descriptor
. node
,
344 message
: interpolate ( computedMessage
, descriptor
. data
),
345 messageId
: descriptor
. messageId
,
346 loc
: normalizeReportLoc ( descriptor
),
347 fix
: metadata
. disableFixes
? null : normalizeFixes ( descriptor
, metadata
. sourceCode
),
348 suggestions
: metadata
. disableFixes
? [] : mapSuggestions ( descriptor
, metadata
. sourceCode
, messages
)