]> git.proxmox.com Git - pve-eslint.git/blame - eslint/docs/developer-guide/working-with-rules.md
import eslint 7.28.0
[pve-eslint.git] / eslint / docs / developer-guide / working-with-rules.md
CommitLineData
eb39fafa
DC
1# Working with Rules
2
3**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.md).
4
5Each rule in ESLint has three files named with its identifier (for example, `no-extra-semi`).
6
7* in the `lib/rules` directory: a source file (for example, `no-extra-semi.js`)
8* in the `tests/lib/rules` directory: a test file (for example, `no-extra-semi.js`)
9* in the `docs/rules` directory: a Markdown documentation file (for example, `no-extra-semi.md`)
10
11**Important:** If you submit a **core** rule to the ESLint repository, you **must** follow some conventions explained below.
12
13Here is the basic format of the source file for a rule:
14
15```js
16/**
17 * @fileoverview Rule to disallow unnecessary semicolons
18 * @author Nicholas C. Zakas
19 */
20
21"use strict";
22
23//------------------------------------------------------------------------------
24// Rule Definition
25//------------------------------------------------------------------------------
26
27module.exports = {
28 meta: {
29 type: "suggestion",
30
31 docs: {
32 description: "disallow unnecessary semicolons",
33 category: "Possible Errors",
34 recommended: true,
35 url: "https://eslint.org/docs/rules/no-extra-semi"
36 },
37 fixable: "code",
38 schema: [] // no options
39 },
40 create: function(context) {
41 return {
42 // callback functions
43 };
44 }
45};
46```
47
48## Rule Basics
49
50The source file for a rule exports an object with the following properties.
51
52`meta` (object) contains metadata for the rule:
53
54* `type` (string) indicates the type of rule, which is one of `"problem"`, `"suggestion"`, or `"layout"`:
55 * `"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.
56 * `"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.
57 * `"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.
58
59* `docs` (object) is required for core rules of ESLint:
60
61 * `description` (string) provides the short description of the rule in the [rules index](../rules/)
62 * `category` (string) specifies the heading under which the rule is listed in the [rules index](../rules/)
5422a9cc 63 * `recommended` (boolean) is whether the `"extends": "eslint:recommended"` property in a [configuration file](../user-guide/configuring/configuration-files.md#extending-configuration-files) enables the rule
eb39fafa
DC
64 * `url` (string) specifies the URL at which the full documentation can be accessed
65 * `suggestion` (boolean) specifies whether rules can return suggestions (defaults to false if omitted)
66
67 In a custom rule or plugin, you can omit `docs` or include any properties that you need in it.
68
69* `fixable` (string) is either `"code"` or `"whitespace"` if the `--fix` option on the [command line](../user-guide/command-line-interface.md#fix) automatically fixes problems reported by the rule
70
6f036462 71 **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.
eb39fafa 72
5422a9cc 73* `schema` (array) specifies the [options](#options-schemas) so ESLint can prevent invalid [rule configurations](../user-guide/configuring/rules.md#configuring-rules)
eb39fafa
DC
74
75* `deprecated` (boolean) indicates whether the rule has been deprecated. You may omit the `deprecated` property if the rule has not been deprecated.
76
77* `replacedBy` (array) in the case of a deprecated rule, specifies replacement rule(s)
78
79`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:
80
81* if a key is a node type or a [selector](./selectors.md), ESLint calls that **visitor** function while going **down** the tree
82* if a key is a node type or a [selector](./selectors.md) plus `:exit`, ESLint calls that **visitor** function while going **up** the tree
83* if a key is an event name, ESLint calls that **handler** function for [code path analysis](./code-path-analysis.md)
84
85A rule can use the current node and its surrounding tree to report or fix problems.
86
87Here are methods for the [array-callback-return](../rules/array-callback-return.md) rule:
88
89```js
90function checkLastSegment (node) {
91 // report problem for function if last code path segment is reachable
92}
93
94module.exports = {
95 meta: { ... },
96 create: function(context) {
97 // declare the state of the rule
98 return {
99 ReturnStatement: function(node) {
100 // at a ReturnStatement node while going down
101 },
102 // at a function expression node while going up:
103 "FunctionExpression:exit": checkLastSegment,
104 "ArrowFunctionExpression:exit": checkLastSegment,
105 onCodePathStart: function (codePath, node) {
106 // at the start of analyzing a code path
107 },
108 onCodePathEnd: function(codePath, node) {
109 // at the end of analyzing a code path
110 }
111 };
112 }
113};
114```
115
116## The Context Object
117
118The `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:
119
5422a9cc 120* `parserOptions` - the parser options configured for this run (more details [here](../user-guide/configuring/language-options.md#specifying-parser-options)).
eb39fafa 121* `id` - the rule ID.
5422a9cc
TL
122* `options` - an array of the [configured options](/docs/user-guide/configuring/rules.md#configuring-rules) for this rule. This array does not include the rule severity. For more information, see [here](#contextoptions).
123* `settings` - the [shared settings](/docs/user-guide/configuring/configuration-files.md#adding-shared-settings) from configuration.
eb39fafa
DC
124* `parserPath` - the name of the `parser` from configuration.
125* `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.)
126
127Additionally, the `context` object has the following methods:
128
129* `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.
130* `getCwd()` - returns the `cwd` passed to [Linter](./nodejs-api.md#Linter). It is a path to a directory that should be considered as the current working directory.
131* `getDeclaredVariables(node)` - returns a list of [variables](./scope-manager-interface.md#variable-interface) declared by the given node. This information can be used to track references to variables.
132 * If the node is a `VariableDeclaration`, all variables declared in the declaration are returned.
133 * If the node is a `VariableDeclarator`, all variables declared in the declarator are returned.
134 * If the node is a `FunctionDeclaration` or `FunctionExpression`, the variable for the function name is returned, in addition to variables for the function parameters.
135 * If the node is an `ArrowFunctionExpression`, variables for the parameters are returned.
136 * If the node is a `ClassDeclaration` or a `ClassExpression`, the variable for the class name is returned.
137 * If the node is a `CatchClause`, the variable for the exception is returned.
138 * If the node is an `ImportDeclaration`, variables for all of its specifiers are returned.
139 * If the node is an `ImportSpecifier`, `ImportDefaultSpecifier`, or `ImportNamespaceSpecifier`, the declared variable is returned.
140 * Otherwise, if the node does not declare any variables, an empty array is returned.
141* `getFilename()` - returns the filename associated with the source.
5422a9cc 142* `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.
eb39fafa 143* `getScope()` - returns the [scope](./scope-manager-interface.md#scope-interface) of the currently-traversed node. This information can be used to track references to variables.
5422a9cc 144* `getSourceCode()` - returns a [`SourceCode`](#contextgetsourcecode) object that you can use to work with the source that was passed to ESLint.
eb39fafa 145* `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.md) rule. Returns `true` if a variable with the given name was found and marked as used, otherwise `false`.
456be15e 146* `report(descriptor)` - reports a problem in the code (see the [dedicated section](#contextreport)).
eb39fafa
DC
147
148**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.
149
150### context.getScope()
151
152This method returns the scope which has the following types:
153
154| AST Node Type | Scope Type |
155|:--------------------------|:-----------|
156| `Program` | `global` |
157| `FunctionDeclaration` | `function` |
158| `FunctionExpression` | `function` |
159| `ArrowFunctionExpression` | `function` |
160| `ClassDeclaration` | `class` |
161| `ClassExpression` | `class` |
162| `BlockStatement` ※1 | `block` |
163| `SwitchStatement` ※1 | `switch` |
164| `ForStatement` ※2 | `for` |
165| `ForInStatement` ※2 | `for` |
166| `ForOfStatement` ※2 | `for` |
167| `WithStatement` | `with` |
168| `CatchClause` | `catch` |
169| others | ※3 |
170
171**※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>
172**※2** Only if the `for` statement defines the iteration variable as a block-scoped variable (E.g., `for (let i = 0;;) {}`).<br>
173**※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.).
174
175The returned value is a [`Scope` object](scope-manager-interface.md) defined by the `eslint-scope` package. The `Variable` objects of global variables have some additional properties.
176
177* `variable.writeable` (`boolean | undefined`) ... If `true`, this global variable can be assigned arbitrary value. If `false`, this global variable is read-only.
178* `variable.eslintExplicitGlobal` (`boolean | undefined`) ... If `true`, this global variable was defined by a `/* globals */` directive comment in the source code file.
179* `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.
180* `variable.eslintImplicitGlobalSetting` (`"readonly" | "writable" | undefined`) ... The configured value in config files. This can be different from `variable.writeable` if there are `/* globals */` directive comments.
181
182### context.report()
183
184The 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:
185
186* `message` - the problem message.
187* `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.
188* `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`.
189 * `start` - An object of the start location.
190 * `line` - the 1-based line number at which the problem occurred.
191 * `column` - the 0-based column number at which the problem occurred.
192 * `end` - An object of the end location.
193 * `line` - the 1-based line number at which the problem occurred.
194 * `column` - the 0-based column number at which the problem occurred.
195* `data` - (optional) [placeholder](#using-message-placeholders) data for `message`.
196* `fix` - (optional) a function that applies a [fix](#applying-fixes) to resolve the problem.
197
198Note that at least one of `node` or `loc` is required.
199
200The simplest example is to use just `node` and `message`:
201
202```js
203context.report({
204 node: node,
205 message: "Unexpected identifier"
206});
207```
208
209The 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.
210
211### Using message placeholders
212
213You can also use placeholders in the message and provide `data`:
214
215```js
216{% raw %}
217context.report({
218 node: node,
219 message: "Unexpected identifier: {{ identifier }}",
220 data: {
221 identifier: node.name
222 }
223});
224{% endraw %}
225```
226
227Note that leading and trailing whitespace is optional in message parameters.
228
229The 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.
230
231### `messageId`s
232
233Instead of typing out messages in both the `context.report()` call and your tests, you can use `messageId`s instead.
234
235This allows you to avoid retyping error messages. It also prevents errors reported in different sections of your rule from having out-of-date messages.
236
237```js
238{% raw %}
239// in your rule
240module.exports = {
241 meta: {
242 messages: {
243 avoidName: "Avoid using variables named '{{ name }}'"
244 }
245 },
246 create(context) {
247 return {
248 Identifier(node) {
249 if (node.name === "foo") {
250 context.report({
251 node,
252 messageId: "avoidName",
253 data: {
254 name: "foo",
255 }
256 });
257 }
258 }
259 };
260 }
261};
262
263// in the file to lint:
264
265var foo = 2;
266// ^ error: Avoid using variables named 'foo'
267
268// In your tests:
269var rule = require("../../../lib/rules/my-rule");
270var RuleTester = require("eslint").RuleTester;
271
272var ruleTester = new RuleTester();
273ruleTester.run("my-rule", rule, {
274 valid: ["bar", "baz"],
275 invalid: [
276 {
277 code: "foo",
278 errors: [
279 {
280 messageId: "avoidName"
281 }
282 ]
283 }
284 ]
285});
286{% endraw %}
287```
288
289### Applying Fixes
290
291If 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:
292
293```js
294context.report({
295 node: node,
296 message: "Missing semicolon",
297 fix: function(fixer) {
298 return fixer.insertTextAfter(node, ";");
299 }
300});
301```
302
303Here, 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.
304
6f036462 305**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.
eb39fafa
DC
306
307The `fixer` object has the following methods:
308
309* `insertTextAfter(nodeOrToken, text)` - inserts text after the given node or token
310* `insertTextAfterRange(range, text)` - inserts text after the given range
311* `insertTextBefore(nodeOrToken, text)` - inserts text before the given node or token
312* `insertTextBeforeRange(range, text)` - inserts text before the given range
313* `remove(nodeOrToken)` - removes the given node or token
314* `removeRange(range)` - removes text in the given range
315* `replaceText(nodeOrToken, text)` - replaces the text in the given node or token
316* `replaceTextRange(range, text)` - replaces the text in the given range
317
318The above methods return a `fixing` object.
319The `fix()` function can return the following values:
320
321* A `fixing` object.
322* An array which includes `fixing` objects.
323* An iterable object which enumerates `fixing` objects. Especially, the `fix()` function can be a generator.
324
325If you make a `fix()` function which returns multiple `fixing` objects, those `fixing` objects must not be overlapped.
326
327Best practices for fixes:
328
3291. Avoid any fixes that could change the runtime behavior of code and cause it to stop working.
3301. Make fixes as small as possible. Fixes that are unnecessarily large could conflict with other fixes, and prevent them from being applied.
3311. Only make one fix per message. This is enforced because you must return the result of the fixer operation from `fix()`.
3321. 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.
333 * 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.
334
335 ```js
336 ({ foo : 1 })
337
338 // should get fixed to either
339
340 ({ 'foo': 1 })
341
342 // or
343
344 ({ "foo": 1 })
345 ```
346
347 * 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.md) rule.
348
349### Providing Suggestions
350
351In 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.
352
353In 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)).
354
355```js
356{% raw %}
357context.report({
358 node: node,
359 message: "Unnecessary escape character: \\{{character}}.",
360 data: { character },
361 suggest: [
362 {
363 desc: "Remove the `\\`. This maintains the current functionality.",
364 fix: function(fixer) {
365 return fixer.removeRange(range);
366 }
367 },
368 {
369 desc: "Replace the `\\` with `\\\\` to include the actual backslash character.",
370 fix: function(fixer) {
371 return fixer.insertTextBeforeRange(range, "\\");
372 }
373 }
374 ]
375});
376{% endraw %}
377```
378
5422a9cc 379Note: 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.
eb39fafa
DC
380
381Best practices for suggestions:
382
3831. Don't try to do too much and suggest large refactors that could introduce a lot of breaking changes.
3841. As noted above, don't try to conform to user-defined styles.
385
6f036462
TL
386Suggestions 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.
387
eb39fafa
DC
388#### Suggestion `messageId`s
389
390Instead 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:
391
392```js
393{% raw %}
394module.exports = {
395 meta: {
396 messages: {
397 unnecessaryEscape: "Unnecessary escape character: \\{{character}}.",
398 removeEscape: "Remove the `\\`. This maintains the current functionality.",
399 escapeBackslash: "Replace the `\\` with `\\\\` to include the actual backslash character."
400 }
401 },
402 create: function(context) {
403 // ...
404 context.report({
405 node: node,
406 messageId: 'unnecessaryEscape',
407 data: { character },
408 suggest: [
409 {
410 messageId: "removeEscape",
411 fix: function(fixer) {
412 return fixer.removeRange(range);
413 }
414 },
415 {
416 messageId: "escapeBackslash",
417 fix: function(fixer) {
418 return fixer.insertTextBeforeRange(range, "\\");
419 }
420 }
421 ]
422 });
423 }
424};
425{% endraw %}
426```
427
428#### Placeholders in suggestion messages
429
430You 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)).
431
432Please note that you have to provide `data` on the suggestion's object. Suggestion messages cannot use properties from the overall error's `data`.
433
434```js
435{% raw %}
436module.exports = {
437 meta: {
438 messages: {
439 unnecessaryEscape: "Unnecessary escape character: \\{{character}}.",
440 removeEscape: "Remove `\\` before {{character}}.",
441 }
442 },
443 create: function(context) {
444 // ...
445 context.report({
446 node: node,
447 messageId: "unnecessaryEscape",
448 data: { character }, // data for the unnecessaryEscape overall message
449 suggest: [
450 {
451 messageId: "removeEscape",
452 data: { character }, // data for the removeEscape suggestion message
453 fix: function(fixer) {
454 return fixer.removeRange(range);
455 }
456 }
457 ]
458 });
459 }
460};
461{% endraw %}
462```
463
464### context.options
465
466Some rules require options in order to function correctly. These options appear in configuration (`.eslintrc`, command line, or in comments). For example:
467
468```json
469{
470 "quotes": ["error", "double"]
471}
472```
473
474The `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"`:
475
476```js
477module.exports = {
478 create: function(context) {
479 var isDouble = (context.options[0] === "double");
480
481 // ...
482 }
483};
484```
485
486Since `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.
487
488When using options, make sure that your rule has some logical defaults in case the options are not provided.
489
490### context.getSourceCode()
491
492The `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:
493
494```js
495module.exports = {
496 create: function(context) {
497 var sourceCode = context.getSourceCode();
498
499 // ...
500 }
501};
502```
503
504Once you have an instance of `SourceCode`, you can use the methods on it to work with the code:
505
506* `getText(node)` - returns the source code for the given node. Omit `node` to get the whole source.
507* `getAllComments()` - returns an array of all comments in the source.
508* `getCommentsBefore(nodeOrToken)` - returns an array of comment tokens that occur directly before the given node or token.
509* `getCommentsAfter(nodeOrToken)` - returns an array of comment tokens that occur directly after the given node or token.
510* `getCommentsInside(node)` - returns an array of all comment tokens inside a given node.
511* `getJSDocComment(node)` - returns the JSDoc comment for a given node or `null` if there is none.
512* `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.
513* `getFirstToken(node, skipOptions)` - returns the first token representing the given node.
514* `getFirstTokens(node, countOptions)` - returns the first `count` tokens representing the given node.
515* `getLastToken(node, skipOptions)` - returns the last token representing the given node.
516* `getLastTokens(node, countOptions)` - returns the last `count` tokens representing the given node.
517* `getTokenAfter(nodeOrToken, skipOptions)` - returns the first token after the given node or token.
518* `getTokensAfter(nodeOrToken, countOptions)` - returns `count` tokens after the given node or token.
519* `getTokenBefore(nodeOrToken, skipOptions)` - returns the first token before the given node or token.
520* `getTokensBefore(nodeOrToken, countOptions)` - returns `count` tokens before the given node or token.
521* `getFirstTokenBetween(nodeOrToken1, nodeOrToken2, skipOptions)` - returns the first token between two nodes or tokens.
522* `getFirstTokensBetween(nodeOrToken1, nodeOrToken2, countOptions)` - returns the first `count` tokens between two nodes or tokens.
523* `getLastTokenBetween(nodeOrToken1, nodeOrToken2, skipOptions)` - returns the last token between two nodes or tokens.
524* `getLastTokensBetween(nodeOrToken1, nodeOrToken2, countOptions)` - returns the last `count` tokens between two nodes or tokens.
525* `getTokens(node)` - returns all tokens for the given node.
526* `getTokensBetween(nodeOrToken1, nodeOrToken2)` - returns all tokens between two nodes.
527* `getTokenByRangeStart(index, rangeOptions)` - returns the token whose range starts at the given index in the source.
528* `getNodeByRangeIndex(index)` - returns the deepest node in the AST containing the given source index.
529* `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.
530* `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.
531* `commentsExistBetween(nodeOrToken1, nodeOrToken2)` - returns `true` if comments exist between two nodes.
532
533`skipOptions` is an object which has 3 properties; `skip`, `includeComments`, and `filter`. Default is `{skip: 0, includeComments: false, filter: null}`.
534
535* `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.
536* `includeComments` is a boolean value, the flag to include comment tokens into the result.
537* `filter` is a function which gets a token as the first argument, if the function returns `false` then the result excludes the token.
538
539`countOptions` is an object which has 3 properties; `count`, `includeComments`, and `filter`. Default is `{count: 0, includeComments: false, filter: null}`.
540
541* `count` is a positive integer, the maximum number of returning tokens.
542* `includeComments` is a boolean value, the flag to include comment tokens into the result.
543* `filter` is a function which gets a token as the first argument, if the function returns `false` then the result excludes the token.
544
545`rangeOptions` is an object which has 1 property: `includeComments`.
546
547* `includeComments` is a boolean value, the flag to include comment tokens into the result.
548
549There are also some properties you can access:
550
551* `hasBOM` - the flag to indicate whether or not the source code has Unicode BOM.
552* `text` - the full text of the code being linted. Unicode BOM has been stripped from this text.
553* `ast` - the `Program` node of the AST for the code being linted.
554* `scopeManager` - the [ScopeManager](./scope-manager-interface.md#scopemanager-interface) object of the code.
555* `visitorKeys` - the visitor keys to traverse this AST.
556* `lines` - an array of lines, split according to the specification's definition of line breaks.
557
558You should use a `SourceCode` object whenever you need to get more information about the code being linted.
559
560#### Deprecated
561
562Please note that the following methods have been deprecated and will be removed in a future version of ESLint:
563
564* `getComments()` - replaced by `getCommentsBefore()`, `getCommentsAfter()`, and `getCommentsInside()`
565* `getTokenOrCommentBefore()` - replaced by `getTokenBefore()` with the `{ includeComments: true }` option
566* `getTokenOrCommentAfter()` - replaced by `getTokenAfter()` with the `{ includeComments: true }` option
567* `isSpaceBetweenTokens()` - replaced by `isSpaceBetween()`
568
569### Options Schemas
570
456be15e 571Rules 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`.
eb39fafa
DC
572
573There 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.
574
575However, 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.
576
577```js
578// "yoda": [2, "never", { "exceptRange": true }]
579module.exports = {
580 meta: {
581 schema: [
582 {
583 "enum": ["always", "never"]
584 },
585 {
586 "type": "object",
587 "properties": {
588 "exceptRange": {
589 "type": "boolean"
590 }
591 },
592 "additionalProperties": false
593 }
594 ]
595 },
596};
597```
598
599In 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`.
600
456be15e 601To 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).
eb39fafa
DC
602
603**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).
604
605### Getting the Source
606
607If your rule needs to get the actual JavaScript source to work with, then use the `sourceCode.getText()` method. This method works as follows:
608
609```js
610
611// get all source
612var source = sourceCode.getText();
613
614// get source for just this AST node
615var nodeSource = sourceCode.getText(node);
616
617// get source for AST node plus previous two characters
618var nodeSourceWithPrev = sourceCode.getText(node, 2);
619
620// get source for AST node plus following two characters
621var nodeSourceWithFollowing = sourceCode.getText(node, 0, 2);
622```
623
624In 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.).
625
626### Accessing Comments
627
628While comments are not technically part of the AST, ESLint provides a few ways for rules to access them:
629
630#### sourceCode.getAllComments()
631
632This 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.
633
634#### sourceCode.getCommentsBefore(), sourceCode.getCommentsAfter(), and sourceCode.getCommentsInside()
635
636These 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.
637
638Keep in mind that the results of this method are calculated on demand.
639
640#### Token traversal methods
641
642Finally, comments can be accessed through many of `sourceCode`'s methods using the `includeComments` option.
643
644### Accessing Shebangs
645
646Shebangs are represented by tokens of type `"Shebang"`. They are treated as comments and can be accessed by the methods outlined above.
647
648### Accessing Code Paths
649
650ESLint analyzes code paths while traversing AST.
651You can access that code path objects with five events related to code paths.
652
653[details here](./code-path-analysis.md)
654
655## Rule Unit Tests
656
657Each 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`.
658
659ESLint provides the [`RuleTester`](/docs/developer-guide/nodejs-api.md#ruletester) utility to make it easy to write tests for rules.
660
661## Performance Testing
662
663To keep the linting process efficient and unobtrusive, it is useful to verify the performance impact of new rules or modifications to existing rules.
664
665### Overall Performance
666
667When 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.
668
669```bash
670$ git checkout master
671Switched to branch 'master'
672
673$ npm run perf
674CPU Speed is 2200 with multiplier 7500000
675Performance Run #1: 1394.689313ms
676Performance Run #2: 1423.295351ms
677Performance Run #3: 1385.09515ms
678Performance Run #4: 1382.406982ms
679Performance Run #5: 1409.68566ms
680Performance budget ok: 1394.689313ms (limit: 3409.090909090909ms)
681
682$ git checkout my-rule-branch
683Switched to branch 'my-rule-branch'
684
685$ npm run perf
686CPU Speed is 2200 with multiplier 7500000
687Performance Run #1: 1443.736547ms
688Performance Run #2: 1419.193291ms
689Performance Run #3: 1436.018228ms
690Performance Run #4: 1473.605485ms
691Performance Run #5: 1457.455283ms
692Performance budget ok: 1443.736547ms (limit: 3409.090909090909ms)
693```
694
695### Per-rule Performance
696
697ESLint 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 and relative performance impact as a percentage of total rule processing time.
698
699```bash
700$ TIMING=1 eslint lib
701Rule | Time (ms) | Relative
702:-----------------------|----------:|--------:
703no-multi-spaces | 52.472 | 6.1%
704camelcase | 48.684 | 5.7%
705no-irregular-whitespace | 43.847 | 5.1%
706valid-jsdoc | 40.346 | 4.7%
707handle-callback-err | 39.153 | 4.6%
708space-infix-ops | 35.444 | 4.1%
709no-undefined | 25.693 | 3.0%
710no-shadow | 22.759 | 2.7%
711no-empty-class | 21.976 | 2.6%
712semi | 19.359 | 2.3%
713```
714
715To test one rule explicitly, combine the `--no-eslintrc`, and `--rule` options:
716
717```bash
718$ TIMING=1 eslint --no-eslintrc --rule "quotes: [2, 'double']" lib
719Rule | Time (ms) | Relative
720:------|----------:|--------:
721quotes | 18.066 | 100.0%
722```
723
456be15e
TL
724To see a longer list of results (more than 10), set the environment variable to another value such as `TIMING=50` or `TIMING=all`.
725
eb39fafa
DC
726## Rule Naming Conventions
727
728The rule naming conventions for ESLint are fairly simple:
729
730* If your rule is disallowing something, prefix it with `no-` such as `no-eval` for disallowing `eval()` and `no-debugger` for disallowing `debugger`.
731* If your rule is enforcing the inclusion of something, use a short name without a special prefix.
732* Use dashes between words.
733
734## Runtime Rules
735
736The 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.
737
738Runtime rules are written in the same format as all other rules. Create your rule as you would any other and then follow these steps:
739
7401. Place all of your runtime rules in the same directory (e.g., `eslint_rules`).
5422a9cc 7412. 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.
eb39fafa 7423. Run the [command line interface](../user-guide/command-line-interface.md) using the `--rulesdir` option to specify the location of your runtime rules.