github-pages-deploy-action/node_modules/eslint/lib/rules/new-parens.js

100 lines
3.4 KiB
JavaScript
Raw Permalink Normal View History

2020-03-07 11:45:40 +08:00
/**
* @fileoverview Rule to flag when using constructor without parentheses
* @author Ilya Volodin
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
2020-03-31 20:40:00 +08:00
const astUtils = require("./utils/ast-utils");
2020-03-07 11:45:40 +08:00
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "layout",
docs: {
2020-03-31 20:40:00 +08:00
description: "enforce or disallow parentheses when invoking a constructor with no arguments",
2020-03-07 11:45:40 +08:00
category: "Stylistic Issues",
recommended: false,
url: "https://eslint.org/docs/rules/new-parens"
},
fixable: "code",
2020-03-31 20:40:00 +08:00
schema: {
anyOf: [
{
type: "array",
items: [
{
enum: ["always", "never"]
}
],
minItems: 0,
maxItems: 1
}
]
},
2020-03-07 11:45:40 +08:00
messages: {
2020-03-31 20:40:00 +08:00
missing: "Missing '()' invoking a constructor.",
unnecessary: "Unnecessary '()' invoking a constructor with no arguments."
2020-03-07 11:45:40 +08:00
}
},
create(context) {
2020-03-31 20:40:00 +08:00
const options = context.options;
const always = options[0] !== "never"; // Default is always
2020-03-07 11:45:40 +08:00
const sourceCode = context.getSourceCode();
return {
NewExpression(node) {
if (node.arguments.length !== 0) {
2020-03-31 20:40:00 +08:00
return; // if there are arguments, there have to be parens
2020-03-07 11:45:40 +08:00
}
const lastToken = sourceCode.getLastToken(node);
const hasLastParen = lastToken && astUtils.isClosingParenToken(lastToken);
2020-03-31 20:40:00 +08:00
// `hasParens` is true only if the new expression ends with its own parens, e.g., new new foo() does not end with its own parens
const hasParens = hasLastParen &&
astUtils.isOpeningParenToken(sourceCode.getTokenBefore(lastToken)) &&
node.callee.range[1] < node.range[1];
if (always) {
if (!hasParens) {
context.report({
node,
messageId: "missing",
fix: fixer => fixer.insertTextAfter(node, "()")
});
}
} else {
if (hasParens) {
context.report({
node,
messageId: "unnecessary",
fix: fixer => [
fixer.remove(sourceCode.getTokenBefore(lastToken)),
fixer.remove(lastToken),
fixer.insertTextBefore(node, "("),
fixer.insertTextAfter(node, ")")
]
});
}
2020-03-07 11:45:40 +08:00
}
}
};
}
};