UNPKG

2.03 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 docs: {
15 description: "require generator functions to contain `yield`",
16 category: "ECMAScript 6",
17 recommended: true,
18 url: "https://eslint.org/docs/rules/require-yield"
19 },
20
21 schema: []
22 },
23
24 create(context) {
25 const stack = [];
26
27 /**
28 * If the node is a generator function, start counting `yield` keywords.
29 * @param {Node} node - A function node to check.
30 * @returns {void}
31 */
32 function beginChecking(node) {
33 if (node.generator) {
34 stack.push(0);
35 }
36 }
37
38 /**
39 * If the node is a generator function, end counting `yield` keywords, then
40 * reports result.
41 * @param {Node} node - A function node to check.
42 * @returns {void}
43 */
44 function endChecking(node) {
45 if (!node.generator) {
46 return;
47 }
48
49 const countYield = stack.pop();
50
51 if (countYield === 0 && node.body.body.length > 0) {
52 context.report({ node, message: "This generator function does not have 'yield'." });
53 }
54 }
55
56 return {
57 FunctionDeclaration: beginChecking,
58 "FunctionDeclaration:exit": endChecking,
59 FunctionExpression: beginChecking,
60 "FunctionExpression:exit": endChecking,
61
62 // Increases the count of `yield` keyword.
63 YieldExpression() {
64
65 /* istanbul ignore else */
66 if (stack.length > 0) {
67 stack[stack.length - 1] += 1;
68 }
69 }
70 };
71 }
72};