/
no-this-in-static.js
90 lines (82 loc) · 2.65 KB
/
no-this-in-static.js
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
/**
* @author Toru Nagashima
* @copyright 2016 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "disallow `this`/`super` in static methods",
category: "Best Practices",
url: "https://github.com/mysticatea/eslint-plugin/blob/v13.0.0/docs/rules/no-this-in-static.md",
},
fixable: null,
schema: [],
type: "suggestion",
},
create(context) {
const sourceCode = context.getSourceCode()
let funcInfo = null
/**
* Checks whether the given function node is a static method or not.
*
* @param {ASTNode} node - The function node to check.
* @returns {boolean} `true` if the node is a static method.
*/
function isStaticMethod(node) {
return (
node.type === "FunctionExpression" &&
node.parent.type === "MethodDefinition" &&
node.parent.static === true
)
}
/**
* Updates the stack of function information.
*
* @param {ASTNode} node - The function node to make information.
* @returns {void}
*/
function enterFunction(node) {
funcInfo = {
upper: funcInfo,
static: isStaticMethod(node),
}
}
/**
* Updates the stack of function information.
*
* @returns {void}
*/
function exitFunction() {
funcInfo = funcInfo.upper
}
/**
* Reports the `this`/`super` node if this is inside of a static method.
*
* @param {ASTNode} node - The node to report.
* @returns {void}
*/
function reportIfStatic(node) {
if (funcInfo != null && funcInfo.static) {
context.report({
node,
loc: node.loc,
message: "Unexpected '{{type}}'.",
data: { type: sourceCode.getText(node) },
})
}
}
return {
FunctionDeclaration: enterFunction,
FunctionExpression: enterFunction,
"FunctionDeclaration:exit": exitFunction,
"FunctionExpression:exit": exitFunction,
ThisExpression: reportIfStatic,
Super: reportIfStatic,
}
},
}