Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add code fix to remove unreachable code #24028

Merged
4 commits merged into from
May 10, 2018
Merged
Show file tree
Hide file tree
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
8 changes: 8 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -4249,5 +4249,13 @@
"Move to a new file": {
"category": "Message",
"code": 95049
},
"Remove unreachable code": {
"category": "Message",
"code": 95050
},
"Remove all unreachable code": {
"category": "Message",
"code": 95051
}
}
1 change: 1 addition & 0 deletions src/harness/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@
"../services/codefixes/fixExtendsInterfaceBecomesImplements.ts",
"../services/codefixes/fixForgottenThisPropertyAccess.ts",
"../services/codefixes/fixUnusedIdentifier.ts",
"../services/codefixes/fixUnreachableCode.ts",
"../services/codefixes/fixJSDocTypes.ts",
"../services/codefixes/fixAwaitInSyncFunction.ts",
"../services/codefixes/disableJsDiagnostics.ts",
Expand Down
1 change: 1 addition & 0 deletions src/server/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
"../services/codefixes/fixExtendsInterfaceBecomesImplements.ts",
"../services/codefixes/fixForgottenThisPropertyAccess.ts",
"../services/codefixes/fixUnusedIdentifier.ts",
"../services/codefixes/fixUnreachableCode.ts",
"../services/codefixes/fixJSDocTypes.ts",
"../services/codefixes/fixAwaitInSyncFunction.ts",
"../services/codefixes/disableJsDiagnostics.ts",
Expand Down
1 change: 1 addition & 0 deletions src/server/tsconfig.library.json
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
"../services/codefixes/fixExtendsInterfaceBecomesImplements.ts",
"../services/codefixes/fixForgottenThisPropertyAccess.ts",
"../services/codefixes/fixUnusedIdentifier.ts",
"../services/codefixes/fixUnreachableCode.ts",
"../services/codefixes/fixJSDocTypes.ts",
"../services/codefixes/fixAwaitInSyncFunction.ts",
"../services/codefixes/disableJsDiagnostics.ts",
Expand Down
89 changes: 89 additions & 0 deletions src/services/codefixes/fixUnreachableCode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/* @internal */
namespace ts.codefix {
const fixId = "fixUnreachableCode";
const errorCodes = [Diagnostics.Unreachable_code_detected.code];
registerCodeFix({
errorCodes,
getCodeActions(context) {
const changes = textChanges.ChangeTracker.with(context, t => doChange(t, context.sourceFile, context.span.start));
return [createCodeFixAction(fixId, changes, Diagnostics.Remove_unreachable_code, fixId, Diagnostics.Remove_all_unreachable_code)];
},
fixIds: [fixId],
getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => doChange(changes, diag.file, diag.start)),
});

function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, start: number): void {
const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
const statement = findAncestor(token, isStatement);
Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile));

const container = (isBlock(statement.parent) ? statement.parent : statement).parent;
switch (container.kind) {
case SyntaxKind.IfStatement:
if ((container as IfStatement).elseStatement) {
if (isBlock(statement.parent)) {
changes.deleteNodeRange(sourceFile, first(statement.parent.statements), last(statement.parent.statements));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't we want to eliminate the whole else-clause?

}
else {
changes.replaceNode(sourceFile, statement, createBlock(emptyArray));
}
break;
}
// falls through
case SyntaxKind.WhileStatement:
case SyntaxKind.ForStatement:
changes.deleteNode(sourceFile, container);
break;
default:
if (isBlock(statement.parent)) {
split(sliceAfter(statement.parent.statements, statement), shouldRemove, (start, end) => changes.deleteNodeRange(sourceFile, start, end));
}
else {
changes.deleteNode(sourceFile, statement);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will a switch case ever be reported as unused? Does that need special handling? What about a catch block?

}
}
}

function shouldRemove(s: Statement): boolean {
// Don't remove statements that can validly be used before they appear.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm missing something - why would it be reported as unused if it's used above?

return !isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) &&
// `var x;` may declare a variable used above
!(isVariableStatement(s) && !(getCombinedNodeFlags(s) & (NodeFlags.Let | NodeFlags.Const)) && s.declarationList.declarations.some(d => !d.initializer));
Copy link
Contributor

@mhegazy mhegazy May 10, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if it is a var statement it make sure it is not ambient.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it's ambient, it should not have an initializer so we won't remove it, right?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

declare let x; would be removed, right?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, right.
Actually, I can't think of a way a declare statement would be unreachable?

}

function isPurelyTypeDeclaration(s: Statement): boolean {
switch (s.kind) {
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
return true;
case SyntaxKind.ModuleDeclaration:
return getModuleInstanceState(s as ModuleDeclaration) !== ModuleInstanceState.Instantiated;
case SyntaxKind.EnumDeclaration:
return hasModifier(s, ModifierFlags.Const);
}
}

function sliceAfter<T>(arr: ReadonlyArray<T>, value: T): ReadonlyArray<T> {
const index = arr.indexOf(value);
Debug.assert(index !== -1);
return arr.slice(index);
}

// Calls 'cb' with the start and end of each range where 'pred' is true.
function split<T>(arr: ReadonlyArray<T>, pred: (t: T) => boolean, cb: (start: T, end: T) => void): void {
let start: T | undefined;
for (let i = 0; i < arr.length; i++) {
const value = arr[i];
if (pred(value)) {
start = start || value;
}
else {
if (start) {
cb(start, arr[i - 1]);
start = undefined;
}
}
}
if (start) cb(start, arr[arr.length - 1]);
}
}
1 change: 1 addition & 0 deletions src/services/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"codefixes/fixExtendsInterfaceBecomesImplements.ts",
"codefixes/fixForgottenThisPropertyAccess.ts",
"codefixes/fixUnusedIdentifier.ts",
"codefixes/fixUnreachableCode.ts",
"codefixes/fixJSDocTypes.ts",
"codefixes/fixAwaitInSyncFunction.ts",
"codefixes/disableJsDiagnostics.ts",
Expand Down
31 changes: 31 additions & 0 deletions tests/cases/fourslash/codeFixUnreachableCode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/// <reference path='fourslash.ts' />

////function f() {
//// return f();
//// return 1;
//// function f() {}
//// return 2;
//// type T = number;
//// interface I {}
//// const enum E {}
//// enum E {}
//// namespace N { export type T = number; }
//// namespace N { export const x = 0; }
//// var x;
//// var y = 0;
////}

verify.codeFix({
description: "Remove unreachable code",
index: 0,
newFileContent:
`function f() {
return f();
function f() {}
type T = number;
interface I {}
const enum E {}
namespace N { export type T = number; }
var x;
}`,
});
40 changes: 40 additions & 0 deletions tests/cases/fourslash/codeFixUnreachableCode_if.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/// <reference path='fourslash.ts' />

////if (false) a;
////if (false) {
//// a;
////}
////
////// No good way to delete just the 'if' part
////if (false) a; else b;
////if (false) {
//// a;
////} else {
//// b;
////}
////
////while (false) a;
////while (false) {
//// a;
////}
////
////for (let x = 0; false; ++x) a;
////for (let x = 0; false; ++x) {
//// a;
////}

verify.codeFixAll({
fixId: "fixUnreachableCode",
fixAllDescription: "Remove all unreachable code",
newFileContent:
`
// No good way to delete just the 'if' part
if (false) { } else b;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In a perfect world, the output would be b;?

if (false) {
} else {
b;
}


`,
});