1 | /**
|
2 | * @fileoverview Rule to flag the generator functions that does not have yield.
|
3 | * @author Toru Nagashima
|
4 | */
|
5 |
|
6 | ;
|
7 |
|
8 | //------------------------------------------------------------------------------
|
9 | // Rule Definition
|
10 | //------------------------------------------------------------------------------
|
11 |
|
12 | module.exports = {
|
13 | meta: {
|
14 | type: "suggestion",
|
15 |
|
16 | docs: {
|
17 | description: "require generator functions to contain `yield`",
|
18 | category: "ECMAScript 6",
|
19 | recommended: true,
|
20 | url: "https://eslint.org/docs/rules/require-yield"
|
21 | },
|
22 |
|
23 | schema: [],
|
24 |
|
25 | messages: {
|
26 | missingYield: "This generator function does not have 'yield'."
|
27 | }
|
28 | },
|
29 |
|
30 | create(context) {
|
31 | const stack = [];
|
32 |
|
33 | /**
|
34 | * If the node is a generator function, start counting `yield` keywords.
|
35 | * @param {Node} node A function node to check.
|
36 | * @returns {void}
|
37 | */
|
38 | function beginChecking(node) {
|
39 | if (node.generator) {
|
40 | stack.push(0);
|
41 | }
|
42 | }
|
43 |
|
44 | /**
|
45 | * If the node is a generator function, end counting `yield` keywords, then
|
46 | * reports result.
|
47 | * @param {Node} node A function node to check.
|
48 | * @returns {void}
|
49 | */
|
50 | function endChecking(node) {
|
51 | if (!node.generator) {
|
52 | return;
|
53 | }
|
54 |
|
55 | const countYield = stack.pop();
|
56 |
|
57 | if (countYield === 0 && node.body.body.length > 0) {
|
58 | context.report({ node, messageId: "missingYield" });
|
59 | }
|
60 | }
|
61 |
|
62 | return {
|
63 | FunctionDeclaration: beginChecking,
|
64 | "FunctionDeclaration:exit": endChecking,
|
65 | FunctionExpression: beginChecking,
|
66 | "FunctionExpression:exit": endChecking,
|
67 |
|
68 | // Increases the count of `yield` keyword.
|
69 | YieldExpression() {
|
70 |
|
71 | /* istanbul ignore else */
|
72 | if (stack.length > 0) {
|
73 | stack[stack.length - 1] += 1;
|
74 | }
|
75 | }
|
76 | };
|
77 | }
|
78 | };
|