This repository has been archived by the owner on Mar 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 887
/
Copy pathmemberAccessRule.ts
236 lines (221 loc) · 8.66 KB
/
memberAccessRule.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
/**
* @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.
*/
import {
getChildOfKind,
getModifier,
getNextToken,
getTokenAtPosition,
hasModifier,
isClassLikeDeclaration,
isConstructorDeclaration,
isParameterProperty,
} from "tsutils";
import * as ts from "typescript";
import { showWarningOnce } from "../error";
import * as Lint from "../index";
const OPTION_NO_PUBLIC = "no-public";
const OPTION_CHECK_ACCESSOR = "check-accessor";
const OPTION_CHECK_CONSTRUCTOR = "check-constructor";
const OPTION_CHECK_PARAMETER_PROPERTY = "check-parameter-property";
interface Options {
noPublic: boolean;
checkAccessor: boolean;
checkConstructor: boolean;
checkParameterProperty: boolean;
}
export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "member-access",
description: "Requires explicit visibility declarations for class members.",
rationale: Lint.Utils.dedent`
Explicit visibility declarations can make code more readable and accessible for those new to TS.
Other languages such as C# default to \`private\`, unlike TypeScript's default of \`public\`.
Members lacking a visibility declaration may be an indication of an accidental leak of class internals.
`,
optionsDescription: Lint.Utils.dedent`
These arguments may be optionally provided:
* \`"no-public"\` forbids public accessibility to be specified, because this is the default.
* \`"check-accessor"\` enforces explicit visibility on get/set accessors
* \`"check-constructor"\` enforces explicit visibility on constructors
* \`"check-parameter-property"\` enforces explicit visibility on parameter properties`,
options: {
type: "array",
items: {
type: "string",
enum: [
OPTION_NO_PUBLIC,
OPTION_CHECK_ACCESSOR,
OPTION_CHECK_CONSTRUCTOR,
OPTION_CHECK_PARAMETER_PROPERTY,
],
},
minLength: 0,
maxLength: 4,
},
optionExamples: [true, [true, OPTION_NO_PUBLIC], [true, OPTION_CHECK_ACCESSOR]],
type: "typescript",
typescriptOnly: true,
hasFix: true,
};
/* tslint:enable:object-literal-sort-keys */
public static FAILURE_STRING_NO_PUBLIC = "'public' is implicit.";
public static FAILURE_STRING_FACTORY(
memberType: string,
memberName: string | undefined,
): string {
memberName = memberName === undefined ? "" : ` '${memberName}'`;
return `The ${memberType}${memberName} must be marked either 'private', 'public', or 'protected'`;
}
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
const options = this.ruleArguments;
const noPublic = options.indexOf(OPTION_NO_PUBLIC) !== -1;
let checkAccessor = options.indexOf(OPTION_CHECK_ACCESSOR) !== -1;
let checkConstructor = options.indexOf(OPTION_CHECK_CONSTRUCTOR) !== -1;
let checkParameterProperty = options.indexOf(OPTION_CHECK_PARAMETER_PROPERTY) !== -1;
if (noPublic) {
if (checkAccessor || checkConstructor || checkParameterProperty) {
showWarningOnce(
`Warning: ${
this.ruleName
} - If 'no-public' is present, it should be the only option.`,
);
return [];
}
checkAccessor = checkConstructor = checkParameterProperty = true;
}
return this.applyWithFunction(sourceFile, walk, {
checkAccessor,
checkConstructor,
checkParameterProperty,
noPublic,
});
}
}
function walk(ctx: Lint.WalkContext<Options>) {
const { noPublic, checkAccessor, checkConstructor, checkParameterProperty } = ctx.options;
return ts.forEachChild(ctx.sourceFile, function recur(node: ts.Node): void {
if (isClassLikeDeclaration(node)) {
for (const child of node.members) {
if (shouldCheck(child)) {
check(child);
}
if (
checkParameterProperty &&
isConstructorDeclaration(child) &&
child.body !== undefined
) {
for (const param of child.parameters) {
if (isParameterProperty(param)) {
check(param);
}
}
}
}
}
return ts.forEachChild(node, recur);
});
function shouldCheck(node: ts.ClassElement): boolean {
switch (node.kind) {
case ts.SyntaxKind.Constructor:
return checkConstructor;
case ts.SyntaxKind.GetAccessor:
case ts.SyntaxKind.SetAccessor:
return checkAccessor;
case ts.SyntaxKind.MethodDeclaration:
case ts.SyntaxKind.PropertyDeclaration:
return true;
default:
return false;
}
}
function check(node: ts.ClassElement | ts.ParameterDeclaration): void {
if (
hasModifier(
node.modifiers,
ts.SyntaxKind.ProtectedKeyword,
ts.SyntaxKind.PrivateKeyword,
)
) {
return;
}
const publicKeyword = getModifier(node, ts.SyntaxKind.PublicKeyword);
if (noPublic && publicKeyword !== undefined) {
// public is not optional for parameter property without the readonly modifier
if (
node.kind !== ts.SyntaxKind.Parameter ||
hasModifier(node.modifiers, ts.SyntaxKind.ReadonlyKeyword)
) {
const start = publicKeyword.end - "public".length;
ctx.addFailure(
start,
publicKeyword.end,
Rule.FAILURE_STRING_NO_PUBLIC,
Lint.Replacement.deleteFromTo(
start,
getNextToken(publicKeyword, ctx.sourceFile)!.getStart(ctx.sourceFile),
),
);
}
}
if (!noPublic && publicKeyword === undefined) {
const nameNode =
node.kind === ts.SyntaxKind.Constructor
? getChildOfKind(node, ts.SyntaxKind.ConstructorKeyword, ctx.sourceFile)!
: node.name !== undefined
? node.name
: node;
const memberName =
node.name !== undefined && node.name.kind === ts.SyntaxKind.Identifier
? node.name.text
: undefined;
ctx.addFailureAtNode(
nameNode,
Rule.FAILURE_STRING_FACTORY(typeToString(node), memberName),
Lint.Replacement.appendText(getInsertionPosition(node, ctx.sourceFile), "public "),
);
}
}
}
function getInsertionPosition(
member: ts.ClassElement | ts.ParameterDeclaration,
sourceFile: ts.SourceFile,
): number {
const node =
member.decorators === undefined
? member
: getTokenAtPosition(member, member.decorators.end, sourceFile)!;
return node.getStart(sourceFile);
}
function typeToString(node: ts.ClassElement | ts.ParameterDeclaration): string {
switch (node.kind) {
case ts.SyntaxKind.MethodDeclaration:
return "class method";
case ts.SyntaxKind.PropertyDeclaration:
return "class property";
case ts.SyntaxKind.Constructor:
return "class constructor";
case ts.SyntaxKind.GetAccessor:
return "get property accessor";
case ts.SyntaxKind.SetAccessor:
return "set property accessor";
case ts.SyntaxKind.Parameter:
return "parameter property";
default:
throw new Error(`unhandled node type ${ts.SyntaxKind[node.kind]}`);
}
}