This repository has been archived by the owner on Mar 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 889
New Rule: param-property-in-constructor #1358
Closed
ChrisMBarr
wants to merge
6
commits into
palantir:master
from
ChrisMBarr:proper-constructor-param-usage
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
6838d23
Merge remote-tracking branch 'palantir/master'
ChrisMBarr 203f039
Merge remote-tracking branch 'palantir/master'
ChrisMBarr ea9f344
Adding new rule: no-improper-constructor-param-usage
ChrisMBarr 9aa60f3
Renaming rule & updating based on suggestions
7a32109
Merge remote-tracking branch 'upstream/master' into proper-constructo…
b7a2984
grunt did this...
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
/** | ||
* @license | ||
* Copyright 2014 Palantir Technologies, Inc. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
import * as Lint from "../lint"; | ||
import * as ts from "typescript"; | ||
|
||
export class Rule extends Lint.Rules.AbstractRule { | ||
/* tslint:disable:object-literal-sort-keys */ | ||
public static metadata: Lint.IRuleMetadata = { | ||
ruleName: "param-property-in-constructor", | ||
description: "Disallows constructor parameter properties to be accessed without the 'this.' prefix", | ||
rationale: Lint.Utils.dedent` | ||
This helps enforce consistancy. | ||
When a constructor parameter is accessed without the 'this.' prefix, it is actually not acessing the same thing. | ||
Example: | ||
class Foo { | ||
constructor(public num: number) { | ||
this.num = 10; | ||
num = 5; //this should be disallowed! | ||
} | ||
} | ||
const f = new Foo(); | ||
alert(f.num); // will display 10`, | ||
optionsDescription: "Not configurable.", | ||
options: null, | ||
optionExamples: ["true"], | ||
type: "functionality", | ||
}; | ||
/* tslint:enable:object-literal-sort-keys */ | ||
|
||
public static FAILURE_STRING_FACTORY = (paramName: string) => { | ||
return `The constructor parameter '${paramName}' should only be accessed with the 'this' keyword: 'this.${paramName}'`; | ||
} | ||
|
||
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { | ||
const languageService = Lint.createLanguageService(sourceFile.fileName, sourceFile.getFullText()); | ||
return this.applyWithWalker(new ParamPropInCtorWalker(sourceFile, this.getOptions(), languageService)); | ||
} | ||
} | ||
|
||
export class ParamPropInCtorWalker extends Lint.RuleWalker { | ||
|
||
constructor(sourceFile: ts.SourceFile, options: Lint.IOptions, private languageService: ts.LanguageService) { | ||
super(sourceFile, options); | ||
this.languageService = languageService; | ||
} | ||
|
||
public visitConstructorDeclaration(node: ts.ConstructorDeclaration) { | ||
if (node.parameters && node.parameters.length > 0) { | ||
const fileName = this.getSourceFile().fileName; | ||
for (let param of node.parameters) { | ||
if (param.modifiers != null && param.modifiers.length > 0) { | ||
this.validateParam(param, fileName); | ||
} | ||
} | ||
} | ||
super.visitConstructorDeclaration(node); | ||
} | ||
|
||
private validateParam(param: ts.ParameterDeclaration, fileName: string) { | ||
const highlights = this.languageService.getDocumentHighlights(fileName, param.name.getStart(), [fileName]); | ||
|
||
if ((highlights !== null && highlights[0].highlightSpans.length > 0)) { | ||
const paramName = param.name.getText(); | ||
highlights[0].highlightSpans.forEach((span: ts.HighlightSpan, idx: number) => { | ||
// Ignore the 1st reference which is the actual parameter definition | ||
if (idx !== 0 && !this.spanHasThisUsage(span, fileName)) { | ||
const msg = Rule.FAILURE_STRING_FACTORY(paramName); | ||
this.addFailure(this.createFailure(span.textSpan.start, span.textSpan.length, msg)); | ||
} | ||
}); | ||
} | ||
} | ||
|
||
private spanHasThisUsage(span: ts.HighlightSpan, fileName: string) { | ||
const endPos = span.textSpan.start + span.textSpan.length; | ||
const nameSpanInfo = this.languageService.getNameOrDottedNameSpan(fileName, span.textSpan.start, endPos); | ||
|
||
// If the difference between these two is exactly 5 characters it accounts for the missing `this.`! | ||
return nameSpanInfo.length - span.textSpan.length === 5; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
class FailingExample1 { | ||
constructor(fruit: string, public num: number, private animal: string, protected mineral: string) { | ||
//Both usage here are OK since `fruit` is a regular parameter and not a class property | ||
fruit = "banana"; | ||
this.fruit = "persimmon"; | ||
|
||
this.num = 10; | ||
num = 5; | ||
~~~ [The constructor parameter 'num' should only be accessed with the 'this' keyword: 'this.num'] | ||
|
||
animal = "aardvark"; | ||
~~~~~~ [The constructor parameter 'animal' should only be accessed with the 'this' keyword: 'this.animal'] | ||
this.animal = "skunk"; | ||
|
||
mineral = "Gypsum"; | ||
~~~~~~~ [The constructor parameter 'mineral' should only be accessed with the 'this' keyword: 'this.mineral'] | ||
this.mineral = "Fluorite"; | ||
} | ||
} | ||
|
||
class FailingExample2 { | ||
constructor(public thing: Object) { | ||
const wow=thing.doTheThing() | ||
~~~~~ [The constructor parameter 'thing' should only be accessed with the 'this' keyword: 'this.thing'] | ||
console.log(wow, thing.amazingDvdCollection); | ||
~~~~~ [The constructor parameter 'thing' should only be accessed with the 'this' keyword: 'this.thing'] | ||
|
||
const pasta = thing.nested.makePasta(); | ||
~~~~~ [The constructor parameter 'thing' should only be accessed with the 'this' keyword: 'this.thing'] | ||
|
||
thing = {}; | ||
~~~~~ [The constructor parameter 'thing' should only be accessed with the 'this' keyword: 'this.thing'] | ||
|
||
this.thing.doSomethingElse(); | ||
} | ||
} | ||
|
||
class PassingExample1 { | ||
//This is OK since `thing` is a regular parameter and not a class property here | ||
constructor(thing: Object) { | ||
const wow=thing.doTheThing() | ||
console.log(wow,thing.amazingDvdCollection); | ||
const pasta = thing.nested.makePasta(); | ||
thing = {}; | ||
this.thing.doSomethingElse(); | ||
} | ||
} | ||
|
||
class PassingExample2 { | ||
constructor(a: string, private b: string, public c: string, protected d: string) { | ||
this.a = "aaa"; | ||
this.b = "bbb"; | ||
this.c = "ccc"; | ||
this.d = "ddd"; | ||
} | ||
} | ||
|
||
class PassingExample3 { | ||
constructor(a: Object, private b: Object, public c: Object, protected d: Object) { | ||
this.a.doThing(); | ||
this.b.doOtherThing(); | ||
this.c.doAnotherThing(); | ||
this.d.doLastThing(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
{ | ||
"rules": { | ||
"param-property-in-constructor": true | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm, I wasn't thinking about this use case. When accessing a value, it doesn't matter if you use
this.
or not. Do you think we should still disallow this?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
On the other hand, using
this.
doesn't hurtThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yeah that was my thinking with the way it was written initially. I was thinking that if we just require
this.
on everything, then there is consistency for how all constructor params are used, regardless if they are used as properties or not.