no-regexp-lookbehind-assertions.js 2.09 KB
Newer Older
liang ce committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
/**
 * @author Toru Nagashima <https://github.com/mysticatea>
 * See LICENSE file in root directory for full license.
 */
"use strict"

const { RegExpValidator } = require("regexpp")
const { getRegExpCalls } = require("../utils")

/**
 * Verify a given regular expression.
 * @param {RuleContext} context The rule context to report.
 * @param {Node} node The AST node to report.
 * @param {string} pattern The pattern part of a RegExp.
 * @param {string} flags The flags part of a RegExp.
 * @returns {void}
 */
function verify(context, node, pattern, flags) {
    try {
        let found = false

        new RegExpValidator({
            onLookaroundAssertionEnter(_start, kind) {
                if (kind === "lookbehind") {
                    found = true
                }
            },
        }).validatePattern(pattern, 0, pattern.length, flags.includes("u"))

        if (found) {
            context.report({ node, messageId: "forbidden" })
        }
    } catch (error) {
        //istanbul ignore else
        if (error.message.startsWith("Invalid regular expression:")) {
            return
        }
        //istanbul ignore next
        throw error
    }
}

module.exports = {
    meta: {
        docs: {
            description: "disallow RegExp lookbehind assertions.",
            category: "ES2018",
            recommended: false,
            url:
                "http://mysticatea.github.io/eslint-plugin-es/rules/no-regexp-lookbehind-assertions.html",
        },
        fixable: null,
        schema: [],
        messages: {
            forbidden: "ES2018 RegExp lookbehind assertions are forbidden.",
        },
    },
    create(context) {
        return {
            "Literal[regex]"(node) {
                const { pattern, flags } = node.regex
                verify(context, node, pattern || "", flags || "")
            },

            "Program:exit"() {
                const scope = context.getScope()
                for (const { node, pattern, flags } of getRegExpCalls(scope)) {
                    verify(context, node, pattern || "", flags || "")
                }
            },
        }
    },
}