2 title: Working with Rules (Deprecated)
7 **Note:** This page covers the deprecated rule format for ESLint <= 2.13.1. [This is the most recent rule format](./working-with-rules).
9 Each rule in ESLint has two files named with its identifier (for example, `no-extra-semi`).
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`)
14 **Important:** If you submit a **core** rule to the ESLint repository, you **must** follow some conventions explained below.
16 Here is the basic format of the source file for a rule:
20 * @fileoverview Rule to disallow unnecessary semicolons
21 * @author Nicholas C. Zakas
26 //------------------------------------------------------------------------------
28 //------------------------------------------------------------------------------
30 module.exports = function(context) {
36 module.exports.schema = []; // no options
41 `schema` (array) specifies the [options](#options-schemas) so ESLint can prevent invalid [rule configurations](../user-guide/configuring/rules#configuring-rules)
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:
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)
49 A rule can use the current node and its surrounding tree to report or fix problems.
51 Here are methods for the [array-callback-return](../rules/array-callback-return) rule:
54 function checkLastSegment (node) {
55 // report problem for function if last code path segment is reachable
58 module.exports = function(context) {
59 // declare the state of the rule
61 ReturnStatement: function(node) {
62 // at a ReturnStatement node while going down
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
70 onCodePathEnd: function(codePath, node) {
71 // at the end of analyzing a code path
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:
81 * `parserOptions` - the parser options configured for this run (more details [here](../user-guide/configuring/language-options#specifying-parser-options)).
83 * `options` - an array of rule options.
84 * `settings` - the `settings` from configuration.
85 * `parserPath` - the full path to the `parser` from configuration.
87 Additionally, the `context` object has the following methods:
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.
97 **Deprecated:** The following methods on the `context` object are deprecated. Please use the corresponding methods on `SourceCode` instead:
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.
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:
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.
130 Note that at least one of `node` or `loc` is required.
132 The simplest example is to use just `node` and `message`:
137 message: "Unexpected identifier"
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.
143 You can also use placeholders in the message and provide `data`:
149 message: "Unexpected identifier: {{ identifier }}",
151 identifier: node.name
157 Note that leading and trailing whitespace is optional in message parameters.
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.
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:
168 message: "Missing semicolon".
169 fix: function(fixer) {
170 return fixer.insertTextAfter(node, ";");
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.
177 The `fixer` object has the following methods:
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
188 Best practices for fixes:
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.
196 Some rules require options in order to function correctly. These options appear in configuration (`.eslintrc`, command line, or in comments). For example:
200 "quotes": [2, "double"]
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"`:
207 module.exports = function(context) {
209 var isDouble = (context.options[0] === "double");
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.
217 When using options, make sure that your rule has some logic defaults in case the options are not provided.
219 ### context.getSourceCode()
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:
224 module.exports = function(context) {
226 var sourceCode = context.getSourceCode();
232 Once you have an instance of `SourceCode`, you can use the methods on it to work with the code:
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.
252 There are also some properties you can access:
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.
259 You should use a `SourceCode` object whenever you need to get more information about the code being linted.
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`.
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.
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.
270 // "yoda": [2, "never", { "exceptRange": true }]
271 module.exports.schema = [
273 "enum": ["always", "never"]
282 "additionalProperties": false
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`.
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).
291 ### Getting the Source
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:
298 var source = sourceCode.getText();
300 // get source for just this AST node
301 var nodeSource = sourceCode.getText(node);
303 // get source for AST node plus previous two characters
304 var nodeSourceWithPrev = sourceCode.getText(node, 2);
306 // get source for AST node plus following two characters
307 var nodeSourceWithFollowing = sourceCode.getText(node, 0, 2);
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.).
312 ### Accessing comments
314 If you need to access comments for a specific node you can use `sourceCode.getComments(node)`:
317 // the "comments" variable has a "leading" and "trailing" property containing
318 // its leading and trailing comments, respectively
319 var comments = sourceCode.getComments(node);
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()`.
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).
326 ### Accessing Code Paths
328 ESLint analyzes code paths while traversing AST.
329 You can access that code path objects with five events related to code paths.
331 [details here](./code-path-analysis)
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`.
337 For your rule, be sure to test:
339 1. All instances that should be flagged as warnings.
340 1. At least one pattern that should **not** be flagged as a warning.
342 The basic pattern for a rule unit test file is:
346 * @fileoverview Tests for no-with rule.
347 * @author Nicholas C. Zakas
352 //------------------------------------------------------------------------------
354 //------------------------------------------------------------------------------
356 var rule = require("../../../lib/rules/no-with"),
357 RuleTester = require("../../../lib/testers/rule-tester");
359 //------------------------------------------------------------------------------
361 //------------------------------------------------------------------------------
363 var ruleTester = new RuleTester();
364 ruleTester.run("no-with", rule, {
370 code: "with(foo) { bar() }",
371 errors: [{ message: "Unexpected use of 'with' statement.", type: "WithStatement"}]
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.
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:
386 code: "window.alert()",
387 globals: [ "window" ]
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:
397 code: "var msg = 'Hello';",
398 options: [ "single" ]
403 The `options` property must be an array of options. This gets passed through to `context.options` in the rule.
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:
412 code: "function doSomething() { var f; if (true) { var build = true; } f = build; }",
414 { message: "build used outside of binding context.", type: "Identifier" }
420 In this case, the message is specific to the variable being used and the AST node type is `Identifier`.
422 Similar to the valid cases, you can also specify `options` to be passed to the rule:
427 code: "function doSomething() { var f; if (true) { var build = true; } f = build; }",
428 options: [ "double" ],
430 { message: "build used outside of binding context.", type: "Identifier" }
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.
441 code: "'single quotes'",
443 errors: ["Strings must use doublequote."]
448 ### Specifying Parser Options
450 Some tests require that a certain parser configuration must be used. This can be specified in test specifications via the `parserOptions` setting.
452 For example, to set `ecmaVersion` to 6 (in order to use constructs like `for ... of`):
457 code: "for (x of a) doSomething();",
458 parserOptions: { ecmaVersion: 6 }
463 If you are working with ES6 modules:
468 code: "export default function () {};",
469 parserOptions: { ecmaVersion: 6, sourceType: "module" }
474 For non-version specific features such as JSX:
479 code: "var foo = <div>{bar}</div>",
480 parserOptions: { ecmaFeatures: { jsx: true } }
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).
487 ### Write Several Tests
489 Provide as many unit tests as possible. Your pull request will never be turned down for having too many tests submitted with it!
491 ## Performance Testing
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.
495 ### Overall Performance
497 The `npm run perf` command gives a high-level overview of ESLint running time with default rules (`eslint:recommended`) enabled.
501 Switched to branch 'main'
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)
512 $ git checkout my-rule-branch
513 Switched to branch 'my-rule-branch'
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)
525 ### Per-rule Performance
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.
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%
545 To test one rule explicitly, combine the `--no-eslintrc`, and `--rule` options:
548 $ TIMING=1 eslint --no-eslintrc --rule "quotes: [2, 'double']" lib
549 Rule | Time (ms) | Relative
550 :------|----------:|--------:
551 quotes | 18.066 | 100.0%
554 ## Rule Naming Conventions
556 The rule naming conventions for ESLint are fairly simple:
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.
563 ## Rule Acceptance Criteria
565 Because rules are highly personal (and therefore very contentious), accepted rules should:
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.
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.
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:
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.