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
Add no-unsafe-any
rule
#2047
Merged
Merged
Add no-unsafe-any
rule
#2047
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
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
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,119 @@ | ||
/** | ||
* @license | ||
* Copyright 2017 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 ts from "typescript"; | ||
import * as Lint from "../index"; | ||
|
||
export class Rule extends Lint.Rules.TypedRule { | ||
/* tslint:disable:object-literal-sort-keys */ | ||
public static metadata: Lint.IRuleMetadata = { | ||
ruleName: "strict-boolean-expressions", | ||
description: Lint.Utils.dedent` | ||
Warns when using an expression of type 'any' in an unsafe way. | ||
Type casts and tests are allowed. | ||
Expressions that work on all values (such as '"" + x') are allowed.`, | ||
optionsDescription: "Not configurable.", | ||
options: null, | ||
optionExamples: ["true"], | ||
type: "functionality", | ||
typescriptOnly: true, | ||
requiresTypeInfo: true, | ||
}; | ||
/* tslint:enable:object-literal-sort-keys */ | ||
|
||
public static FAILURE_STRING = "Unsafe use of expression of type 'any'."; | ||
|
||
public applyWithProgram(srcFile: ts.SourceFile, langSvc: ts.LanguageService): Lint.RuleFailure[] { | ||
return this.applyWithWalker(new Walker(srcFile, this.getOptions(), langSvc.getProgram())); | ||
} | ||
} | ||
|
||
class Walker extends Lint.ProgramAwareRuleWalker { | ||
public visitNode(node: ts.Node) { | ||
if (ts.isExpression(node) && isAny(this.getType(node)) && !this.isAllowedLocation(node)) { | ||
this.addFailureAtNode(node, Rule.FAILURE_STRING); | ||
} else { | ||
super.visitNode(node); | ||
} | ||
} | ||
|
||
private isAllowedLocation(node: ts.Expression): boolean { | ||
const parent = node.parent!; | ||
switch (parent.kind) { | ||
case ts.SyntaxKind.ExpressionStatement: // Allow unused expression | ||
case ts.SyntaxKind.Parameter: // Allow to declare a parameter of type 'any' | ||
case ts.SyntaxKind.TypeOfExpression: // Allow test | ||
case ts.SyntaxKind.TemplateSpan: // Allow stringification (works on all values) | ||
// Allow casts | ||
case ts.SyntaxKind.TypeAssertionExpression: | ||
case ts.SyntaxKind.AsExpression: | ||
return true; | ||
|
||
// OK to pass 'any' to a function that takes 'any' as its argument | ||
case ts.SyntaxKind.CallExpression: | ||
case ts.SyntaxKind.NewExpression: | ||
return isAny(this.getTypeChecker().getContextualType(node)); | ||
|
||
case ts.SyntaxKind.BinaryExpression: | ||
const { left, right, operatorToken } = parent as ts.BinaryExpression; | ||
switch (operatorToken.kind) { | ||
case ts.SyntaxKind.InstanceOfKeyword: // Allow test | ||
// Allow equality since all values support equality. | ||
case ts.SyntaxKind.EqualsEqualsToken: | ||
case ts.SyntaxKind.EqualsEqualsEqualsToken: | ||
case ts.SyntaxKind.ExclamationEqualsToken: | ||
case ts.SyntaxKind.ExclamationEqualsEqualsToken: | ||
return true; | ||
case ts.SyntaxKind.PlusToken: // Allow stringification | ||
return node === left ? this.isStringLike(right) : this.isStringLike(left); | ||
case ts.SyntaxKind.PlusEqualsToken: // Allow stringification in `str += x;`, but not `x += str;`. | ||
return node === right && this.isStringLike(left); | ||
default: | ||
return false; | ||
} | ||
|
||
// Allow `const x = foo;`, but not `const x: Foo = foo;`. | ||
case ts.SyntaxKind.VariableDeclaration: | ||
return Lint.hasModifier(parent.parent!.parent!.modifiers, ts.SyntaxKind.DeclareKeyword) || | ||
(parent as ts.VariableDeclaration).type === undefined; | ||
|
||
case ts.SyntaxKind.PropertyAccessExpression: | ||
// Don't warn for right hand side; this is redundant if we warn for the left-hand side. | ||
return (parent as ts.PropertyAccessExpression).name === node; | ||
|
||
default: | ||
return false; | ||
} | ||
} | ||
|
||
private isStringLike(node: ts.Expression) { | ||
return Lint.isTypeFlagSet(this.getType(node), ts.TypeFlags.StringLike); | ||
} | ||
|
||
private getType(node: ts.Expression): ts.Type { | ||
return this.getTypeChecker().getTypeAtLocation(node); | ||
} | ||
} | ||
|
||
function isAny(type: ts.Type | undefined): boolean { | ||
return type !== undefined && Lint.isTypeFlagSet(type, ts.TypeFlags.Any); | ||
} | ||
|
||
// This is marked @internal, but we need it! | ||
declare module "typescript" { | ||
export function isExpression(node: ts.Node): node is ts.Expression; | ||
} |
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,54 @@ | ||
declare const x: any; | ||
|
||
function f(x: any) { | ||
x.foo; | ||
~ [0] | ||
x(0); | ||
~ [0] | ||
x``; | ||
~ [0] | ||
x + 3; | ||
~ [0] | ||
|
||
// OK to pass it to a function that takes `any` | ||
g(x); | ||
// Not OK to pass to any other function. | ||
[].map(x); | ||
~ [0] | ||
|
||
// Same for constructors | ||
new X(x); | ||
new Y(x); | ||
~ [0] | ||
} | ||
|
||
class X { constructor(x: any) {} } | ||
class Y { constructor(x: number) {} } | ||
|
||
function g(x: any): string { | ||
if (x === undefined) { | ||
return "undefined"; | ||
} | ||
if (typeof x === "string") { | ||
return `string: ${x}`; | ||
} | ||
if (x instanceof Array) { | ||
// Once it's been tested, OK to use it as an array. | ||
return `Array, length ${x.length}`; | ||
} | ||
if (Math.random() > 0.5) { | ||
// Allow explicit cast | ||
return (<string> x).toLowerCase() + (x as string).toUpperCase(); | ||
} | ||
|
||
"" + x; | ||
x + ""; | ||
let s = ""; | ||
s += x; | ||
x += s; | ||
~ [0] | ||
|
||
return `other: ${x}`; | ||
} | ||
|
||
[0]: Unsafe use of expression of type 'any'. |
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,8 @@ | ||
{ | ||
"linterOptions": { | ||
"typeCheck": true | ||
}, | ||
"rules": { | ||
"no-unsafe-any": true | ||
} | ||
} |
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.
Rule name is misspelled. (Not a code review; I'm just here to read the description.)