summaryrefslogtreecommitdiff
path: root/tools/eslint/lib/rules/no-duplicate-case.js
blob: 89de7174fcb8c016535a6c86c522a0e618e5c730 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
 * @fileoverview Rule to disallow a duplicate case label.
 * @author Dieter Oberkofler
 * @copyright 2015 Dieter Oberkofler. All rights reserved.
 */

"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = function(context) {

    /**
     * Get a hash value for the node
     * @param {ASTNode} node The node.
     * @returns {string} A hash value for the node.
     * @private
     */
    function getHash(node) {
        if (node.type === "Literal") {
            return node.type + typeof node.value + node.value;
        } else if (node.type === "Identifier") {
            return node.type + typeof node.name + node.name;
        } else if (node.type === "MemberExpression") {
            return node.type + getHash(node.object) + getHash(node.property);
        }
    }

    var switchStatement = [];

    return {

        "SwitchStatement": function(/*node*/) {
            switchStatement.push({});
        },

        "SwitchStatement:exit": function(/*node*/) {
            switchStatement.pop();
        },

        "SwitchCase": function(node) {
            var currentSwitch = switchStatement[switchStatement.length - 1],
                hashValue;

            if (node.test) {
                hashValue = getHash(node.test);
                if (typeof hashValue !== "undefined" && currentSwitch.hasOwnProperty(hashValue)) {
                    context.report(node, "Duplicate case label.");
                } else {
                    currentSwitch[hashValue] = true;
                }
            }
        }

    };

};