2 * @fileoverview A rule to disallow duplicate name in class members.
3 * @author Toru Nagashima
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
17 description: "disallow duplicate class members",
18 category: "ECMAScript 6",
20 url: "https://eslint.org/docs/rules/no-dupe-class-members"
26 unexpected: "Duplicate name '{{name}}'."
34 * Gets state of a given member name.
35 * @param {string} name A name of a member.
36 * @param {boolean} isStatic A flag which specifies that is a static member.
37 * @returns {Object} A state of a given member name.
38 * - retv.init {boolean} A flag which shows the name is declared as normal member.
39 * - retv.get {boolean} A flag which shows the name is declared as getter.
40 * - retv.set {boolean} A flag which shows the name is declared as setter.
42 function getState(name, isStatic) {
43 const stateMap = stack[stack.length - 1];
44 const key = `$${name}`; // to avoid "__proto__".
48 nonStatic: { init: false, get: false, set: false },
49 static: { init: false, get: false, set: false }
53 return stateMap[key][isStatic ? "static" : "nonStatic"];
57 * Gets the name text of a given node.
58 * @param {ASTNode} node A node to get the name.
59 * @returns {string} The name text of the node.
61 function getName(node) {
63 case "Identifier": return node.name;
64 case "Literal": return String(node.value);
66 /* istanbul ignore next: syntax error */
73 // Initializes the stack of state of member declarations.
78 // Initializes state of member declarations for the class.
80 stack.push(Object.create(null));
83 // Disposes the state for the class.
88 // Reports the node if its name has been declared already.
89 MethodDefinition(node) {
94 const name = getName(node.key);
95 const state = getState(name, node.static);
96 let isDuplicate = false;
98 if (node.kind === "get") {
99 isDuplicate = (state.init || state.get);
101 } else if (node.kind === "set") {
102 isDuplicate = (state.init || state.set);
105 isDuplicate = (state.init || state.get || state.set);
110 context.report({ node, messageId: "unexpected", data: { name } });