no-extend-native.js 6.95 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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
/**
 * @fileoverview Rule to flag adding properties to native object's prototypes.
 * @author David Nelson
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const astUtils = require("../util/ast-utils");
const globals = require("globals");

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

const propertyDefinitionMethods = new Set(["defineProperty", "defineProperties"]);

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    meta: {
        type: "suggestion",

        docs: {
            description: "disallow extending native types",
            category: "Best Practices",
            recommended: false,
            url: "https://eslint.org/docs/rules/no-extend-native"
        },

        schema: [
            {
                type: "object",
                properties: {
                    exceptions: {
                        type: "array",
                        items: {
                            type: "string"
                        },
                        uniqueItems: true
                    }
                },
                additionalProperties: false
            }
        ],

        messages: {
            unexpected: "{{builtin}} prototype is read only, properties should not be added."
        }
    },

    create(context) {

        const config = context.options[0] || {};
        const exceptions = new Set(config.exceptions || []);
        const modifiedBuiltins = new Set(
            Object.keys(globals.builtin)
                .filter(builtin => builtin[0].toUpperCase() === builtin[0])
                .filter(builtin => !exceptions.has(builtin))
        );

        /**
         * Reports a lint error for the given node.
         * @param {ASTNode} node The node to report.
         * @param {string} builtin The name of the native builtin being extended.
         * @returns {void}
         */
        function reportNode(node, builtin) {
            context.report({
                node,
                messageId: "unexpected",
                data: {
                    builtin
                }
            });
        }

        /**
         * Check to see if the `prototype` property of the given object
         * identifier node is being accessed.
         * @param {ASTNode} identifierNode The Identifier representing the object
         * to check.
         * @returns {boolean} True if the identifier is the object of a
         * MemberExpression and its `prototype` property is being accessed,
         * false otherwise.
         */
        function isPrototypePropertyAccessed(identifierNode) {
            return Boolean(
                identifierNode &&
                identifierNode.parent &&
                identifierNode.parent.type === "MemberExpression" &&
                identifierNode.parent.object === identifierNode &&
                astUtils.getStaticPropertyName(identifierNode.parent) === "prototype"
            );
        }

        /**
         * Checks that an identifier is an object of a prototype whose member
         * is being assigned in an AssignmentExpression.
         * Example: Object.prototype.foo = "bar"
         * @param {ASTNode} identifierNode The identifier to check.
         * @returns {boolean} True if the identifier's prototype is modified.
         */
        function isInPrototypePropertyAssignment(identifierNode) {
            return Boolean(
                isPrototypePropertyAccessed(identifierNode) &&
                identifierNode.parent.parent.type === "MemberExpression" &&
                identifierNode.parent.parent.parent.type === "AssignmentExpression" &&
                identifierNode.parent.parent.parent.left === identifierNode.parent.parent
            );
        }

        /**
         * Checks that an identifier is an object of a prototype whose member
         * is being extended via the Object.defineProperty() or
         * Object.defineProperties() methods.
         * Example: Object.defineProperty(Array.prototype, "foo", ...)
         * Example: Object.defineProperties(Array.prototype, ...)
         * @param {ASTNode} identifierNode The identifier to check.
         * @returns {boolean} True if the identifier's prototype is modified.
         */
        function isInDefinePropertyCall(identifierNode) {
            return Boolean(
                isPrototypePropertyAccessed(identifierNode) &&
                identifierNode.parent.parent.type === "CallExpression" &&
                identifierNode.parent.parent.arguments[0] === identifierNode.parent &&
                identifierNode.parent.parent.callee.type === "MemberExpression" &&
                identifierNode.parent.parent.callee.object.type === "Identifier" &&
                identifierNode.parent.parent.callee.object.name === "Object" &&
                identifierNode.parent.parent.callee.property.type === "Identifier" &&
                propertyDefinitionMethods.has(identifierNode.parent.parent.callee.property.name)
            );
        }

        /**
         * Check to see if object prototype access is part of a prototype
         * extension. There are three ways a prototype can be extended:
         * 1. Assignment to prototype property (Object.prototype.foo = 1)
         * 2. Object.defineProperty()/Object.defineProperties() on a prototype
         * If prototype extension is detected, report the AssignmentExpression
         * or CallExpression node.
         * @param {ASTNode} identifierNode The Identifier representing the object
         * which prototype is being accessed and possibly extended.
         * @returns {void}
         */
        function checkAndReportPrototypeExtension(identifierNode) {
            if (isInPrototypePropertyAssignment(identifierNode)) {

                // Identifier --> MemberExpression --> MemberExpression --> AssignmentExpression
                reportNode(identifierNode.parent.parent.parent, identifierNode.name);
            } else if (isInDefinePropertyCall(identifierNode)) {

                // Identifier --> MemberExpression --> CallExpression
                reportNode(identifierNode.parent.parent, identifierNode.name);
            }
        }

        return {

            "Program:exit"() {
                const globalScope = context.getScope();

                modifiedBuiltins.forEach(builtin => {
                    const builtinVar = globalScope.set.get(builtin);

                    if (builtinVar && builtinVar.references) {
                        builtinVar.references
                            .map(ref => ref.identifier)
                            .forEach(checkAndReportPrototypeExtension);
                    }
                });
            }
        };

    }
};