require-yield.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. /** @type {import('../shared/types').Rule} */
  10. module.exports = {
  11. meta: {
  12. type: "suggestion",
  13. docs: {
  14. description: "Require generator functions to contain `yield`",
  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. if (stack.length > 0) {
  58. stack[stack.length - 1] += 1;
  59. }
  60. }
  61. };
  62. }
  63. };