]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/new-parens.js
import 8.3.0 source
[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 module.exports = {
23 meta: {
24 type: "layout",
25
26 docs: {
27 description: "enforce or disallow parentheses when invoking a constructor with no arguments",
28 recommended: false,
29 url: "https://eslint.org/docs/rules/new-parens"
30 },
31
32 fixable: "code",
33 schema: {
34 anyOf: [
35 {
36 type: "array",
37 items: [
38 {
39 enum: ["always", "never"]
40 }
41 ],
42 minItems: 0,
43 maxItems: 1
44 }
45 ]
46 },
47 messages: {
48 missing: "Missing '()' invoking a constructor.",
49 unnecessary: "Unnecessary '()' invoking a constructor with no arguments."
50 }
51 },
52
53 create(context) {
54 const options = context.options;
55 const always = options[0] !== "never"; // Default is always
56
57 const sourceCode = context.getSourceCode();
58
59 return {
60 NewExpression(node) {
61 if (node.arguments.length !== 0) {
62 return; // if there are arguments, there have to be parens
63 }
64
65 const lastToken = sourceCode.getLastToken(node);
66 const hasLastParen = lastToken && astUtils.isClosingParenToken(lastToken);
67
68 // `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
69 const hasParens = hasLastParen &&
70 astUtils.isOpeningParenToken(sourceCode.getTokenBefore(lastToken)) &&
71 node.callee.range[1] < node.range[1];
72
73 if (always) {
74 if (!hasParens) {
75 context.report({
76 node,
77 messageId: "missing",
78 fix: fixer => fixer.insertTextAfter(node, "()")
79 });
80 }
81 } else {
82 if (hasParens) {
83 context.report({
84 node,
85 messageId: "unnecessary",
86 fix: fixer => [
87 fixer.remove(sourceCode.getTokenBefore(lastToken)),
88 fixer.remove(lastToken),
89 fixer.insertTextBefore(node, "("),
90 fixer.insertTextAfter(node, ")")
91 ]
92 });
93 }
94 }
95 }
96 };
97 }
98 };