]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/developer-guide/working-with-rules-deprecated.md
import 8.23.1 source
[pve-eslint.git] / eslint / docs / src / developer-guide / working-with-rules-deprecated.md
1 ---
2 title: Working with Rules (Deprecated)
3 layout: doc
4
5 ---
6
7 **Note:** This page covers the deprecated rule format for ESLint <= 2.13.1. [This is the most recent rule format](./working-with-rules).
8
9 Each rule in ESLint has two files named with its identifier (for example, `no-extra-semi`).
10
11 * in the `lib/rules` directory: a source file (for example, `no-extra-semi.js`)
12 * in the `tests/lib/rules` directory: a test file (for example, `no-extra-semi.js`)
13
14 **Important:** If you submit a **core** rule to the ESLint repository, you **must** follow some conventions explained below.
15
16 Here is the basic format of the source file for a rule:
17
18 ```js
19 /**
20 * @fileoverview Rule to disallow unnecessary semicolons
21 * @author Nicholas C. Zakas
22 */
23
24 "use strict";
25
26 //------------------------------------------------------------------------------
27 // Rule Definition
28 //------------------------------------------------------------------------------
29
30 module.exports = function(context) {
31 return {
32 // callback functions
33 };
34 };
35
36 module.exports.schema = []; // no options
37 ```
38
39 ## Rule Basics
40
41 `schema` (array) specifies the [options](#options-schemas) so ESLint can prevent invalid [rule configurations](../user-guide/configuring/rules#configuring-rules)
42
43 `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:
44
45 * if a key is a node type, ESLint calls that **visitor** function while going **down** the tree
46 * if a key is a node type plus `:exit`, ESLint calls that **visitor** function while going **up** the tree
47 * if a key is an event name, ESLint calls that **handler** function for [code path analysis](./code-path-analysis)
48
49 A rule can use the current node and its surrounding tree to report or fix problems.
50
51 Here are methods for the [array-callback-return](../rules/array-callback-return) rule:
52
53 ```js
54 function checkLastSegment (node) {
55 // report problem for function if last code path segment is reachable
56 }
57
58 module.exports = function(context) {
59 // declare the state of the rule
60 return {
61 ReturnStatement: function(node) {
62 // at a ReturnStatement node while going down
63 },
64 // at a function expression node while going up:
65 "FunctionExpression:exit": checkLastSegment,
66 "ArrowFunctionExpression:exit": checkLastSegment,
67 onCodePathStart: function (codePath, node) {
68 // at the start of analyzing a code path
69 },
70 onCodePathEnd: function(codePath, node) {
71 // at the end of analyzing a code path
72 }
73 };
74 };
75 ```
76
77 ## The Context Object
78
79 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:
80
81 * `parserOptions` - the parser options configured for this run (more details [here](../user-guide/configuring/language-options#specifying-parser-options)).
82 * `id` - the rule ID.
83 * `options` - an array of rule options.
84 * `settings` - the `settings` from configuration.
85 * `parserPath` - the full path to the `parser` from configuration.
86
87 Additionally, the `context` object has the following methods:
88
89 * `getAncestors()` - returns an array of ancestor nodes based on the current traversal.
90 * `getDeclaredVariables(node)` - returns the declared variables on the given node.
91 * `getFilename()` - returns the filename associated with the source.
92 * `getScope()` - returns the current scope.
93 * `getSourceCode()` - returns a `SourceCode` object that you can use to work with the source that was passed to ESLint
94 * `markVariableAsUsed(name)` - marks the named variable in scope as used. This affects the [no-unused-vars](../rules/no-unused-vars) rule.
95 * `report(descriptor)` - reports a problem in the code.
96
97 **Deprecated:** The following methods on the `context` object are deprecated. Please use the corresponding methods on `SourceCode` instead:
98
99 * `getAllComments()` - returns an array of all comments in the source. Use `sourceCode.getAllComments()` instead.
100 * `getComments(node)` - returns the leading and trailing comments arrays for the given node. Use `sourceCode.getComments(node)` instead.
101 * `getFirstToken(node)` - returns the first token representing the given node. Use `sourceCode.getFirstToken(node)` instead.
102 * `getFirstTokens(node, count)` - returns the first `count` tokens representing the given node. Use `sourceCode.getFirstTokens(node, count)` instead.
103 * `getJSDocComment(node)` - returns the JSDoc comment for a given node or `null` if there is none. Use `sourceCode.getJSDocComment(node)` instead.
104 * `getLastToken(node)` - returns the last token representing the given node. Use `sourceCode.getLastToken(node)` instead.
105 * `getLastTokens(node, count)` - returns the last `count` tokens representing the given node. Use `sourceCode.getLastTokens(node, count)` instead.
106 * `getNodeByRangeIndex(index)` - returns the deepest node in the AST containing the given source index. Use `sourceCode.getNodeByRangeIndex(index)` instead.
107 * `getSource(node)` - returns the source code for the given node. Omit `node` to get the whole source. Use `sourceCode.getText(node)` instead.
108 * `getSourceLines()` - returns the entire source code split into an array of string lines. Use `sourceCode.lines` instead.
109 * `getTokenAfter(nodeOrToken)` - returns the first token after the given node or token. Use `sourceCode.getTokenAfter(nodeOrToken)` instead.
110 * `getTokenBefore(nodeOrToken)` - returns the first token before the given node or token. Use `sourceCode.getTokenBefore(nodeOrToken)` instead.
111 * `getTokenByRangeStart(index)` - returns the token whose range starts at the given index in the source. Use `sourceCode.getTokenByRangeStart(index)` instead.
112 * `getTokens(node)` - returns all tokens for the given node. Use `sourceCode.getTokens(node)` instead.
113 * `getTokensAfter(nodeOrToken, count)` - returns `count` tokens after the given node or token. Use `sourceCode.getTokensAfter(nodeOrToken, count)` instead.
114 * `getTokensBefore(nodeOrToken, count)` - returns `count` tokens before the given node or token. Use `sourceCode.getTokensBefore(nodeOrToken, count)` instead.
115 * `getTokensBetween(node1, node2)` - returns the tokens between two nodes. Use `sourceCode.getTokensBetween(node1, node2)` instead.
116 * `report(node, [location], message)` - reports a problem in the code.
117
118 ### context.report()
119
120 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:
121
122 * `message` - the problem message.
123 * `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.
124 * `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`.
125 * `line` - the 1-based line number at which the problem occurred.
126 * `column` - the 0-based column number at which the problem occurred.
127 * `data` - (optional) placeholder data for `message`.
128 * `fix` - (optional) a function that applies a fix to resolve the problem.
129
130 Note that at least one of `node` or `loc` is required.
131
132 The simplest example is to use just `node` and `message`:
133
134 ```js
135 context.report({
136 node: node,
137 message: "Unexpected identifier"
138 });
139 ```
140
141 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.
142
143 You can also use placeholders in the message and provide `data`:
144
145 ```js
146 {% raw %}
147 context.report({
148 node: node,
149 message: "Unexpected identifier: {{ identifier }}",
150 data: {
151 identifier: node.name
152 }
153 });
154 {% endraw %}
155 ```
156
157 Note that leading and trailing whitespace is optional in message parameters.
158
159 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.
160
161 ### Applying Fixes
162
163 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:
164
165 ```js
166 context.report({
167 node: node,
168 message: "Missing semicolon".
169 fix: function(fixer) {
170 return fixer.insertTextAfter(node, ";");
171 }
172 });
173 ```
174
175 Here, the `fix()` function is used to insert a semicolon after the node. Note that the fix is not immediately applied and may not be applied at all if there are conflicts with other fixes. If the fix cannot be applied, then the problem message is reported as usual; if the fix can be applied, then the problem message is not reported.
176
177 The `fixer` object has the following methods:
178
179 * `insertTextAfter(nodeOrToken, text)` - inserts text after the given node or token
180 * `insertTextAfterRange(range, text)` - inserts text after the given range
181 * `insertTextBefore(nodeOrToken, text)` - inserts text before the given node or token
182 * `insertTextBeforeRange(range, text)` - inserts text before the given range
183 * `remove(nodeOrToken)` - removes the given node or token
184 * `removeRange(range)` - removes text in the given range
185 * `replaceText(nodeOrToken, text)` - replaces the text in the given node or token
186 * `replaceTextRange(range, text)` - replaces the text in the given range
187
188 Best practices for fixes:
189
190 1. Make fixes that are as small as possible. Anything more than a single character is risky and could prevent other, simpler fixes from being made.
191 1. Only make one fix per message. This is enforced because you must return the result of the fixer operation from `fix()`.
192 1. Fixes should not introduce clashes with other rules. You can accidentally introduce a new problem that won't be reported until ESLint is run again. Another good reason to make as small a fix as possible.
193
194 ### context.options
195
196 Some rules require options in order to function correctly. These options appear in configuration (`.eslintrc`, command line, or in comments). For example:
197
198 ```json
199 {
200 "quotes": [2, "double"]
201 }
202 ```
203
204 The `quotes` rule in this example has one option, `"double"` (the `2` 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"`:
205
206 ```js
207 module.exports = function(context) {
208
209 var isDouble = (context.options[0] === "double");
210
211 // ...
212 }
213 ```
214
215 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.
216
217 When using options, make sure that your rule has some logic defaults in case the options are not provided.
218
219 ### context.getSourceCode()
220
221 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:
222
223 ```js
224 module.exports = function(context) {
225
226 var sourceCode = context.getSourceCode();
227
228 // ...
229 }
230 ```
231
232 Once you have an instance of `SourceCode`, you can use the methods on it to work with the code:
233
234 * `getAllComments()` - returns an array of all comments in the source.
235 * `getComments(node)` - returns the leading and trailing comments arrays for the given node.
236 * `getFirstToken(node)` - returns the first token representing the given node.
237 * `getFirstTokens(node, count)` - returns the first `count` tokens representing the given node.
238 * `getJSDocComment(node)` - returns the JSDoc comment for a given node or `null` if there is none.
239 * `getLastToken(node)` - returns the last token representing the given node.
240 * `getLastTokens(node, count)` - returns the last `count` tokens representing the given node.
241 * `getNodeByRangeIndex(index)` - returns the deepest node in the AST containing the given source index.
242 * `isSpaceBetweenTokens(first, second)` - returns true if there is a whitespace character between the two tokens.
243 * `getText(node)` - returns the source code for the given node. Omit `node` to get the whole source.
244 * `getTokenAfter(nodeOrToken)` - returns the first token after the given node or token.
245 * `getTokenBefore(nodeOrToken)` - returns the first token before the given node or token.
246 * `getTokenByRangeStart(index)` - returns the token whose range starts at the given index in the source.
247 * `getTokens(node)` - returns all tokens for the given node.
248 * `getTokensAfter(nodeOrToken, count)` - returns `count` tokens after the given node or token.
249 * `getTokensBefore(nodeOrToken, count)` - returns `count` tokens before the given node or token.
250 * `getTokensBetween(node1, node2)` - returns the tokens between two nodes.
251
252 There are also some properties you can access:
253
254 * `hasBOM` - the flag to indicate whether or not the source code has Unicode BOM.
255 * `text` - the full text of the code being linted. Unicode BOM has been stripped from this text.
256 * `ast` - the `Program` node of the AST for the code being linted.
257 * `lines` - an array of lines, split according to the specification's definition of line breaks.
258
259 You should use a `SourceCode` object whenever you need to get more information about the code being linted.
260
261 ### Options Schemas
262
263 Rules may export a `schema` property, which is a [JSON schema](http://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`.
264
265 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.
266
267 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.
268
269 ```js
270 // "yoda": [2, "never", { "exceptRange": true }]
271 module.exports.schema = [
272 {
273 "enum": ["always", "never"]
274 },
275 {
276 "type": "object",
277 "properties": {
278 "exceptRange": {
279 "type": "boolean"
280 }
281 },
282 "additionalProperties": false
283 }
284 ];
285 ```
286
287 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`.
288
289 To learn more about JSON Schema, we recommend looking at some [examples](http://json-schema.org/examples.html) to start, and also reading [Understanding JSON Schema](http://spacetelescope.github.io/understanding-json-schema/) (a free ebook).
290
291 ### Getting the Source
292
293 If your rule needs to get the actual JavaScript source to work with, then use the `sourceCode.getText()` method. This method works as follows:
294
295 ```js
296
297 // get all source
298 var source = sourceCode.getText();
299
300 // get source for just this AST node
301 var nodeSource = sourceCode.getText(node);
302
303 // get source for AST node plus previous two characters
304 var nodeSourceWithPrev = sourceCode.getText(node, 2);
305
306 // get source for AST node plus following two characters
307 var nodeSourceWithFollowing = sourceCode.getText(node, 0, 2);
308 ```
309
310 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.).
311
312 ### Accessing comments
313
314 If you need to access comments for a specific node you can use `sourceCode.getComments(node)`:
315
316 ```js
317 // the "comments" variable has a "leading" and "trailing" property containing
318 // its leading and trailing comments, respectively
319 var comments = sourceCode.getComments(node);
320 ```
321
322 Keep in mind that comments are technically not a part of the AST and are only attached to it on demand, i.e. when you call `getComments()`.
323
324 **Note:** One of the libraries adds AST node properties for comments - do not use these properties. Always use `sourceCode.getComments()` as this is the only guaranteed API for accessing comments (we will likely change how comments are handled later).
325
326 ### Accessing Code Paths
327
328 ESLint analyzes code paths while traversing AST.
329 You can access that code path objects with five events related to code paths.
330
331 [details here](./code-path-analysis)
332
333 ## Rule Unit Tests
334
335 Each rule 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 your rule source file is `lib/rules/foo.js` then your test file should be `tests/lib/rules/foo.js`.
336
337 For your rule, be sure to test:
338
339 1. All instances that should be flagged as warnings.
340 1. At least one pattern that should **not** be flagged as a warning.
341
342 The basic pattern for a rule unit test file is:
343
344 ```js
345 /**
346 * @fileoverview Tests for no-with rule.
347 * @author Nicholas C. Zakas
348 */
349
350 "use strict";
351
352 //------------------------------------------------------------------------------
353 // Requirements
354 //------------------------------------------------------------------------------
355
356 var rule = require("../../../lib/rules/no-with"),
357 RuleTester = require("../../../lib/testers/rule-tester");
358
359 //------------------------------------------------------------------------------
360 // Tests
361 //------------------------------------------------------------------------------
362
363 var ruleTester = new RuleTester();
364 ruleTester.run("no-with", rule, {
365 valid: [
366 "foo.bar()"
367 ],
368 invalid: [
369 {
370 code: "with(foo) { bar() }",
371 errors: [{ message: "Unexpected use of 'with' statement.", type: "WithStatement"}]
372 }
373 ]
374 });
375 ```
376
377 Be sure to replace the value of `"no-with"` with your rule's ID. There are plenty of examples in the `tests/lib/rules/` directory.
378
379 ### Valid Code
380
381 Each valid case can be either a string or an object. The object form is used when you need to specify additional global variables or arguments for the rule. For example, the following defines `window` as a global variable for code that should not trigger the rule being tested:
382
383 ```js
384 valid: [
385 {
386 code: "window.alert()",
387 globals: [ "window" ]
388 }
389 ]
390 ```
391
392 You can also pass options to the rule (if it accepts them). These arguments are equivalent to how people can configure rules in their `.eslintrc` file. For example:
393
394 ```js
395 valid: [
396 {
397 code: "var msg = 'Hello';",
398 options: [ "single" ]
399 }
400 ]
401 ```
402
403 The `options` property must be an array of options. This gets passed through to `context.options` in the rule.
404
405 ### Invalid Code
406
407 Each invalid case must be an object containing the code to test and at least one message that is produced by the rule. The `errors` key specifies an array of objects, each containing a message (your rule may trigger multiple messages for the same code). You should also specify the type of AST node you expect to receive back using the `type` key. The AST node should represent the actual spot in the code where there is a problem. For example:
408
409 ```js
410 invalid: [
411 {
412 code: "function doSomething() { var f; if (true) { var build = true; } f = build; }",
413 errors: [
414 { message: "build used outside of binding context.", type: "Identifier" }
415 ]
416 }
417 ]
418 ```
419
420 In this case, the message is specific to the variable being used and the AST node type is `Identifier`.
421
422 Similar to the valid cases, you can also specify `options` to be passed to the rule:
423
424 ```js
425 invalid: [
426 {
427 code: "function doSomething() { var f; if (true) { var build = true; } f = build; }",
428 options: [ "double" ],
429 errors: [
430 { message: "build used outside of binding context.", type: "Identifier" }
431 ]
432 }
433 ]
434 ```
435
436 For simpler cases where the only thing that really matters is the error message, you can also specify any `errors` as strings. You can also have some strings and some objects, if you like.
437
438 ```js
439 invalid: [
440 {
441 code: "'single quotes'",
442 options: ["double"],
443 errors: ["Strings must use doublequote."]
444 }
445 ]
446 ```
447
448 ### Specifying Parser Options
449
450 Some tests require that a certain parser configuration must be used. This can be specified in test specifications via the `parserOptions` setting.
451
452 For example, to set `ecmaVersion` to 6 (in order to use constructs like `for ... of`):
453
454 ```js
455 valid: [
456 {
457 code: "for (x of a) doSomething();",
458 parserOptions: { ecmaVersion: 6 }
459 }
460 ]
461 ```
462
463 If you are working with ES6 modules:
464
465 ```js
466 valid: [
467 {
468 code: "export default function () {};",
469 parserOptions: { ecmaVersion: 6, sourceType: "module" }
470 }
471 ]
472 ```
473
474 For non-version specific features such as JSX:
475
476 ```js
477 valid: [
478 {
479 code: "var foo = <div>{bar}</div>",
480 parserOptions: { ecmaFeatures: { jsx: true } }
481 }
482 ]
483 ```
484
485 The options available and the expected syntax for `parserOptions` is the same as those used in [configuration](../user-guide/configuring/language-options#specifying-parser-options).
486
487 ### Write Several Tests
488
489 Provide as many unit tests as possible. Your pull request will never be turned down for having too many tests submitted with it!
490
491 ## Performance Testing
492
493 To keep the linting process efficient and unobtrusive, it is useful to verify the performance impact of new rules or modifications to existing rules.
494
495 ### Overall Performance
496
497 The `npm run perf` command gives a high-level overview of ESLint running time with default rules (`eslint:recommended`) enabled.
498
499 ```bash
500 $ git checkout main
501 Switched to branch 'main'
502
503 $ npm run perf
504 CPU Speed is 2200 with multiplier 7500000
505 Performance Run #1: 1394.689313ms
506 Performance Run #2: 1423.295351ms
507 Performance Run #3: 1385.09515ms
508 Performance Run #4: 1382.406982ms
509 Performance Run #5: 1409.68566ms
510 Performance budget ok: 1394.689313ms (limit: 3409.090909090909ms)
511
512 $ git checkout my-rule-branch
513 Switched to branch 'my-rule-branch'
514
515 $ npm run perf
516 CPU Speed is 2200 with multiplier 7500000
517 Performance Run #1: 1443.736547ms
518 Performance Run #2: 1419.193291ms
519 Performance Run #3: 1436.018228ms
520 Performance Run #4: 1473.605485ms
521 Performance Run #5: 1457.455283ms
522 Performance budget ok: 1443.736547ms (limit: 3409.090909090909ms)
523 ```
524
525 ### Per-rule Performance
526
527 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 and relative performance impact as a percentage of total rule processing time.
528
529 ```bash
530 $ TIMING=1 eslint lib
531 Rule | Time (ms) | Relative
532 :-----------------------|----------:|--------:
533 no-multi-spaces | 52.472 | 6.1%
534 camelcase | 48.684 | 5.7%
535 no-irregular-whitespace | 43.847 | 5.1%
536 valid-jsdoc | 40.346 | 4.7%
537 handle-callback-err | 39.153 | 4.6%
538 space-infix-ops | 35.444 | 4.1%
539 no-undefined | 25.693 | 3.0%
540 no-shadow | 22.759 | 2.7%
541 no-empty-class | 21.976 | 2.6%
542 semi | 19.359 | 2.3%
543 ```
544
545 To test one rule explicitly, combine the `--no-eslintrc`, and `--rule` options:
546
547 ```bash
548 $ TIMING=1 eslint --no-eslintrc --rule "quotes: [2, 'double']" lib
549 Rule | Time (ms) | Relative
550 :------|----------:|--------:
551 quotes | 18.066 | 100.0%
552 ```
553
554 ## Rule Naming Conventions
555
556 The rule naming conventions for ESLint are fairly simple:
557
558 * If your rule is disallowing something, prefix it with `no-` such as `no-eval` for disallowing `eval()` and `no-debugger` for disallowing `debugger`.
559 * If your rule is enforcing the inclusion of something, use a short name without a special prefix.
560 * Keep your rule names as short as possible, use abbreviations where appropriate, and no more than four words.
561 * Use dashes between words.
562
563 ## Rule Acceptance Criteria
564
565 Because rules are highly personal (and therefore very contentious), accepted rules should:
566
567 * Not be library-specific.
568 * Demonstrate a possible issue that can be resolved by rewriting the code.
569 * Be general enough so as to apply for a large number of developers.
570 * Not be the opposite of an existing rule.
571 * Not overlap with an existing rule.
572
573 ## Runtime Rules
574
575 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.
576
577 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:
578
579 1. Place all of your runtime rules in the same directory (i.e., `eslint_rules`).
580 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 `1` or `2` in the configuration file.
581 3. Run the [command line interface](../user-guide/command-line-interface) using the `--rulesdir` option to specify the location of your runtime rules.