UNPKG

2.06 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag the generator functions that does not have yield.
3 * @author Toru Nagashima
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Rule Definition
10//------------------------------------------------------------------------------
11
12module.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
26 create(context) {
27 const stack = [];
28
29 /**
30 * If the node is a generator function, start counting `yield` keywords.
31 * @param {Node} node - A function node to check.
32 * @returns {void}
33 */
34 function beginChecking(node) {
35 if (node.generator) {
36 stack.push(0);
37 }
38 }
39
40 /**
41 * If the node is a generator function, end counting `yield` keywords, then
42 * reports result.
43 * @param {Node} node - A function node to check.
44 * @returns {void}
45 */
46 function endChecking(node) {
47 if (!node.generator) {
48 return;
49 }
50
51 const countYield = stack.pop();
52
53 if (countYield === 0 && node.body.body.length > 0) {
54 context.report({ node, message: "This generator function does not have 'yield'." });
55 }
56 }
57
58 return {
59 FunctionDeclaration: beginChecking,
60 "FunctionDeclaration:exit": endChecking,
61 FunctionExpression: beginChecking,
62 "FunctionExpression:exit": endChecking,
63
64 // Increases the count of `yield` keyword.
65 YieldExpression() {
66
67 /* istanbul ignore else */
68 if (stack.length > 0) {
69 stack[stack.length - 1] += 1;
70 }
71 }
72 };
73 }
74};