]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/new-parens.js
bump version to 8.41.0-3
[pve-eslint.git] / eslint / lib / rules / new-parens.js
1 /**
2 * @fileoverview Rule to flag when using constructor without parentheses
3 * @author Ilya Volodin
4 */
5
6 "use strict";
7
8 //------------------------------------------------------------------------------
9 // Requirements
10 //------------------------------------------------------------------------------
11
12 const astUtils = require("./utils/ast-utils");
13
14 //------------------------------------------------------------------------------
15 // Helpers
16 //------------------------------------------------------------------------------
17
18 //------------------------------------------------------------------------------
19 // Rule Definition
20 //------------------------------------------------------------------------------
21
22 /** @type {import('../shared/types').Rule} */
23 module.exports = {
24 meta: {
25 type: "layout",
26
27 docs: {
28 description: "Enforce or disallow parentheses when invoking a constructor with no arguments",
29 recommended: false,
30 url: "https://eslint.org/docs/latest/rules/new-parens"
31 },
32
33 fixable: "code",
34 schema: [
35 {
36 enum: ["always", "never"]
37 }
38 ],
39 messages: {
40 missing: "Missing '()' invoking a constructor.",
41 unnecessary: "Unnecessary '()' invoking a constructor with no arguments."
42 }
43 },
44
45 create(context) {
46 const options = context.options;
47 const always = options[0] !== "never"; // Default is always
48
49 const sourceCode = context.sourceCode;
50
51 return {
52 NewExpression(node) {
53 if (node.arguments.length !== 0) {
54 return; // if there are arguments, there have to be parens
55 }
56
57 const lastToken = sourceCode.getLastToken(node);
58 const hasLastParen = lastToken && astUtils.isClosingParenToken(lastToken);
59
60 // `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
61 const hasParens = hasLastParen &&
62 astUtils.isOpeningParenToken(sourceCode.getTokenBefore(lastToken)) &&
63 node.callee.range[1] < node.range[1];
64
65 if (always) {
66 if (!hasParens) {
67 context.report({
68 node,
69 messageId: "missing",
70 fix: fixer => fixer.insertTextAfter(node, "()")
71 });
72 }
73 } else {
74 if (hasParens) {
75 context.report({
76 node,
77 messageId: "unnecessary",
78 fix: fixer => [
79 fixer.remove(sourceCode.getTokenBefore(lastToken)),
80 fixer.remove(lastToken),
81 fixer.insertTextBefore(node, "("),
82 fixer.insertTextAfter(node, ")")
83 ]
84 });
85 }
86 }
87 }
88 };
89 }
90 };