]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/require-await.js
import 8.3.0 source
[pve-eslint.git] / eslint / lib / rules / require-await.js
1 /**
2 * @fileoverview Rule to disallow async functions which have no `await` expression.
3 * @author Toru Nagashima
4 */
5
6 "use strict";
7
8 //------------------------------------------------------------------------------
9 // Requirements
10 //------------------------------------------------------------------------------
11
12 const astUtils = require("./utils/ast-utils");
13
14 //------------------------------------------------------------------------------
15 // Helpers
16 //------------------------------------------------------------------------------
17
18 /**
19 * Capitalize the 1st letter of the given text.
20 * @param {string} text The text to capitalize.
21 * @returns {string} The text that the 1st letter was capitalized.
22 */
23 function capitalizeFirstLetter(text) {
24 return text[0].toUpperCase() + text.slice(1);
25 }
26
27 //------------------------------------------------------------------------------
28 // Rule Definition
29 //------------------------------------------------------------------------------
30
31 module.exports = {
32 meta: {
33 type: "suggestion",
34
35 docs: {
36 description: "disallow async functions which have no `await` expression",
37 recommended: false,
38 url: "https://eslint.org/docs/rules/require-await"
39 },
40
41 schema: [],
42
43 messages: {
44 missingAwait: "{{name}} has no 'await' expression."
45 }
46 },
47
48 create(context) {
49 const sourceCode = context.getSourceCode();
50 let scopeInfo = null;
51
52 /**
53 * Push the scope info object to the stack.
54 * @returns {void}
55 */
56 function enterFunction() {
57 scopeInfo = {
58 upper: scopeInfo,
59 hasAwait: false
60 };
61 }
62
63 /**
64 * Pop the top scope info object from the stack.
65 * Also, it reports the function if needed.
66 * @param {ASTNode} node The node to report.
67 * @returns {void}
68 */
69 function exitFunction(node) {
70 if (!node.generator && node.async && !scopeInfo.hasAwait && !astUtils.isEmptyFunction(node)) {
71 context.report({
72 node,
73 loc: astUtils.getFunctionHeadLoc(node, sourceCode),
74 messageId: "missingAwait",
75 data: {
76 name: capitalizeFirstLetter(
77 astUtils.getFunctionNameWithKind(node)
78 )
79 }
80 });
81 }
82
83 scopeInfo = scopeInfo.upper;
84 }
85
86 return {
87 FunctionDeclaration: enterFunction,
88 FunctionExpression: enterFunction,
89 ArrowFunctionExpression: enterFunction,
90 "FunctionDeclaration:exit": exitFunction,
91 "FunctionExpression:exit": exitFunction,
92 "ArrowFunctionExpression:exit": exitFunction,
93
94 AwaitExpression() {
95 if (!scopeInfo) {
96 return;
97 }
98
99 scopeInfo.hasAwait = true;
100 },
101 ForOfStatement(node) {
102 if (!scopeInfo) {
103 return;
104 }
105
106 if (node.await) {
107 scopeInfo.hasAwait = true;
108 }
109 }
110 };
111 }
112 };