-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
no-unused-expressions.ts
67 lines (61 loc) · 2 KB
/
no-unused-expressions.ts
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
import {
AST_NODE_TYPES,
TSESTree,
} from '@typescript-eslint/experimental-utils';
import { getESLintCoreRule } from '../util/getESLintCoreRule';
import * as util from '../util';
const baseRule = getESLintCoreRule('no-unused-expressions');
type MessageIds = util.InferMessageIdsTypeFromRule<typeof baseRule>;
type Options = util.InferOptionsTypeFromRule<typeof baseRule>;
export default util.createRule<Options, MessageIds>({
name: 'no-unused-expressions',
meta: {
type: 'suggestion',
docs: {
description: 'Disallow unused expressions',
recommended: false,
extendsBaseRule: true,
},
hasSuggestions: baseRule.meta.hasSuggestions,
schema: baseRule.meta.schema,
// TODO: this rule has only had messages since v7.0 - remove this when we remove support for v6
messages: baseRule.meta.messages ?? {
unusedExpression:
'Expected an assignment or function call and instead saw an expression.',
},
},
defaultOptions: [
{
allowShortCircuit: false,
allowTernary: false,
allowTaggedTemplates: false,
},
],
create(context, [{ allowShortCircuit = false, allowTernary = false }]) {
const rules = baseRule.create(context);
function isValidExpression(node: TSESTree.Node): boolean {
if (allowShortCircuit && node.type === AST_NODE_TYPES.LogicalExpression) {
return isValidExpression(node.right);
}
if (allowTernary && node.type === AST_NODE_TYPES.ConditionalExpression) {
return (
isValidExpression(node.alternate) &&
isValidExpression(node.consequent)
);
}
return (
(node.type === AST_NODE_TYPES.ChainExpression &&
node.expression.type === AST_NODE_TYPES.CallExpression) ||
node.type === AST_NODE_TYPES.ImportExpression
);
}
return {
ExpressionStatement(node): void {
if (node.directive || isValidExpression(node.expression)) {
return;
}
rules.ExpressionStatement(node);
},
};
},
});