Skip to content

Commit

Permalink
convert no-var-self rule to use a walk function (microsoft#774)
Browse files Browse the repository at this point in the history
  • Loading branch information
drexler authored and apawast committed Feb 26, 2019
1 parent 8e095b3 commit 276999c
Showing 1 changed file with 31 additions and 15 deletions.
46 changes: 31 additions & 15 deletions src/noVarSelfRule.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import * as ts from 'typescript';
import * as Lint from 'tslint';
import * as tsutils from 'tsutils';

import { ExtendedMetadata } from './utils/ExtendedMetadata';

interface Options {
bannedVariableNames: RegExp;
}

const FAILURE_STRING: string = 'Assigning this reference to local variable: ';

export class Rule extends Lint.Rules.AbstractRule {
Expand All @@ -29,29 +34,40 @@ export class Rule extends Lint.Rules.AbstractRule {
console.warn('Warning: no-var-self rule is deprecated. Replace your usage with the TSLint no-this-assignment rule.');
Rule.isWarningShown = true;
}
return this.applyWithWalker(new NoVarSelfRuleWalker(sourceFile, this.getOptions()));

return this.applyWithFunction(sourceFile, walk, this.parseOptions(this.getOptions()));
}
}

class NoVarSelfRuleWalker extends Lint.RuleWalker {
private readonly bannedVariableNames: RegExp = /.*/; // default is to ban everything
private parseOptions(options: Lint.IOptions): Options {
const opt: Options = {
bannedVariableNames: /.*/
};

constructor(sourceFile: ts.SourceFile, options: Lint.IOptions) {
super(sourceFile, options);
if (options.ruleArguments !== undefined && options.ruleArguments.length > 0) {
this.bannedVariableNames = new RegExp(options.ruleArguments[0]);
if (options.ruleArguments && options.ruleArguments.length > 0) {
opt.bannedVariableNames = new RegExp(options.ruleArguments[0]);
}

return opt;
}
}

function walk(ctx: Lint.WalkContext<Options>) {
const { bannedVariableNames } = ctx.options;

protected visitVariableDeclaration(node: ts.VariableDeclaration): void {
if (node.initializer !== undefined && node.initializer.kind === ts.SyntaxKind.ThisKeyword) {
if (node.name.kind === ts.SyntaxKind.Identifier) {
const identifier: ts.Identifier = <ts.Identifier>node.name;
if (this.bannedVariableNames.test(identifier.text)) {
this.addFailureAt(node.getStart(), node.getWidth(), FAILURE_STRING + node.getText());
function cb(node: ts.Node): void {
if (tsutils.isVariableDeclaration(node)) {
if (node.initializer && node.initializer.kind === ts.SyntaxKind.ThisKeyword) {
if (tsutils.isIdentifier(node.name)) {
const identifier: ts.Identifier = node.name;
if (bannedVariableNames.test(identifier.text)) {
ctx.addFailureAt(node.getStart(), node.getWidth(), FAILURE_STRING + node.getText());
}
}
}
}
super.visitVariableDeclaration(node);

return ts.forEachChild(node, cb);
}

return ts.forEachChild(ctx.sourceFile, cb);
}

0 comments on commit 276999c

Please sign in to comment.