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