no-use-before-define.js
10.3 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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
"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 util = __importStar(require("../util"));
const SENTINEL_TYPE = /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/;
/**
* Parses a given value as options.
*/
function parseOptions(options) {
let functions = true;
let classes = true;
let enums = true;
let variables = true;
let typedefs = true;
let ignoreTypeReferences = true;
if (typeof options === 'string') {
functions = options !== 'nofunc';
}
else if (typeof options === 'object' && options !== null) {
functions = options.functions !== false;
classes = options.classes !== false;
enums = options.enums !== false;
variables = options.variables !== false;
typedefs = options.typedefs !== false;
ignoreTypeReferences = options.ignoreTypeReferences !== false;
}
return {
functions,
classes,
enums,
variables,
typedefs,
ignoreTypeReferences,
};
}
/**
* Checks whether or not a given variable is a function declaration.
*/
function isFunction(variable) {
return variable.defs[0].type === 'FunctionName';
}
/**
* Checks whether or not a given variable is a type declaration.
*/
function isTypedef(variable) {
return variable.defs[0].type === 'Type';
}
/**
* Checks whether or not a given variable is a enum declaration.
*/
function isOuterEnum(variable, reference) {
return (variable.defs[0].type == 'TSEnumName' &&
variable.scope.variableScope !== reference.from.variableScope);
}
/**
* Checks whether or not a given variable is a class declaration in an upper function scope.
*/
function isOuterClass(variable, reference) {
return (variable.defs[0].type === 'ClassName' &&
variable.scope.variableScope !== reference.from.variableScope);
}
/**
* Checks whether or not a given variable is a variable declaration in an upper function scope.
*/
function isOuterVariable(variable, reference) {
return (variable.defs[0].type === 'Variable' &&
variable.scope.variableScope !== reference.from.variableScope);
}
/**
* Recursively checks whether or not a given reference has a type query declaration among it's parents
*/
function referenceContainsTypeQuery(node) {
switch (node.type) {
case experimental_utils_1.AST_NODE_TYPES.TSTypeQuery:
return true;
case experimental_utils_1.AST_NODE_TYPES.TSQualifiedName:
case experimental_utils_1.AST_NODE_TYPES.Identifier:
if (!node.parent) {
return false;
}
return referenceContainsTypeQuery(node.parent);
default:
// if we find a different node, there's no chance that we're in a TSTypeQuery
return false;
}
}
/**
* Checks whether or not a given reference is a type reference.
*/
function isTypeReference(reference) {
return (reference.isTypeReference ||
referenceContainsTypeQuery(reference.identifier));
}
/**
* Checks whether or not a given location is inside of the range of a given node.
*/
function isInRange(node, location) {
return !!node && node.range[0] <= location && location <= node.range[1];
}
/**
* Decorators are transpiled such that the decorator is placed after the class declaration
* So it is considered safe
*/
function isClassRefInClassDecorator(variable, reference) {
if (variable.defs[0].type !== 'ClassName') {
return false;
}
if (!variable.defs[0].node.decorators ||
variable.defs[0].node.decorators.length === 0) {
return false;
}
for (const deco of variable.defs[0].node.decorators) {
if (reference.identifier.range[0] >= deco.range[0] &&
reference.identifier.range[1] <= deco.range[1]) {
return true;
}
}
return false;
}
/**
* Checks whether or not a given reference is inside of the initializers of a given variable.
*
* @returns `true` in the following cases:
* - var a = a
* - var [a = a] = list
* - var {a = a} = obj
* - for (var a in a) {}
* - for (var a of a) {}
*/
function isInInitializer(variable, reference) {
var _a;
if (variable.scope !== reference.from) {
return false;
}
let node = variable.identifiers[0].parent;
const location = reference.identifier.range[1];
while (node) {
if (node.type === experimental_utils_1.AST_NODE_TYPES.VariableDeclarator) {
if (isInRange(node.init, location)) {
return true;
}
if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) &&
(node.parent.parent.type === experimental_utils_1.AST_NODE_TYPES.ForInStatement ||
node.parent.parent.type === experimental_utils_1.AST_NODE_TYPES.ForOfStatement) &&
isInRange(node.parent.parent.right, location)) {
return true;
}
break;
}
else if (node.type === experimental_utils_1.AST_NODE_TYPES.AssignmentPattern) {
if (isInRange(node.right, location)) {
return true;
}
}
else if (SENTINEL_TYPE.test(node.type)) {
break;
}
node = node.parent;
}
return false;
}
exports.default = util.createRule({
name: 'no-use-before-define',
meta: {
type: 'problem',
docs: {
description: 'Disallow the use of variables before they are defined',
category: 'Variables',
recommended: false,
extendsBaseRule: true,
},
messages: {
noUseBeforeDefine: "'{{name}}' was used before it was defined.",
},
schema: [
{
oneOf: [
{
enum: ['nofunc'],
},
{
type: 'object',
properties: {
functions: { type: 'boolean' },
classes: { type: 'boolean' },
enums: { type: 'boolean' },
variables: { type: 'boolean' },
typedefs: { type: 'boolean' },
ignoreTypeReferences: { type: 'boolean' },
},
additionalProperties: false,
},
],
},
],
},
defaultOptions: [
{
functions: true,
classes: true,
enums: true,
variables: true,
typedefs: true,
ignoreTypeReferences: true,
},
],
create(context, optionsWithDefault) {
const options = parseOptions(optionsWithDefault[0]);
/**
* Determines whether a given use-before-define case should be reported according to the options.
* @param variable The variable that gets used before being defined
* @param reference The reference to the variable
*/
function isForbidden(variable, reference) {
if (options.ignoreTypeReferences && isTypeReference(reference)) {
return false;
}
if (isFunction(variable)) {
return options.functions;
}
if (isOuterClass(variable, reference)) {
return options.classes;
}
if (isOuterVariable(variable, reference)) {
return options.variables;
}
if (isOuterEnum(variable, reference)) {
return options.enums;
}
if (isTypedef(variable)) {
return options.typedefs;
}
return true;
}
/**
* Finds and validates all variables in a given scope.
*/
function findVariablesInScope(scope) {
scope.references.forEach(reference => {
const variable = reference.resolved;
// Skips when the reference is:
// - initializations.
// - referring to an undefined variable.
// - referring to a global environment variable (there're no identifiers).
// - located preceded by the variable (except in initializers).
// - allowed by options.
if (reference.init ||
!variable ||
variable.identifiers.length === 0 ||
(variable.identifiers[0].range[1] <= reference.identifier.range[1] &&
!isInInitializer(variable, reference)) ||
!isForbidden(variable, reference) ||
isClassRefInClassDecorator(variable, reference) ||
reference.from.type === experimental_utils_1.TSESLint.Scope.ScopeType.functionType) {
return;
}
// Reports.
context.report({
node: reference.identifier,
messageId: 'noUseBeforeDefine',
data: {
name: reference.identifier.name,
},
});
});
scope.childScopes.forEach(findVariablesInScope);
}
return {
Program() {
findVariablesInScope(context.getScope());
},
};
},
});
//# sourceMappingURL=no-use-before-define.js.map