Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

Commit

Permalink
no-parameter-properties: Rewrite to walker function (#2663)
Browse files Browse the repository at this point in the history
[no-log] just refactoring
  • Loading branch information
ajafff authored and adidahiya committed May 24, 2017
1 parent 7d95432 commit d39070d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 16 deletions.
24 changes: 13 additions & 11 deletions src/rules/noParameterPropertiesRule.ts
Expand Up @@ -15,6 +15,7 @@
* limitations under the License.
*/

import { isParameterProperty } from "tsutils";
import * as ts from "typescript";

import * as Lint from "../index";
Expand All @@ -40,20 +41,21 @@ export class Rule extends Lint.Rules.AbstractRule {
}

public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new NoParameterPropertiesWalker(sourceFile, this.getOptions()));
return this.applyWithFunction(sourceFile, walk);
}
}

export class NoParameterPropertiesWalker extends Lint.RuleWalker {
public visitConstructorDeclaration(node: ts.ConstructorDeclaration) {
const parameters = node.parameters;
for (const parameter of parameters) {
if (parameter.modifiers != null && parameter.modifiers.length > 0) {
const errorMessage = Rule.FAILURE_STRING_FACTORY((parameter.name as ts.Identifier).text);
const lastModifier = parameter.modifiers[parameter.modifiers.length - 1];
this.addFailureFromStartToEnd(parameter.getStart(), lastModifier.getEnd(), errorMessage);
function walk(ctx: Lint.WalkContext<void>) {
return ts.forEachChild(ctx.sourceFile, function cb(node): void {
if (node.kind === ts.SyntaxKind.Constructor) {
for (const parameter of (node as ts.ConstructorDeclaration).parameters) {
if (isParameterProperty(parameter)) {
ctx.addFailure(parameter.getStart(ctx.sourceFile),
parameter.name.pos,
Rule.FAILURE_STRING_FACTORY(parameter.name.getText(ctx.sourceFile)));
}
}
}
super.visitConstructorDeclaration(node);
}
return ts.forEachChild(node, cb);
});
}
14 changes: 9 additions & 5 deletions test/rules/no-parameter-properties/test.ts.lint
@@ -1,15 +1,17 @@
class Class1 {
// one error
constructor(private foo: string) {
~~~~~~~ [Property 'foo' cannot be declared in the constructor]
~~~~~~~ [err % ('foo')]
}
}

class Class2 {
// two errors, last one is correct
constructor(private foo: string, public bar: string, qux: any) {
~~~~~~~ [Property 'foo' cannot be declared in the constructor]
~~~~~~ [Property 'bar' cannot be declared in the constructor]
// three errors, last one is correct
// don't crash if name is not an identifier
constructor(private foo: string, public bar: string, qux: any, readonly {baz}: any) {
~~~~~~~ [err % ('foo')]
~~~~~~ [err % ('bar')]
~~~~~~~~ [err % ('{baz}')]
}
}

Expand All @@ -18,3 +20,5 @@ class Class3 {
constructor() {
}
}

[err]: Property '%s' cannot be declared in the constructor

0 comments on commit d39070d

Please sign in to comment.