summaryrefslogtreecommitdiff
path: root/tools/eslint/lib/rules/func-names.js
blob: 44b989b2c47116a1435d6ec5de92f7e2f24310f3 (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
60
61
62
63
64
/**
 * @fileoverview Rule to warn when a function expression does not have a name.
 * @author Kyle T. Nunery
 */

"use strict";

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

module.exports = {
    meta: {
        docs: {
            description: "require or disallow named `function` expressions",
            category: "Stylistic Issues",
            recommended: false
        },

        schema: [
            {
                enum: ["always", "never"]
            }
        ]
    },

    create: function(context) {
        var never = context.options[0] === "never";

        /**
         * Determines whether the current FunctionExpression node is a get, set, or
         * shorthand method in an object literal or a class.
         * @returns {boolean} True if the node is a get, set, or shorthand method.
         */
        function isObjectOrClassMethod() {
            var parent = context.getAncestors().pop();

            return (parent.type === "MethodDefinition" || (
                parent.type === "Property" && (
                    parent.method ||
                    parent.kind === "get" ||
                    parent.kind === "set"
                )
            ));
        }

        return {
            FunctionExpression: function(node) {

                var name = node.id && node.id.name;

                if (never) {
                    if (name) {
                        context.report(node, "Unexpected function expression name.");
                    }
                } else {
                    if (!name && !isObjectOrClassMethod()) {
                        context.report(node, "Missing function expression name.");
                    }
                }
            }
        };
    }
};