This repository has been archived by the owner on Mar 25, 2021. It is now read-only.
/
variableNameRule.ts
265 lines (233 loc) · 9.64 KB
/
variableNameRule.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
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
/**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// tslint:disable object-literal-sort-keys
import * as tsutils from "tsutils";
import * as ts from "typescript";
import * as Lint from "../index";
import { isLowerCase, isUpperCase } from "../utils";
const BANNED_KEYWORDS = [
"any",
"Number",
"number",
"String",
"string",
"Boolean",
"boolean",
"Undefined",
"undefined",
];
const bannedKeywordsSet = new Set(BANNED_KEYWORDS);
const bannedKeywordsStr = BANNED_KEYWORDS.map(kw => `\`${kw}\``).join(", ");
const OPTION_CHECK_FORMAT = "check-format";
const OPTION_ALLOW_LEADING_UNDERSCORE = "allow-leading-underscore";
const OPTION_ALLOW_PASCAL_CASE = "allow-pascal-case";
const OPTION_ALLOW_SNAKE_CASE = "allow-snake-case";
const OPTION_ALLOW_TRAILING_UNDERSCORE = "allow-trailing-underscore";
const OPTION_REQUIRE_CONST_FOR_ALL_CAPS = "require-const-for-all-caps";
const OPTION_BAN_KEYWORDS = "ban-keywords";
export class Rule extends Lint.Rules.AbstractRule {
public static metadata: Lint.IRuleMetadata = {
ruleName: "variable-name",
description: "Checks variable names for various errors.",
optionsDescription: Lint.Utils.dedent`
Several arguments may be optionally provided:
* \`"${OPTION_CHECK_FORMAT}"\` enbables enforcement of a certain naming format. By default, the rule only allows only lowerCamelCased or UPPER_CASED variable names.
* These additional options make the check stricter:
* \`"${OPTION_REQUIRE_CONST_FOR_ALL_CAPS}"\`: enforces that all variables with UPPER_CASED names should be \`const\`.
* These additional options make the check more permissive:
* \`"${OPTION_ALLOW_LEADING_UNDERSCORE}"\` allows underscores at the beginning (only has an effect if "check-format" specified)
* \`"${OPTION_ALLOW_PASCAL_CASE}"\` allows PascalCase in addition to lowerCamelCase.
* \`"${OPTION_ALLOW_SNAKE_CASE}"\` allows snake_case in addition to lowerCamelCase.
* \`"${OPTION_ALLOW_TRAILING_UNDERSCORE}"\` allows underscores at the end. (only has an effect if "check-format" specified)
* \`"${OPTION_BAN_KEYWORDS}"\`: disallows the use of certain TypeScript keywords as variable or parameter names.
* These are: ${bannedKeywordsStr}`,
options: {
type: "array",
items: {
type: "string",
enum: [
OPTION_CHECK_FORMAT,
OPTION_ALLOW_LEADING_UNDERSCORE,
OPTION_ALLOW_PASCAL_CASE,
OPTION_ALLOW_SNAKE_CASE,
OPTION_ALLOW_TRAILING_UNDERSCORE,
OPTION_REQUIRE_CONST_FOR_ALL_CAPS,
OPTION_BAN_KEYWORDS,
],
},
minLength: 0,
maxLength: 6,
},
optionExamples: [
{
options: [
"ban-keywords",
"check-format",
"allow-leading-underscore",
"allow-pascal-case",
],
},
],
type: "style",
typescriptOnly: false,
};
public static KEYWORD_FAILURE = "variable name clashes with keyword/type";
public static FAILURE_STRING_CONST = "Only `const` variables may be UPPER_CASE.";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk, parseOptions(this.ruleArguments));
}
}
interface Options {
banKeywords: boolean;
checkFormat: boolean;
leadingUnderscore: boolean;
trailingUnderscore: boolean;
allCapsForConst: boolean;
allowPascalCase: boolean;
allowSnakeCase: boolean;
}
function parseOptions(ruleArguments: string[]): Options {
const banKeywords = hasOption(OPTION_BAN_KEYWORDS);
return {
banKeywords,
// check variable name formatting by default if no options are specified
checkFormat: !banKeywords || hasOption(OPTION_CHECK_FORMAT),
leadingUnderscore: hasOption(OPTION_ALLOW_LEADING_UNDERSCORE),
trailingUnderscore: hasOption(OPTION_ALLOW_TRAILING_UNDERSCORE),
allCapsForConst: hasOption(OPTION_REQUIRE_CONST_FOR_ALL_CAPS),
allowPascalCase: hasOption(OPTION_ALLOW_PASCAL_CASE),
allowSnakeCase: hasOption(OPTION_ALLOW_SNAKE_CASE),
};
function hasOption(name: string): boolean {
return ruleArguments.indexOf(name) !== -1;
}
}
function walk(ctx: Lint.WalkContext<Options>): void {
const { options, sourceFile } = ctx;
return ts.forEachChild(sourceFile, function cb(node: ts.Node): void {
switch (node.kind) {
case ts.SyntaxKind.BindingElement: {
const { initializer, name, propertyName } = node as ts.BindingElement;
if (name.kind === ts.SyntaxKind.Identifier) {
handleVariableNameKeyword(name);
// A destructuring pattern that does not rebind an expression is
// always an alias, e.g. `var {Foo} = ...;`. Only check if the name is
// rebound (`var {Foo: bar} = ...;`).
if (
node.parent.kind !== ts.SyntaxKind.ObjectBindingPattern ||
propertyName !== undefined
) {
handleVariableNameFormat(name, initializer);
}
}
break;
}
case ts.SyntaxKind.VariableStatement:
// skip 'declare' keywords
if (tsutils.hasModifier(node.modifiers, ts.SyntaxKind.DeclareKeyword)) {
return;
}
break;
case ts.SyntaxKind.Parameter:
case ts.SyntaxKind.PropertyDeclaration:
handleDeclaredVariable(node as ts.ParameterDeclaration | ts.PropertyDeclaration);
break;
case ts.SyntaxKind.VariableDeclaration:
handleVariableDeclaration(node as ts.VariableDeclaration);
}
return ts.forEachChild(node, cb);
});
function handleDeclaredVariable(
node: ts.ParameterDeclaration | ts.PropertyDeclaration | ts.VariableDeclaration,
): void {
const { name, initializer } = node;
if (name.kind === ts.SyntaxKind.Identifier) {
handleVariableNameFormat(name, initializer);
// do not check property declarations for keywords, they are allowed to be
// keywords
if (node.kind !== ts.SyntaxKind.PropertyDeclaration) {
handleVariableNameKeyword(name);
}
}
}
function handleVariableNameFormat(name: ts.Identifier, initializer?: ts.Expression): void {
if (!options.checkFormat) {
return;
}
const { text } = name;
if (initializer !== undefined && isAlias(text, initializer)) {
return;
}
if (text.length !== 0 && !isCamelCase(text, options) && !isUpperCase(text)) {
ctx.addFailureAtNode(name, formatFailure());
}
}
function handleVariableNameKeyword(name: ts.Identifier): void {
if (options.banKeywords && bannedKeywordsSet.has(name.text)) {
ctx.addFailureAtNode(name, Rule.KEYWORD_FAILURE);
}
}
function handleVariableDeclaration(node: ts.VariableDeclaration): void {
handleDeclaredVariable(node);
if (!ctx.options.allCapsForConst || tsutils.isBindingPattern(node.name)) {
return;
}
const declarationList = node.parent;
const text = node.name.text;
if (isUpperCase(text) && !tsutils.isNodeFlagSet(declarationList, ts.NodeFlags.Const)) {
ctx.addFailureAtNode(node, Rule.FAILURE_STRING_CONST);
}
}
function formatFailure(): string {
let failureMessage = "variable name must be in lowerCamelCase";
if (options.allowPascalCase) {
failureMessage += ", PascalCase";
}
if (options.allowSnakeCase) {
failureMessage += ", snake_case";
}
return `${failureMessage} or UPPER_CASE`;
}
}
function isAlias(name: string, initializer: ts.Expression): boolean {
switch (initializer.kind) {
case ts.SyntaxKind.PropertyAccessExpression:
return (initializer as ts.PropertyAccessExpression).name.text === name;
case ts.SyntaxKind.Identifier:
return (initializer as ts.Identifier).text === name;
default:
return false;
}
}
function isCamelCase(name: string, options: Options): boolean {
const firstCharacter = name[0];
const lastCharacter = name[name.length - 1];
const middle = name.slice(1, -1);
if (!options.leadingUnderscore && firstCharacter === "_") {
return false;
}
if (!options.trailingUnderscore && lastCharacter === "_") {
return false;
}
if (!options.allowPascalCase && !isLowerCase(firstCharacter)) {
return false;
}
if (!options.allowSnakeCase && middle.indexOf("_") !== -1) {
return false;
}
return true;
}