]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/developer-guide/working-with-rules.md
import 8.23.1 source
[pve-eslint.git] / eslint / docs / src / developer-guide / working-with-rules.md
1 ---
2 title: Working with Rules
3 layout: doc
4 eleventyNavigation:
5 key: working with rules
6 parent: developer guide
7 title: Working with Rules
8 order: 4
9
10 ---
11
12 **Note:** This page covers the most recent rule format for ESLint >= 3.0.0. There is also a [deprecated rule format](./working-with-rules-deprecated).
13
14 Each rule in ESLint has three files named with its identifier (for example, `no-extra-semi`).
15
16 * in the `lib/rules` directory: a source file (for example, `no-extra-semi.js`)
17 * in the `tests/lib/rules` directory: a test file (for example, `no-extra-semi.js`)
18 * in the `docs/src/rules` directory: a Markdown documentation file (for example, `no-extra-semi.md`)
19
20 **Important:** If you submit a **core** rule to the ESLint repository, you **must** follow some conventions explained below.
21
22 Here is the basic format of the source file for a rule:
23
24 ```js
25 /**
26 * @fileoverview Rule to disallow unnecessary semicolons
27 * @author Nicholas C. Zakas
28 */
29
30 "use strict";
31
32 //------------------------------------------------------------------------------
33 // Rule Definition
34 //------------------------------------------------------------------------------
35
36 /** @type {import('eslint').Rule.RuleModule} */
37 module.exports = {
38 meta: {
39 type: "suggestion",
40
41 docs: {
42 description: "disallow unnecessary semicolons",
43 recommended: true,
44 url: "https://eslint.org/docs/rules/no-extra-semi"
45 },
46 fixable: "code",
47 schema: [] // no options
48 },
49 create: function(context) {
50 return {
51 // callback functions
52 };
53 }
54 };
55 ```
56
57 ## Rule Basics
58
59 The source file for a rule exports an object with the following properties.
60
61 `meta` (object) contains metadata for the rule:
62
63 * `type` (string) indicates the type of rule, which is one of `"problem"`, `"suggestion"`, or `"layout"`:
64 * `"problem"` means the rule is identifying code that either will cause an error or may cause a confusing behavior. Developers should consider this a high priority to resolve.
65 * `"suggestion"` means the rule is identifying something that could be done in a better way but no errors will occur if the code isn't changed.
66 * `"layout"` means the rule cares primarily about whitespace, semicolons, commas, and parentheses, all the parts of the program that determine how the code looks rather than how it executes. These rules work on parts of the code that aren't specified in the AST.
67
68 * `docs` (object) is required for core rules of ESLint:
69
70 * `description` (string) provides the short description of the rule in the [rules index](../rules/)
71 * `recommended` (boolean) is whether the `"extends": "eslint:recommended"` property in a [configuration file](../user-guide/configuring/configuration-files#extending-configuration-files) enables the rule
72 * `url` (string) specifies the URL at which the full documentation can be accessed (enabling code editors to provide a helpful link on highlighted rule violations)
73
74 In a custom rule or plugin, you can omit `docs` or include any properties that you need in it.
75
76 * `fixable` (string) is either `"code"` or `"whitespace"` if the `--fix` option on the [command line](../user-guide/command-line-interface#--fix) automatically fixes problems reported by the rule
77
78 **Important:** the `fixable` property is mandatory for fixable rules. If this property isn't specified, ESLint will throw an error whenever the rule attempts to produce a fix. Omit the `fixable` property if the rule is not fixable.
79
80 * `hasSuggestions` (boolean) specifies whether rules can return suggestions (defaults to `false` if omitted)
81
82 **Important:** the `hasSuggestions` property is mandatory for rules that provide suggestions. If this property isn't set to `true`, ESLint will throw an error whenever the rule attempts to produce a suggestion. Omit the `hasSuggestions` property if the rule does not provide suggestions.
83
84 * `schema` (array) specifies the [options](#options-schemas) so ESLint can prevent invalid [rule configurations](../user-guide/configuring/rules#configuring-rules)
85
86 * `deprecated` (boolean) indicates whether the rule has been deprecated. You may omit the `deprecated` property if the rule has not been deprecated.
87
88 * `replacedBy` (array) in the case of a deprecated rule, specifies replacement rule(s)
89
90 `create` (function) returns an object with methods that ESLint calls to "visit" nodes while traversing the abstract syntax tree (AST as defined by [ESTree](https://github.com/estree/estree)) of JavaScript code:
91
92 * if a key is a node type or a [selector](./selectors), ESLint calls that **visitor** function while going **down** the tree
93 * if a key is a node type or a [selector](./selectors) plus `:exit`, ESLint calls that **visitor** function while going **up** the tree
94 * if a key is an event name, ESLint calls that **handler** function for [code path analysis](./code-path-analysis)
95
96 A rule can use the current node and its surrounding tree to report or fix problems.
97
98 Here are methods for the [array-callback-return](../rules/array-callback-return) rule:
99
100 ```js
101 function checkLastSegment (node) {
102 // report problem for function if last code path segment is reachable
103 }
104
105 module.exports = {
106 meta: { ... },
107 create: function(context) {
108 // declare the state of the rule
109 return {
110 ReturnStatement: function(node) {
111 // at a ReturnStatement node while going down
112 },
113 // at a function expression node while going up:
114 "FunctionExpression:exit": checkLastSegment,
115 "ArrowFunctionExpression:exit": checkLastSegment,
116 onCodePathStart: function (codePath, node) {
117 // at the start of analyzing a code path
118 },
119 onCodePathEnd: function(codePath, node) {
120 // at the end of analyzing a code path
121 }
122 };
123 }
124 };
125 ```
126
127 ## The Context Object
128
129 The `context` object contains additional functionality that is helpful for rules to do their jobs. As the name implies, the `context` object contains information that is relevant to the context of the rule. The `context` object has the following properties:
130
131 * `parserOptions` - the parser options configured for this run (more details [here](../user-guide/configuring/language-options#specifying-parser-options)).
132 * `id` - the rule ID.
133 * `options` - an array of the [configured options](/docs/user-guide/configuring/rules#configuring-rules) for this rule. This array does not include the rule severity. For more information, see [here](#contextoptions).
134 * `settings` - the [shared settings](/docs/user-guide/configuring/configuration-files#adding-shared-settings) from configuration.
135 * `parserPath` - the name of the `parser` from configuration.
136 * `parserServices` - an object containing parser-provided services for rules. The default parser does not provide any services. However, if a rule is intended to be used with a custom parser, it could use `parserServices` to access anything provided by that parser. (For example, a TypeScript parser could provide the ability to get the computed type of a given node.)
137
138 Additionally, the `context` object has the following methods:
139
140 * `getAncestors()` - returns an array of the ancestors of the currently-traversed node, starting at the root of the AST and continuing through the direct parent of the current node. This array does not include the currently-traversed node itself.
141 * `getCwd()` - returns the `cwd` passed to [Linter](./nodejs-api#linter). It is a path to a directory that should be considered as the current working directory.
142 * `getDeclaredVariables(node)` - returns a list of [variables](./scope-manager-interface#variable-interface) declared by the given node. This information can be used to track references to variables.
143 * If the node is a `VariableDeclaration`, all variables declared in the declaration are returned.
144 * If the node is a `VariableDeclarator`, all variables declared in the declarator are returned.
145 * If the node is a `FunctionDeclaration` or `FunctionExpression`, the variable for the function name is returned, in addition to variables for the function parameters.
146 * If the node is an `ArrowFunctionExpression`, variables for the parameters are returned.
147 * If the node is a `ClassDeclaration` or a `ClassExpression`, the variable for the class name is returned.
148 * If the node is a `CatchClause`, the variable for the exception is returned.
149 * If the node is an `ImportDeclaration`, variables for all of its specifiers are returned.
150 * If the node is an `ImportSpecifier`, `ImportDefaultSpecifier`, or `ImportNamespaceSpecifier`, the declared variable is returned.
151 * Otherwise, if the node does not declare any variables, an empty array is returned.
152 * `getFilename()` - returns the filename associated with the source.
153 * `getPhysicalFilename()` - when linting a file, it returns the full path of the file on disk without any code block information. When linting text, it returns the value passed to `—stdin-filename` or `<text>` if not specified.
154 * `getScope()` - returns the [scope](./scope-manager-interface#scope-interface) of the currently-traversed node. This information can be used to track references to variables.
155 * `getSourceCode()` - returns a [`SourceCode`](#contextgetsourcecode) object that you can use to work with the source that was passed to ESLint.
156 * `markVariableAsUsed(name)` - marks a variable with the given name in the current scope as used. This affects the [no-unused-vars](../rules/no-unused-vars) rule. Returns `true` if a variable with the given name was found and marked as used, otherwise `false`.
157 * `report(descriptor)` - reports a problem in the code (see the [dedicated section](#contextreport)).
158
159 **Note:** Earlier versions of ESLint supported additional methods on the `context` object. Those methods were removed in the new format and should not be relied upon.
160
161 ### context.getScope()
162
163 This method returns the scope which has the following types:
164
165 | AST Node Type | Scope Type |
166 |:--------------------------|:-----------|
167 | `Program` | `global` |
168 | `FunctionDeclaration` | `function` |
169 | `FunctionExpression` | `function` |
170 | `ArrowFunctionExpression` | `function` |
171 | `ClassDeclaration` | `class` |
172 | `ClassExpression` | `class` |
173 | `BlockStatement` ※1 | `block` |
174 | `SwitchStatement` ※1 | `switch` |
175 | `ForStatement` ※2 | `for` |
176 | `ForInStatement` ※2 | `for` |
177 | `ForOfStatement` ※2 | `for` |
178 | `WithStatement` | `with` |
179 | `CatchClause` | `catch` |
180 | others | ※3 |
181
182 **※1** Only if the configured parser provided the block-scope feature. The default parser provides the block-scope feature if `parserOptions.ecmaVersion` is not less than `6`.<br>
183 **※2** Only if the `for` statement defines the iteration variable as a block-scoped variable (E.g., `for (let i = 0;;) {}`).<br>
184 **※3** The scope of the closest ancestor node which has own scope. If the closest ancestor node has multiple scopes then it chooses the innermost scope (E.g., the `Program` node has a `global` scope and a `module` scope if `Program#sourceType` is `"module"`. The innermost scope is the `module` scope.).
185
186 The returned value is a [`Scope` object](scope-manager-interface) defined by the `eslint-scope` package. The `Variable` objects of global variables have some additional properties.
187
188 * `variable.writeable` (`boolean | undefined`) ... If `true`, this global variable can be assigned arbitrary value. If `false`, this global variable is read-only.
189 * `variable.eslintExplicitGlobal` (`boolean | undefined`) ... If `true`, this global variable was defined by a `/* globals */` directive comment in the source code file.
190 * `variable.eslintExplicitGlobalComments` (`Comment[] | undefined`) ... The array of `/* globals */` directive comments which defined this global variable in the source code file. This property is `undefined` if there are no `/* globals */` directive comments.
191 * `variable.eslintImplicitGlobalSetting` (`"readonly" | "writable" | undefined`) ... The configured value in config files. This can be different from `variable.writeable` if there are `/* globals */` directive comments.
192
193 ### context.report()
194
195 The main method you'll use is `context.report()`, which publishes a warning or error (depending on the configuration being used). This method accepts a single argument, which is an object containing the following properties:
196
197 * `message` - the problem message.
198 * `node` - (optional) the AST node related to the problem. If present and `loc` is not specified, then the starting location of the node is used as the location of the problem.
199 * `loc` - (optional) an object specifying the location of the problem. If both `loc` and `node` are specified, then the location is used from `loc` instead of `node`.
200 * `start` - An object of the start location.
201 * `line` - the 1-based line number at which the problem occurred.
202 * `column` - the 0-based column number at which the problem occurred.
203 * `end` - An object of the end location.
204 * `line` - the 1-based line number at which the problem occurred.
205 * `column` - the 0-based column number at which the problem occurred.
206 * `data` - (optional) [placeholder](#using-message-placeholders) data for `message`.
207 * `fix` - (optional) a function that applies a [fix](#applying-fixes) to resolve the problem.
208
209 Note that at least one of `node` or `loc` is required.
210
211 The simplest example is to use just `node` and `message`:
212
213 ```js
214 context.report({
215 node: node,
216 message: "Unexpected identifier"
217 });
218 ```
219
220 The node contains all of the information necessary to figure out the line and column number of the offending text as well the source text representing the node.
221
222 ### Using message placeholders
223
224 You can also use placeholders in the message and provide `data`:
225
226 ```js
227 {% raw %}
228 context.report({
229 node: node,
230 message: "Unexpected identifier: {{ identifier }}",
231 data: {
232 identifier: node.name
233 }
234 });
235 {% endraw %}
236 ```
237
238 Note that leading and trailing whitespace is optional in message parameters.
239
240 The node contains all of the information necessary to figure out the line and column number of the offending text as well the source text representing the node.
241
242 ### `messageId`s
243
244 Instead of typing out messages in both the `context.report()` call and your tests, you can use `messageId`s instead.
245
246 This allows you to avoid retyping error messages. It also prevents errors reported in different sections of your rule from having out-of-date messages.
247
248 ```js
249 {% raw %}
250 // in your rule
251 module.exports = {
252 meta: {
253 messages: {
254 avoidName: "Avoid using variables named '{{ name }}'"
255 }
256 },
257 create(context) {
258 return {
259 Identifier(node) {
260 if (node.name === "foo") {
261 context.report({
262 node,
263 messageId: "avoidName",
264 data: {
265 name: "foo",
266 }
267 });
268 }
269 }
270 };
271 }
272 };
273
274 // in the file to lint:
275
276 var foo = 2;
277 // ^ error: Avoid using variables named 'foo'
278
279 // In your tests:
280 var rule = require("../../../lib/rules/my-rule");
281 var RuleTester = require("eslint").RuleTester;
282
283 var ruleTester = new RuleTester();
284 ruleTester.run("my-rule", rule, {
285 valid: ["bar", "baz"],
286 invalid: [
287 {
288 code: "foo",
289 errors: [
290 {
291 messageId: "avoidName"
292 }
293 ]
294 }
295 ]
296 });
297 {% endraw %}
298 ```
299
300 ### Applying Fixes
301
302 If you'd like ESLint to attempt to fix the problem you're reporting, you can do so by specifying the `fix` function when using `context.report()`. The `fix` function receives a single argument, a `fixer` object, that you can use to apply a fix. For example:
303
304 ```js
305 context.report({
306 node: node,
307 message: "Missing semicolon",
308 fix: function(fixer) {
309 return fixer.insertTextAfter(node, ";");
310 }
311 });
312 ```
313
314 Here, the `fix()` function is used to insert a semicolon after the node. Note that a fix is not immediately applied, and may not be applied at all if there are conflicts with other fixes. After applying fixes, ESLint will run all of the enabled rules again on the fixed code, potentially applying more fixes. This process will repeat up to 10 times, or until no more fixable problems are found. Afterwards, any remaining problems will be reported as usual.
315
316 **Important:** The `meta.fixable` property is mandatory for fixable rules. ESLint will throw an error if a rule that implements `fix` functions does not [export](#rule-basics) the `meta.fixable` property.
317
318 The `fixer` object has the following methods:
319
320 * `insertTextAfter(nodeOrToken, text)` - inserts text after the given node or token
321 * `insertTextAfterRange(range, text)` - inserts text after the given range
322 * `insertTextBefore(nodeOrToken, text)` - inserts text before the given node or token
323 * `insertTextBeforeRange(range, text)` - inserts text before the given range
324 * `remove(nodeOrToken)` - removes the given node or token
325 * `removeRange(range)` - removes text in the given range
326 * `replaceText(nodeOrToken, text)` - replaces the text in the given node or token
327 * `replaceTextRange(range, text)` - replaces the text in the given range
328
329 A range is a two-item array containing character indices inside of the source code. The first item is the start of the range (inclusive) and the second item is the end of the range (exclusive). Every node and token has a `range` property to identify the source code range they represent.
330
331 The above methods return a `fixing` object.
332 The `fix()` function can return the following values:
333
334 * A `fixing` object.
335 * An array which includes `fixing` objects.
336 * An iterable object which enumerates `fixing` objects. Especially, the `fix()` function can be a generator.
337
338 If you make a `fix()` function which returns multiple `fixing` objects, those `fixing` objects must not be overlapped.
339
340 Best practices for fixes:
341
342 1. Avoid any fixes that could change the runtime behavior of code and cause it to stop working.
343 1. Make fixes as small as possible. Fixes that are unnecessarily large could conflict with other fixes, and prevent them from being applied.
344 1. Only make one fix per message. This is enforced because you must return the result of the fixer operation from `fix()`.
345 1. Since all rules are run again after the initial round of fixes is applied, it's not necessary for a rule to check whether the code style of a fix will cause errors to be reported by another rule.
346 * For example, suppose a fixer would like to surround an object key with quotes, but it's not sure whether the user would prefer single or double quotes.
347
348 ```js
349 ({ foo : 1 })
350
351 // should get fixed to either
352
353 ({ 'foo': 1 })
354
355 // or
356
357 ({ "foo": 1 })
358 ```
359
360 * This fixer can just select a quote type arbitrarily. If it guesses wrong, the resulting code will be automatically reported and fixed by the [`quotes`](/docs/rules/quotes) rule.
361
362 Note: Making fixes as small as possible is a best practice, but in some cases it may be correct to extend the range of the fix in order to intentionally prevent other rules from making fixes in a surrounding range in the same pass. For instance, if replacement text declares a new variable, it can be useful to prevent other changes in the scope of the variable as they might cause name collisions.
363
364 The following example replaces `node` and also ensures that no other fixes will be applied in the range of `node.parent` in the same pass:
365
366 ```js
367 context.report({
368 node,
369 message,
370 *fix(fixer) {
371 yield fixer.replaceText(node, replacementText);
372
373 // extend range of the fix to the range of `node.parent`
374 yield fixer.insertTextBefore(node.parent, "");
375 yield fixer.insertTextAfter(node.parent, "");
376 }
377 });
378 ```
379
380 ### Providing Suggestions
381
382 In some cases fixes aren't appropriate to be automatically applied, for example, if a fix potentially changes functionality or if there are multiple valid ways to fix a rule depending on the implementation intent (see the best practices for [applying fixes](#applying-fixes) listed above). In these cases, there is an alternative `suggest` option on `context.report()` that allows other tools, such as editors, to expose helpers for users to manually apply a suggestion.
383
384 In order to provide suggestions, use the `suggest` key in the report argument with an array of suggestion objects. The suggestion objects represent individual suggestions that could be applied and require either a `desc` key string that describes what applying the suggestion would do or a `messageId` key (see [below](#suggestion-messageids)), and a `fix` key that is a function defining the suggestion result. This `fix` function follows the same API as regular fixes (described above in [applying fixes](#applying-fixes)).
385
386 ```js
387 {% raw %}
388 context.report({
389 node: node,
390 message: "Unnecessary escape character: \\{{character}}.",
391 data: { character },
392 suggest: [
393 {
394 desc: "Remove the `\\`. This maintains the current functionality.",
395 fix: function(fixer) {
396 return fixer.removeRange(range);
397 }
398 },
399 {
400 desc: "Replace the `\\` with `\\\\` to include the actual backslash character.",
401 fix: function(fixer) {
402 return fixer.insertTextBeforeRange(range, "\\");
403 }
404 }
405 ]
406 });
407 {% endraw %}
408 ```
409
410 **Important:** The `meta.hasSuggestions` property is mandatory for rules that provide suggestions. ESLint will throw an error if a rule attempts to produce a suggestion but does not [export](#rule-basics) this property.
411
412 Note: Suggestions will be applied as a stand-alone change, without triggering multipass fixes. Each suggestion should focus on a singular change in the code and should not try to conform to user defined styles. For example, if a suggestion is adding a new statement into the codebase, it should not try to match correct indentation, or conform to user preferences on presence/absence of semicolons. All of those things can be corrected by multipass autofix when the user triggers it.
413
414 Best practices for suggestions:
415
416 1. Don't try to do too much and suggest large refactors that could introduce a lot of breaking changes.
417 1. As noted above, don't try to conform to user-defined styles.
418
419 Suggestions are intended to provide fixes. ESLint will automatically remove the whole suggestion from the linting output if the suggestion's `fix` function returned `null` or an empty array/sequence.
420
421 #### Suggestion `messageId`s
422
423 Instead of using a `desc` key for suggestions a `messageId` can be used instead. This works the same way as `messageId`s for the overall error (see [messageIds](#messageids)). Here is an example of how to use it in a rule:
424
425 ```js
426 {% raw %}
427 module.exports = {
428 meta: {
429 messages: {
430 unnecessaryEscape: "Unnecessary escape character: \\{{character}}.",
431 removeEscape: "Remove the `\\`. This maintains the current functionality.",
432 escapeBackslash: "Replace the `\\` with `\\\\` to include the actual backslash character."
433 },
434 hasSuggestions: true
435 },
436 create: function(context) {
437 // ...
438 context.report({
439 node: node,
440 messageId: 'unnecessaryEscape',
441 data: { character },
442 suggest: [
443 {
444 messageId: "removeEscape",
445 fix: function(fixer) {
446 return fixer.removeRange(range);
447 }
448 },
449 {
450 messageId: "escapeBackslash",
451 fix: function(fixer) {
452 return fixer.insertTextBeforeRange(range, "\\");
453 }
454 }
455 ]
456 });
457 }
458 };
459 {% endraw %}
460 ```
461
462 #### Placeholders in suggestion messages
463
464 You can also use placeholders in the suggestion message. This works the same way as placeholders for the overall error (see [using message placeholders](#using-message-placeholders)).
465
466 Please note that you have to provide `data` on the suggestion's object. Suggestion messages cannot use properties from the overall error's `data`.
467
468 ```js
469 {% raw %}
470 module.exports = {
471 meta: {
472 messages: {
473 unnecessaryEscape: "Unnecessary escape character: \\{{character}}.",
474 removeEscape: "Remove `\\` before {{character}}.",
475 },
476 hasSuggestions: true
477 },
478 create: function(context) {
479 // ...
480 context.report({
481 node: node,
482 messageId: "unnecessaryEscape",
483 data: { character }, // data for the unnecessaryEscape overall message
484 suggest: [
485 {
486 messageId: "removeEscape",
487 data: { character }, // data for the removeEscape suggestion message
488 fix: function(fixer) {
489 return fixer.removeRange(range);
490 }
491 }
492 ]
493 });
494 }
495 };
496 {% endraw %}
497 ```
498
499 ### context.options
500
501 Some rules require options in order to function correctly. These options appear in configuration (`.eslintrc`, command line, or in comments). For example:
502
503 ```json
504 {
505 "quotes": ["error", "double"]
506 }
507 ```
508
509 The `quotes` rule in this example has one option, `"double"` (the `error` is the error level). You can retrieve the options for a rule by using `context.options`, which is an array containing every configured option for the rule. In this case, `context.options[0]` would contain `"double"`:
510
511 ```js
512 module.exports = {
513 create: function(context) {
514 var isDouble = (context.options[0] === "double");
515
516 // ...
517 }
518 };
519 ```
520
521 Since `context.options` is just an array, you can use it to determine how many options have been passed as well as retrieving the actual options themselves. Keep in mind that the error level is not part of `context.options`, as the error level cannot be known or modified from inside a rule.
522
523 When using options, make sure that your rule has some logical defaults in case the options are not provided.
524
525 ### context.getSourceCode()
526
527 The `SourceCode` object is the main object for getting more information about the source code being linted. You can retrieve the `SourceCode` object at any time by using the `getSourceCode()` method:
528
529 ```js
530 module.exports = {
531 create: function(context) {
532 var sourceCode = context.getSourceCode();
533
534 // ...
535 }
536 };
537 ```
538
539 Once you have an instance of `SourceCode`, you can use the following methods on it to work with the code:
540
541 * `getText(node)` - returns the source code for the given node. Omit `node` to get the whole source.
542 * `getAllComments()` - returns an array of all comments in the source.
543 * `getCommentsBefore(nodeOrToken)` - returns an array of comment tokens that occur directly before the given node or token.
544 * `getCommentsAfter(nodeOrToken)` - returns an array of comment tokens that occur directly after the given node or token.
545 * `getCommentsInside(node)` - returns an array of all comment tokens inside a given node.
546 * `isSpaceBetween(nodeOrToken, nodeOrToken)` - returns true if there is a whitespace character between the two tokens or, if given a node, the last token of the first node and the first token of the second node.
547 * `getFirstToken(node, skipOptions)` - returns the first token representing the given node.
548 * `getFirstTokens(node, countOptions)` - returns the first `count` tokens representing the given node.
549 * `getLastToken(node, skipOptions)` - returns the last token representing the given node.
550 * `getLastTokens(node, countOptions)` - returns the last `count` tokens representing the given node.
551 * `getTokenAfter(nodeOrToken, skipOptions)` - returns the first token after the given node or token.
552 * `getTokensAfter(nodeOrToken, countOptions)` - returns `count` tokens after the given node or token.
553 * `getTokenBefore(nodeOrToken, skipOptions)` - returns the first token before the given node or token.
554 * `getTokensBefore(nodeOrToken, countOptions)` - returns `count` tokens before the given node or token.
555 * `getFirstTokenBetween(nodeOrToken1, nodeOrToken2, skipOptions)` - returns the first token between two nodes or tokens.
556 * `getFirstTokensBetween(nodeOrToken1, nodeOrToken2, countOptions)` - returns the first `count` tokens between two nodes or tokens.
557 * `getLastTokenBetween(nodeOrToken1, nodeOrToken2, skipOptions)` - returns the last token between two nodes or tokens.
558 * `getLastTokensBetween(nodeOrToken1, nodeOrToken2, countOptions)` - returns the last `count` tokens between two nodes or tokens.
559 * `getTokens(node)` - returns all tokens for the given node.
560 * `getTokensBetween(nodeOrToken1, nodeOrToken2)` - returns all tokens between two nodes.
561 * `getTokenByRangeStart(index, rangeOptions)` - returns the token whose range starts at the given index in the source.
562 * `getNodeByRangeIndex(index)` - returns the deepest node in the AST containing the given source index.
563 * `getLocFromIndex(index)` - returns an object with `line` and `column` properties, corresponding to the location of the given source index. `line` is 1-based and `column` is 0-based.
564 * `getIndexFromLoc(loc)` - returns the index of a given location in the source code, where `loc` is an object with a 1-based `line` key and a 0-based `column` key.
565 * `commentsExistBetween(nodeOrToken1, nodeOrToken2)` - returns `true` if comments exist between two nodes.
566
567 `skipOptions` is an object which has 3 properties; `skip`, `includeComments`, and `filter`. Default is `{skip: 0, includeComments: false, filter: null}`.
568
569 * `skip` is a positive integer, the number of skipping tokens. If `filter` option is given at the same time, it doesn't count filtered tokens as skipped.
570 * `includeComments` is a boolean value, the flag to include comment tokens into the result.
571 * `filter` is a function which gets a token as the first argument, if the function returns `false` then the result excludes the token.
572
573 `countOptions` is an object which has 3 properties; `count`, `includeComments`, and `filter`. Default is `{count: 0, includeComments: false, filter: null}`.
574
575 * `count` is a positive integer, the maximum number of returning tokens.
576 * `includeComments` is a boolean value, the flag to include comment tokens into the result.
577 * `filter` is a function which gets a token as the first argument, if the function returns `false` then the result excludes the token.
578
579 `rangeOptions` is an object which has 1 property: `includeComments`.
580
581 * `includeComments` is a boolean value, the flag to include comment tokens into the result.
582
583 There are also some properties you can access:
584
585 * `hasBOM` - the flag to indicate whether or not the source code has Unicode BOM.
586 * `text` - the full text of the code being linted. Unicode BOM has been stripped from this text.
587 * `ast` - the `Program` node of the AST for the code being linted.
588 * `scopeManager` - the [ScopeManager](./scope-manager-interface#scopemanager-interface) object of the code.
589 * `visitorKeys` - the visitor keys to traverse this AST.
590 * `lines` - an array of lines, split according to the specification's definition of line breaks.
591
592 You should use a `SourceCode` object whenever you need to get more information about the code being linted.
593
594 #### Deprecated
595
596 Please note that the following methods have been deprecated and will be removed in a future version of ESLint:
597
598 * `getComments()` - replaced by `getCommentsBefore()`, `getCommentsAfter()`, and `getCommentsInside()`
599 * `getTokenOrCommentBefore()` - replaced by `getTokenBefore()` with the `{ includeComments: true }` option
600 * `getTokenOrCommentAfter()` - replaced by `getTokenAfter()` with the `{ includeComments: true }` option
601 * `isSpaceBetweenTokens()` - replaced by `isSpaceBetween()`
602 * `getJSDocComment()`
603
604 ### Options Schemas
605
606 Rules may export a `schema` property, which is a [JSON schema](https://json-schema.org/) format description of a rule's options which will be used by ESLint to validate configuration options and prevent invalid or unexpected inputs before they are passed to the rule in `context.options`.
607
608 There are two formats for a rule's exported `schema`. The first is a full JSON Schema object describing all possible options the rule accepts, including the rule's error level as the first argument and any optional arguments thereafter.
609
610 However, to simplify schema creation, rules may also export an array of schemas for each optional positional argument, and ESLint will automatically validate the required error level first. For example, the `yoda` rule accepts a primary mode argument, as well as an extra options object with named properties.
611
612 ```js
613 // "yoda": [2, "never", { "exceptRange": true }]
614 module.exports = {
615 meta: {
616 schema: [
617 {
618 "enum": ["always", "never"]
619 },
620 {
621 "type": "object",
622 "properties": {
623 "exceptRange": {
624 "type": "boolean"
625 }
626 },
627 "additionalProperties": false
628 }
629 ]
630 },
631 };
632 ```
633
634 In the preceding example, the error level is assumed to be the first argument. It is followed by the first optional argument, a string which may be either `"always"` or `"never"`. The final optional argument is an object, which may have a Boolean property named `exceptRange`.
635
636 To learn more about JSON Schema, we recommend looking at some examples in [website](https://json-schema.org/learn/) to start, and also reading [Understanding JSON Schema](https://json-schema.org/understanding-json-schema/) (a free ebook).
637
638 **Note:** Currently you need to use full JSON Schema object rather than array in case your schema has references ($ref), because in case of array format ESLint transforms this array into a single schema without updating references that makes them incorrect (they are ignored).
639
640 ### Getting the Source
641
642 If your rule needs to get the actual JavaScript source to work with, then use the `sourceCode.getText()` method. This method works as follows:
643
644 ```js
645
646 // get all source
647 var source = sourceCode.getText();
648
649 // get source for just this AST node
650 var nodeSource = sourceCode.getText(node);
651
652 // get source for AST node plus previous two characters
653 var nodeSourceWithPrev = sourceCode.getText(node, 2);
654
655 // get source for AST node plus following two characters
656 var nodeSourceWithFollowing = sourceCode.getText(node, 0, 2);
657 ```
658
659 In this way, you can look for patterns in the JavaScript text itself when the AST isn't providing the appropriate data (such as location of commas, semicolons, parentheses, etc.).
660
661 ### Accessing Comments
662
663 While comments are not technically part of the AST, ESLint provides a few ways for rules to access them:
664
665 #### sourceCode.getAllComments()
666
667 This method returns an array of all the comments found in the program. This is useful for rules that need to check all comments regardless of location.
668
669 #### sourceCode.getCommentsBefore(), sourceCode.getCommentsAfter(), and sourceCode.getCommentsInside()
670
671 These methods return an array of comments that appear directly before, directly after, and inside nodes, respectively. They are useful for rules that need to check comments in relation to a given node or token.
672
673 Keep in mind that the results of this method are calculated on demand.
674
675 #### Token traversal methods
676
677 Finally, comments can be accessed through many of `sourceCode`'s methods using the `includeComments` option.
678
679 ### Accessing Shebangs
680
681 Shebangs are represented by tokens of type `"Shebang"`. They are treated as comments and can be accessed by the methods outlined above.
682
683 ### Accessing Code Paths
684
685 ESLint analyzes code paths while traversing AST.
686 You can access that code path objects with five events related to code paths.
687
688 [details here](./code-path-analysis)
689
690 ## Rule Unit Tests
691
692 Each bundled rule for ESLint core must have a set of unit tests submitted with it to be accepted. The test file is named the same as the source file but lives in `tests/lib/`. For example, if the rule source file is `lib/rules/foo.js` then the test file should be `tests/lib/rules/foo.js`.
693
694 ESLint provides the [`RuleTester`](/docs/developer-guide/nodejs-api#ruletester) utility to make it easy to write tests for rules.
695
696 ## Performance Testing
697
698 To keep the linting process efficient and unobtrusive, it is useful to verify the performance impact of new rules or modifications to existing rules.
699
700 ### Overall Performance
701
702 When developing in the ESLint core repository, the `npm run perf` command gives a high-level overview of ESLint running time with all core rules enabled.
703
704 ```bash
705 $ git checkout main
706 Switched to branch 'main'
707
708 $ npm run perf
709 CPU Speed is 2200 with multiplier 7500000
710 Performance Run #1: 1394.689313ms
711 Performance Run #2: 1423.295351ms
712 Performance Run #3: 1385.09515ms
713 Performance Run #4: 1382.406982ms
714 Performance Run #5: 1409.68566ms
715 Performance budget ok: 1394.689313ms (limit: 3409.090909090909ms)
716
717 $ git checkout my-rule-branch
718 Switched to branch 'my-rule-branch'
719
720 $ npm run perf
721 CPU Speed is 2200 with multiplier 7500000
722 Performance Run #1: 1443.736547ms
723 Performance Run #2: 1419.193291ms
724 Performance Run #3: 1436.018228ms
725 Performance Run #4: 1473.605485ms
726 Performance Run #5: 1457.455283ms
727 Performance budget ok: 1443.736547ms (limit: 3409.090909090909ms)
728 ```
729
730 ### Per-rule Performance
731
732 ESLint has a built-in method to track performance of individual rules. Setting the `TIMING` environment variable will trigger the display, upon linting completion, of the ten longest-running rules, along with their individual running time (rule creation + rule execution) and relative performance impact as a percentage of total rule processing time (rule creation + rule execution).
733
734 ```bash
735 $ TIMING=1 eslint lib
736 Rule | Time (ms) | Relative
737 :-----------------------|----------:|--------:
738 no-multi-spaces | 52.472 | 6.1%
739 camelcase | 48.684 | 5.7%
740 no-irregular-whitespace | 43.847 | 5.1%
741 valid-jsdoc | 40.346 | 4.7%
742 handle-callback-err | 39.153 | 4.6%
743 space-infix-ops | 35.444 | 4.1%
744 no-undefined | 25.693 | 3.0%
745 no-shadow | 22.759 | 2.7%
746 no-empty-class | 21.976 | 2.6%
747 semi | 19.359 | 2.3%
748 ```
749
750 To test one rule explicitly, combine the `--no-eslintrc`, and `--rule` options:
751
752 ```bash
753 $ TIMING=1 eslint --no-eslintrc --rule "quotes: [2, 'double']" lib
754 Rule | Time (ms) | Relative
755 :------|----------:|--------:
756 quotes | 18.066 | 100.0%
757 ```
758
759 To see a longer list of results (more than 10), set the environment variable to another value such as `TIMING=50` or `TIMING=all`.
760
761 ## Rule Naming Conventions
762
763 The rule naming conventions for ESLint are fairly simple:
764
765 * If your rule is disallowing something, prefix it with `no-` such as `no-eval` for disallowing `eval()` and `no-debugger` for disallowing `debugger`.
766 * If your rule is enforcing the inclusion of something, use a short name without a special prefix.
767 * Use dashes between words.
768
769 ## Runtime Rules
770
771 The thing that makes ESLint different from other linters is the ability to define custom rules at runtime. This is perfect for rules that are specific to your project or company and wouldn't make sense for ESLint to ship with. With runtime rules, you don't have to wait for the next version of ESLint or be disappointed that your rule isn't general enough to apply to the larger JavaScript community, just write your rules and include them at runtime.
772
773 Runtime rules are written in the same format as all other rules. Create your rule as you would any other and then follow these steps:
774
775 1. Place all of your runtime rules in the same directory (e.g., `eslint_rules`).
776 2. Create a [configuration file](../user-guide/configuring/) and specify your rule ID error level under the `rules` key. Your rule will not run unless it has a value of `"warn"` or `"error"` in the configuration file.
777 3. Run the [command line interface](../user-guide/command-line-interface) using the `--rulesdir` option to specify the location of your runtime rules.