google_forms/node_modules/eslint/lib/rules/no-empty-character-class.js

77 lines
2.2 KiB
JavaScript
Raw Permalink Normal View History

2024-08-09 12:04:48 +00:00
/**
* @fileoverview Rule to flag the use of empty character classes in regular expressions
* @author Ian Christian Myers
*/
"use strict";
2024-08-21 06:34:30 +00:00
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const { RegExpParser, visitRegExpAST } = require("@eslint-community/regexpp");
2024-08-09 12:04:48 +00:00
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
2024-08-21 06:34:30 +00:00
const parser = new RegExpParser();
const QUICK_TEST_REGEX = /\[\]/u;
2024-08-09 12:04:48 +00:00
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
2024-08-21 06:34:30 +00:00
/** @type {import('../shared/types').Rule} */
2024-08-09 12:04:48 +00:00
module.exports = {
meta: {
type: "problem",
docs: {
2024-08-21 06:34:30 +00:00
description: "Disallow empty character classes in regular expressions",
2024-08-09 12:04:48 +00:00
recommended: true,
2024-08-21 06:34:30 +00:00
url: "https://eslint.org/docs/latest/rules/no-empty-character-class"
2024-08-09 12:04:48 +00:00
},
schema: [],
messages: {
unexpected: "Empty class."
}
},
create(context) {
return {
2024-08-21 06:34:30 +00:00
"Literal[regex]"(node) {
const { pattern, flags } = node.regex;
2024-08-09 12:04:48 +00:00
2024-08-21 06:34:30 +00:00
if (!QUICK_TEST_REGEX.test(pattern)) {
return;
}
let regExpAST;
try {
regExpAST = parser.parsePattern(pattern, 0, pattern.length, {
unicode: flags.includes("u"),
unicodeSets: flags.includes("v")
});
} catch {
2024-08-09 12:04:48 +00:00
2024-08-21 06:34:30 +00:00
// Ignore regular expressions that regexpp cannot parse
return;
2024-08-09 12:04:48 +00:00
}
2024-08-21 06:34:30 +00:00
visitRegExpAST(regExpAST, {
onCharacterClassEnter(characterClass) {
if (!characterClass.negate && characterClass.elements.length === 0) {
context.report({ node, messageId: "unexpected" });
}
}
});
}
2024-08-09 12:04:48 +00:00
};
}
};