2015-11-11 22:30:26 +01:00
|
|
|
import * as Lint from "tslint/lib/lint";
|
|
|
|
import * as ts from "typescript";
|
2015-08-26 20:59:53 +02:00
|
|
|
|
|
|
|
export class Rule extends Lint.Rules.AbstractRule {
|
|
|
|
public static FAILURE_STRING_FACTORY = (name: string, currently: string) => `Tag boolean argument as '${name}' (currently '${currently}')`;
|
|
|
|
|
|
|
|
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
|
|
|
|
const program = ts.createProgram([sourceFile.fileName], Lint.createCompilerOptions());
|
|
|
|
const checker = program.getTypeChecker();
|
|
|
|
return this.applyWithWalker(new BooleanTriviaWalker(checker, program.getSourceFile(sourceFile.fileName), this.getOptions()));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class BooleanTriviaWalker extends Lint.RuleWalker {
|
|
|
|
constructor(private checker: ts.TypeChecker, file: ts.SourceFile, opts: Lint.IOptions) {
|
|
|
|
super(file, opts);
|
|
|
|
}
|
|
|
|
|
|
|
|
visitCallExpression(node: ts.CallExpression) {
|
|
|
|
super.visitCallExpression(node);
|
2015-11-11 22:30:26 +01:00
|
|
|
if (node.arguments) {
|
2015-08-26 20:59:53 +02:00
|
|
|
const targetCallSignature = this.checker.getResolvedSignature(node);
|
|
|
|
if (!!targetCallSignature) {
|
|
|
|
const targetParameters = targetCallSignature.getParameters();
|
|
|
|
const source = this.getSourceFile();
|
|
|
|
for (let index = 0; index < targetParameters.length; index++) {
|
|
|
|
const param = targetParameters[index];
|
|
|
|
const arg = node.arguments[index];
|
2015-12-28 23:11:55 +01:00
|
|
|
if (!(arg && param)) {
|
|
|
|
continue;
|
|
|
|
}
|
2015-08-26 20:59:53 +02:00
|
|
|
|
|
|
|
const argType = this.checker.getContextualType(arg);
|
|
|
|
if (argType && (argType.getFlags() & ts.TypeFlags.Boolean)) {
|
|
|
|
if (arg.kind !== ts.SyntaxKind.TrueKeyword && arg.kind !== ts.SyntaxKind.FalseKeyword) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
let triviaContent: string;
|
|
|
|
const ranges = ts.getLeadingCommentRanges(arg.getFullText(), 0);
|
|
|
|
if (ranges && ranges.length === 1 && ranges[0].kind === ts.SyntaxKind.MultiLineCommentTrivia) {
|
2015-11-11 22:30:26 +01:00
|
|
|
triviaContent = arg.getFullText().slice(ranges[0].pos + 2, ranges[0].end - 2); // +/-2 to remove /**/
|
2015-08-26 20:59:53 +02:00
|
|
|
}
|
2015-12-28 23:11:55 +01:00
|
|
|
|
|
|
|
const paramName = param.getName();
|
|
|
|
if (triviaContent !== paramName && triviaContent !== paramName + ":") {
|
2015-08-26 20:59:53 +02:00
|
|
|
this.addFailure(this.createFailure(arg.getStart(source), arg.getWidth(source), Rule.FAILURE_STRING_FACTORY(param.getName(), triviaContent)));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-11-11 22:30:26 +01:00
|
|
|
}
|
2015-08-26 20:59:53 +02:00
|
|
|
}
|
|
|
|
}
|