require-yield.js 2.1 KB

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