UNPKG

3.13 kBPlain TextView Raw
1import * as ts from 'typescript';
2import * as Lint from 'tslint';
3import { ErrorTolerantWalker } from './ErrorTolerantWalker';
4
5/**
6 * Implementation of the banned-term rulesets.
7 */
8export class BannedTermWalker extends ErrorTolerantWalker {
9 private failureString: string;
10 private bannedTerms: string[];
11 private allowQuotedProperties: boolean = false;
12
13 constructor(sourceFile: ts.SourceFile, options: Lint.IOptions, failureString: string, bannedTerms: string[]) {
14 super(sourceFile, options);
15 this.failureString = failureString;
16 this.bannedTerms = bannedTerms;
17 this.getOptions().forEach((opt: any) => {
18 if (typeof opt === 'object') {
19 this.allowQuotedProperties = opt['allow-quoted-properties'] === true;
20 }
21 });
22 }
23
24 protected visitFunctionDeclaration(node: ts.FunctionDeclaration): void {
25 this.validateNode(node);
26 super.visitFunctionDeclaration(node);
27 }
28
29 protected visitGetAccessor(node: ts.AccessorDeclaration): void {
30 this.validateNode(node);
31 super.visitGetAccessor(node);
32 }
33
34 protected visitMethodDeclaration(node: ts.MethodDeclaration): void {
35 this.validateNode(node);
36 super.visitMethodDeclaration(node);
37 }
38
39 protected visitParameterDeclaration(node: ts.ParameterDeclaration): void {
40 // typescript 2.0 introduces function level 'this' types
41 if (node.name.getText() !== 'this') {
42 this.validateNode(node);
43 }
44 super.visitParameterDeclaration(node);
45 }
46
47 protected visitPropertyDeclaration(node: ts.PropertyDeclaration): void {
48 this.validateNode(node);
49 super.visitPropertyDeclaration(node);
50 }
51
52 protected visitPropertySignature(node: ts.Node): void {
53 if (node.kind === ts.SyntaxKind.PropertySignature) {
54 const signature: ts.PropertySignature = <ts.PropertySignature>node;
55 const propertyName = signature.name;
56 // ignore StringLiteral property names if that option is set
57 if (this.allowQuotedProperties === false || propertyName.kind !== ts.SyntaxKind.StringLiteral) {
58 this.validateNode(node);
59 }
60 } else {
61 this.validateNode(node);
62 }
63 super.visitPropertySignature(node);
64 }
65
66 protected visitSetAccessor(node: ts.AccessorDeclaration): void {
67 this.validateNode(node);
68 super.visitSetAccessor(node);
69 }
70
71 protected visitVariableDeclaration(node: ts.VariableDeclaration): void {
72 this.validateNode(node);
73 super.visitVariableDeclaration(node);
74 }
75
76 private validateNode(node: ts.Node): void {
77 if ((<any>node).name) {
78 if ((<any>node).name.text) {
79 const text: string = (<any>node).name.text;
80 if (this.isBannedTerm(text)) {
81 this.addFailureAt(node.getStart(), node.getWidth(), this.failureString + text);
82 }
83 }
84 }
85 }
86
87 private isBannedTerm(text: string): boolean {
88 return this.bannedTerms.indexOf(text) !== -1;
89 }
90}