UNPKG

3.53 kBJavaScriptView Raw
1"use strict";
2var _a;
3Object.defineProperty(exports, "__esModule", { value: true });
4const utils_1 = require("@typescript-eslint/utils");
5const getESLintCoreRule_1 = require("../util/getESLintCoreRule");
6const util_1 = require("../util");
7const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('no-invalid-this');
8exports.default = (0, util_1.createRule)({
9 name: 'no-invalid-this',
10 meta: {
11 type: 'suggestion',
12 docs: {
13 description: 'Disallow `this` keywords outside of classes or class-like objects',
14 recommended: false,
15 extendsBaseRule: true,
16 },
17 // TODO: this rule has only had messages since v7.0 - remove this when we remove support for v6
18 messages: (_a = baseRule.meta.messages) !== null && _a !== void 0 ? _a : {
19 unexpectedThis: "Unexpected 'this'.",
20 },
21 hasSuggestions: baseRule.meta.hasSuggestions,
22 schema: baseRule.meta.schema,
23 },
24 defaultOptions: [{ capIsConstructor: true }],
25 create(context) {
26 const rules = baseRule.create(context);
27 /**
28 * Since function definitions can be nested we use a stack storing if "this" is valid in the current context.
29 *
30 * Example:
31 *
32 * function a(this: number) { // valid "this"
33 * function b() {
34 * console.log(this); // invalid "this"
35 * }
36 * }
37 *
38 * When parsing the function declaration of "a" the stack will be: [true]
39 * When parsing the function declaration of "b" the stack will be: [true, false]
40 */
41 const thisIsValidStack = [];
42 return Object.assign(Object.assign({}, rules), { PropertyDefinition() {
43 thisIsValidStack.push(true);
44 },
45 'PropertyDefinition:exit'() {
46 thisIsValidStack.pop();
47 },
48 FunctionDeclaration(node) {
49 var _a;
50 thisIsValidStack.push(node.params.some(param => param.type === utils_1.AST_NODE_TYPES.Identifier && param.name === 'this'));
51 // baseRule's work
52 (_a = rules.FunctionDeclaration) === null || _a === void 0 ? void 0 : _a.call(rules, node);
53 },
54 'FunctionDeclaration:exit'(node) {
55 var _a;
56 thisIsValidStack.pop();
57 // baseRule's work
58 (_a = rules['FunctionDeclaration:exit']) === null || _a === void 0 ? void 0 : _a.call(rules, node);
59 },
60 FunctionExpression(node) {
61 var _a;
62 thisIsValidStack.push(node.params.some(param => param.type === utils_1.AST_NODE_TYPES.Identifier && param.name === 'this'));
63 // baseRule's work
64 (_a = rules.FunctionExpression) === null || _a === void 0 ? void 0 : _a.call(rules, node);
65 },
66 'FunctionExpression:exit'(node) {
67 var _a;
68 thisIsValidStack.pop();
69 // baseRule's work
70 (_a = rules['FunctionExpression:exit']) === null || _a === void 0 ? void 0 : _a.call(rules, node);
71 },
72 ThisExpression(node) {
73 const thisIsValidHere = thisIsValidStack[thisIsValidStack.length - 1];
74 if (thisIsValidHere) {
75 return;
76 }
77 // baseRule's work
78 rules.ThisExpression(node);
79 } });
80 },
81});
82//# sourceMappingURL=no-invalid-this.js.map
\No newline at end of file