Skip to content

Commit 7b1147f

Browse files
committed
Stop inadvertently exempting expression statements from check
1 parent 2a4ab08 commit 7b1147f

File tree

4 files changed

+42
-8
lines changed

4 files changed

+42
-8
lines changed

src/harness/unittests/extractConstants.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@ function F() {
4040
}
4141
`);
4242

43+
testExtractConstant("extractConstant_ExpressionStatementConsumesLocal", `
44+
function F() {
45+
let i = 0;
46+
[#|i++|];
47+
}
48+
`);
49+
4350
testExtractConstant("extractConstant_BlockScopes_NoDependencies",
4451
`for (let i = 0; i < 10; i++) {
4552
for (let j = 0; j < 10; j++) {

src/services/refactors/extractSymbol.ts

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1351,14 +1351,13 @@ namespace ts.refactor.extractSymbol {
13511351
}
13521352

13531353
for (let i = 0; i < scopes.length; i++) {
1354-
if (!isReadonlyArray(targetRange.range)) {
1355-
const scopeUsages = usagesPerScope[i];
1356-
// Special case: in the innermost scope, all usages are available.
1357-
// (The computed value reflects the value at the top-level of the scope, but the
1358-
// local will actually be declared at the same level as the extracted expression).
1359-
if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) {
1360-
constantErrorsPerScope[i].push(createDiagnosticForNode(targetRange.range, Messages.CannotAccessVariablesFromNestedScopes));
1361-
}
1354+
const scopeUsages = usagesPerScope[i];
1355+
// Special case: in the innermost scope, all usages are available.
1356+
// (The computed value reflects the value at the top-level of the scope, but the
1357+
// local will actually be declared at the same level as the extracted expression).
1358+
if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) {
1359+
const errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range;
1360+
constantErrorsPerScope[i].push(createDiagnosticForNode(errorNode, Messages.CannotAccessVariablesFromNestedScopes));
13621361
}
13631362

13641363
let hasWrite = false;
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// ==ORIGINAL==
2+
3+
function F() {
4+
let i = 0;
5+
i++;
6+
}
7+
8+
// ==SCOPE::Extract to constant in enclosing scope==
9+
10+
function F() {
11+
let i = 0;
12+
const /*RENAME*/newLocal = i++;
13+
}
14+
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// ==ORIGINAL==
2+
3+
function F() {
4+
let i = 0;
5+
i++;
6+
}
7+
8+
// ==SCOPE::Extract to constant in enclosing scope==
9+
10+
function F() {
11+
let i = 0;
12+
const /*RENAME*/newLocal = i++;
13+
}
14+

0 commit comments

Comments
 (0)