no-confusing-void-expression.js
13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const experimental_utils_1 = require("@typescript-eslint/experimental-utils");
const tsutils = __importStar(require("tsutils"));
const ts = __importStar(require("typescript"));
const util = __importStar(require("../util"));
exports.default = util.createRule({
name: 'no-confusing-void-expression',
meta: {
docs: {
description: 'Requires expressions of type void to appear in statement position',
category: 'Best Practices',
recommended: false,
requiresTypeChecking: true,
},
messages: {
invalidVoidExpr: 'Placing a void expression inside another expression is forbidden. ' +
'Move it to its own statement instead.',
invalidVoidExprWrapVoid: 'Void expressions used inside another expression ' +
'must be moved to its own statement ' +
'or marked explicitly with the `void` operator.',
invalidVoidExprArrow: 'Returning a void expression from an arrow function shorthand is forbidden. ' +
'Please add braces to the arrow function.',
invalidVoidExprArrowWrapVoid: 'Void expressions returned from an arrow function shorthand ' +
'must be marked explicitly with the `void` operator.',
invalidVoidExprReturn: 'Returning a void expression from a function is forbidden. ' +
'Please move it before the `return` statement.',
invalidVoidExprReturnLast: 'Returning a void expression from a function is forbidden. ' +
'Please remove the `return` statement.',
invalidVoidExprReturnWrapVoid: 'Void expressions returned from a function ' +
'must be marked explicitly with the `void` operator.',
voidExprWrapVoid: 'Mark with an explicit `void` operator',
},
schema: [
{
type: 'object',
properties: {
ignoreArrowShorthand: { type: 'boolean' },
ignoreVoidOperator: { type: 'boolean' },
},
additionalProperties: false,
},
],
type: 'problem',
fixable: 'code',
},
defaultOptions: [{}],
create(context, [options]) {
return {
'AwaitExpression, CallExpression, TaggedTemplateExpression'(node) {
const parserServices = util.getParserServices(context);
const checker = parserServices.program.getTypeChecker();
const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node);
const type = util.getConstrainedTypeAtLocation(checker, tsNode);
if (!tsutils.isTypeFlagSet(type, ts.TypeFlags.VoidLike)) {
// not a void expression
return;
}
const invalidAncestor = findInvalidAncestor(node);
if (invalidAncestor == null) {
// void expression is in valid position
return;
}
const sourceCode = context.getSourceCode();
const wrapVoidFix = (fixer) => {
const nodeText = sourceCode.getText(node);
const newNodeText = `void ${nodeText}`;
return fixer.replaceText(node, newNodeText);
};
if (invalidAncestor.type === experimental_utils_1.AST_NODE_TYPES.ArrowFunctionExpression) {
// handle arrow function shorthand
if (options.ignoreVoidOperator) {
// handle wrapping with `void`
return context.report({
node,
messageId: 'invalidVoidExprArrowWrapVoid',
fix: wrapVoidFix,
});
}
// handle wrapping with braces
const arrowFunction = invalidAncestor;
return context.report({
node,
messageId: 'invalidVoidExprArrow',
fix(fixer) {
const arrowBody = arrowFunction.body;
const arrowBodyText = sourceCode.getText(arrowBody);
const newArrowBodyText = `{ ${arrowBodyText}; }`;
if (util.isParenthesized(arrowBody, sourceCode)) {
const bodyOpeningParen = sourceCode.getTokenBefore(arrowBody, util.isOpeningParenToken);
const bodyClosingParen = sourceCode.getTokenAfter(arrowBody, util.isClosingParenToken);
return fixer.replaceTextRange([bodyOpeningParen.range[0], bodyClosingParen.range[1]], newArrowBodyText);
}
return fixer.replaceText(arrowBody, newArrowBodyText);
},
});
}
if (invalidAncestor.type === experimental_utils_1.AST_NODE_TYPES.ReturnStatement) {
// handle return statement
if (options.ignoreVoidOperator) {
// handle wrapping with `void`
return context.report({
node,
messageId: 'invalidVoidExprReturnWrapVoid',
fix: wrapVoidFix,
});
}
const returnStmt = invalidAncestor;
if (isFinalReturn(returnStmt)) {
// remove the `return` keyword
return context.report({
node,
messageId: 'invalidVoidExprReturnLast',
fix(fixer) {
const returnValue = returnStmt.argument;
const returnValueText = sourceCode.getText(returnValue);
let newReturnStmtText = `${returnValueText};`;
if (isPreventingASI(returnValue, sourceCode)) {
// put a semicolon at the beginning of the line
newReturnStmtText = `;${newReturnStmtText}`;
}
return fixer.replaceText(returnStmt, newReturnStmtText);
},
});
}
// move before the `return` keyword
return context.report({
node,
messageId: 'invalidVoidExprReturn',
fix(fixer) {
var _a;
const returnValue = returnStmt.argument;
const returnValueText = sourceCode.getText(returnValue);
let newReturnStmtText = `${returnValueText}; return;`;
if (isPreventingASI(returnValue, sourceCode)) {
// put a semicolon at the beginning of the line
newReturnStmtText = `;${newReturnStmtText}`;
}
if (((_a = returnStmt.parent) === null || _a === void 0 ? void 0 : _a.type) !== experimental_utils_1.AST_NODE_TYPES.BlockStatement) {
// e.g. `if (cond) return console.error();`
// add braces if not inside a block
newReturnStmtText = `{ ${newReturnStmtText} }`;
}
return fixer.replaceText(returnStmt, newReturnStmtText);
},
});
}
// handle generic case
if (options.ignoreVoidOperator) {
// this would be reported by this rule btw. such irony
return context.report({
node,
messageId: 'invalidVoidExprWrapVoid',
suggest: [{ messageId: 'voidExprWrapVoid', fix: wrapVoidFix }],
});
}
context.report({
node,
messageId: 'invalidVoidExpr',
});
},
};
/**
* Inspects the void expression's ancestors and finds closest invalid one.
* By default anything other than an ExpressionStatement is invalid.
* Parent expressions which can be used for their short-circuiting behavior
* are ignored and their parents are checked instead.
* @param node The void expression node to check.
* @returns Invalid ancestor node if it was found. `null` otherwise.
*/
function findInvalidAncestor(node) {
const parent = util.nullThrows(node.parent, util.NullThrowsReasons.MissingParent);
if (parent.type === experimental_utils_1.AST_NODE_TYPES.ExpressionStatement) {
// e.g. `{ console.log("foo"); }`
// this is always valid
return null;
}
if (parent.type === experimental_utils_1.AST_NODE_TYPES.LogicalExpression) {
if (parent.right === node) {
// e.g. `x && console.log(x)`
// this is valid only if the next ancestor is valid
return findInvalidAncestor(parent);
}
}
if (parent.type === experimental_utils_1.AST_NODE_TYPES.ConditionalExpression) {
if (parent.consequent === node || parent.alternate === node) {
// e.g. `cond ? console.log(true) : console.log(false)`
// this is valid only if the next ancestor is valid
return findInvalidAncestor(parent);
}
}
if (parent.type === experimental_utils_1.AST_NODE_TYPES.ArrowFunctionExpression) {
// e.g. `() => console.log("foo")`
// this is valid with an appropriate option
if (options.ignoreArrowShorthand) {
return null;
}
}
if (parent.type === experimental_utils_1.AST_NODE_TYPES.UnaryExpression) {
if (parent.operator === 'void') {
// e.g. `void console.log("foo")`
// this is valid with an appropriate option
if (options.ignoreVoidOperator) {
return null;
}
}
}
// any other parent is invalid
return parent;
}
/** Checks whether the return statement is the last statement in a function body. */
function isFinalReturn(node) {
// the parent must be a block
const block = util.nullThrows(node.parent, util.NullThrowsReasons.MissingParent);
if (block.type !== experimental_utils_1.AST_NODE_TYPES.BlockStatement) {
// e.g. `if (cond) return;` (not in a block)
return false;
}
// the block's parent must be a function
const blockParent = util.nullThrows(block.parent, util.NullThrowsReasons.MissingParent);
if (![
experimental_utils_1.AST_NODE_TYPES.FunctionDeclaration,
experimental_utils_1.AST_NODE_TYPES.FunctionExpression,
experimental_utils_1.AST_NODE_TYPES.ArrowFunctionExpression,
].includes(blockParent.type)) {
// e.g. `if (cond) { return; }`
// not in a top-level function block
return false;
}
// must be the last child of the block
if (block.body.indexOf(node) < block.body.length - 1) {
// not the last statement in the block
return false;
}
return true;
}
/**
* Checks whether the given node, if placed on its own line,
* would prevent automatic semicolon insertion on the line before.
*
* This happens if the line begins with `(`, `[` or `` ` ``
*/
function isPreventingASI(node, sourceCode) {
const startToken = util.nullThrows(sourceCode.getFirstToken(node), util.NullThrowsReasons.MissingToken('first token', node.type));
return ['(', '[', '`'].includes(startToken.value);
}
},
});
//# sourceMappingURL=no-confusing-void-expression.js.map