github-pages-deploy-action/node_modules/eslint/lib/rules/no-obj-calls.js

85 lines
2.6 KiB
JavaScript
Raw Normal View History

2020-03-07 11:45:40 +08:00
/**
* @fileoverview Rule to flag use of an object property of the global object (Math and JSON) as a function
* @author James Allardice
*/
"use strict";
2020-03-31 20:40:00 +08:00
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
2020-05-15 05:33:08 +08:00
const { CALL, CONSTRUCT, ReferenceTracker } = require("eslint-utils");
const getPropertyName = require("./utils/ast-utils").getStaticPropertyName;
2020-03-31 20:40:00 +08:00
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const nonCallableGlobals = ["Atomics", "JSON", "Math", "Reflect"];
2020-05-15 05:33:08 +08:00
/**
* Returns the name of the node to report
* @param {ASTNode} node A node to report
* @returns {string} name to report
*/
function getReportNodeName(node) {
2020-09-13 06:19:45 +08:00
if (node.type === "ChainExpression") {
return getReportNodeName(node.expression);
2020-05-15 05:33:08 +08:00
}
2020-09-13 06:19:45 +08:00
if (node.type === "MemberExpression") {
return getPropertyName(node);
}
return node.name;
2020-05-15 05:33:08 +08:00
}
2020-03-07 11:45:40 +08:00
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "problem",
docs: {
description: "disallow calling global object properties as functions",
category: "Possible Errors",
recommended: true,
url: "https://eslint.org/docs/rules/no-obj-calls"
},
2020-03-31 20:40:00 +08:00
schema: [],
messages: {
2020-05-15 05:33:08 +08:00
unexpectedCall: "'{{name}}' is not a function.",
unexpectedRefCall: "'{{name}}' is reference to '{{ref}}', which is not a function."
2020-03-31 20:40:00 +08:00
}
2020-03-07 11:45:40 +08:00
},
create(context) {
return {
2020-03-31 20:40:00 +08:00
Program() {
const scope = context.getScope();
const tracker = new ReferenceTracker(scope);
const traceMap = {};
2020-05-15 05:33:08 +08:00
for (const g of nonCallableGlobals) {
traceMap[g] = {
[CALL]: true,
[CONSTRUCT]: true
2020-03-31 20:40:00 +08:00
};
}
2020-03-07 11:45:40 +08:00
2020-05-15 05:33:08 +08:00
for (const { node, path } of tracker.iterateGlobalReferences(traceMap)) {
2020-09-13 06:19:45 +08:00
const name = getReportNodeName(node.callee);
2020-05-15 05:33:08 +08:00
const ref = path[0];
const messageId = name === ref ? "unexpectedCall" : "unexpectedRefCall";
context.report({ node, messageId, data: { name, ref } });
2020-03-07 11:45:40 +08:00
}
}
};
}
};