Skip to content
This repository has been archived by the owner on Jul 15, 2023. It is now read-only.

convert no-var-self rule to use a walk function #774

Merged
merged 1 commit into from
Jan 7, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}