Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 1 | /** |
| 2 | * @fileoverview Rule to flag the use of empty character classes in regular expressions |
| 3 | * @author Ian Christian Myers |
| 4 | */ |
| 5 | |
| 6 | "use strict"; |
| 7 | |
| 8 | //------------------------------------------------------------------------------ |
| 9 | // Helpers |
| 10 | //------------------------------------------------------------------------------ |
| 11 | |
| 12 | /* |
| 13 | * plain-English description of the following regexp: |
| 14 | * 0. `^` fix the match at the beginning of the string |
Tim van der Lippe | 0fb4780 | 2021-11-08 16:23:10 +0000 | [diff] [blame] | 15 | * 1. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following |
| 16 | * 1.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes) |
| 17 | * 1.1. `\\.`: an escape sequence |
| 18 | * 1.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty |
| 19 | * 2. `$`: fix the match at the end of the string |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 20 | */ |
Tim van der Lippe | 0fb4780 | 2021-11-08 16:23:10 +0000 | [diff] [blame] | 21 | const regex = /^([^\\[]|\\.|\[([^\\\]]|\\.)+\])*$/u; |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 22 | |
| 23 | //------------------------------------------------------------------------------ |
| 24 | // Rule Definition |
| 25 | //------------------------------------------------------------------------------ |
| 26 | |
| 27 | module.exports = { |
| 28 | meta: { |
| 29 | type: "problem", |
| 30 | |
| 31 | docs: { |
| 32 | description: "disallow empty character classes in regular expressions", |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 33 | recommended: true, |
| 34 | url: "https://eslint.org/docs/rules/no-empty-character-class" |
| 35 | }, |
| 36 | |
| 37 | schema: [], |
| 38 | |
| 39 | messages: { |
| 40 | unexpected: "Empty class." |
| 41 | } |
| 42 | }, |
| 43 | |
| 44 | create(context) { |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 45 | return { |
Tim van der Lippe | 0fb4780 | 2021-11-08 16:23:10 +0000 | [diff] [blame] | 46 | "Literal[regex]"(node) { |
| 47 | if (!regex.test(node.regex.pattern)) { |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 48 | context.report({ node, messageId: "unexpected" }); |
| 49 | } |
| 50 | } |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 51 | }; |
| 52 | |
| 53 | } |
| 54 | }; |