Skip to content
Open
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
37 changes: 25 additions & 12 deletions src/compiler/transformers/esnext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,11 +301,12 @@ export function transformESNext(context: TransformationContext): (x: SourceFile
// produces a shallow transformation to:
//
// for (const x_1 of y) {
// using x = x;
// ...
// using x = x_1;
// { ... }
// }
//
// before handing the shallow transformation back to the visitor for an in-depth transformation.
// where the original loop body is wrapped in an additional block scope
// to handle shadowing variables naturally through block scoping.
const forInitializer = node.initializer;
const forDecl = firstOrUndefined(forInitializer.declarations) || factory.createVariableDeclaration(factory.createTempVariable(/*recordTempVariable*/ undefined));

Expand All @@ -314,6 +315,26 @@ export function transformESNext(context: TransformationContext): (x: SourceFile
const usingVar = factory.updateVariableDeclaration(forDecl, forDecl.name, /*exclamationToken*/ undefined, /*type*/ undefined, temp);
const usingVarList = factory.createVariableDeclarationList([usingVar], isAwaitUsing ? NodeFlags.AwaitUsing : NodeFlags.Using);
const usingVarStatement = factory.createVariableStatement(/*modifiers*/ undefined, usingVarList);

// Wrap the original loop body in an additional block scope to handle shadowing
// Don't create an extra block if the original statement is empty or contains only empty statements
const isEmptyBlock = isBlock(node.statement) && (
node.statement.statements.length === 0 ||
node.statement.statements.every(stmt => stmt.kind === SyntaxKind.EmptyStatement)
);
const shouldWrapInBlock = !isEmptyBlock;

const statements: Statement[] = [usingVarStatement];
if (shouldWrapInBlock) {
const wrappedStatement = isBlock(node.statement) ?
node.statement :
factory.createBlock([node.statement], /*multiLine*/ true);
statements.push(wrappedStatement);
}
else {
statements.push(...(isBlock(node.statement) ? node.statement.statements : [node.statement]));
}

return visitNode(
factory.updateForOfStatement(
node,
Expand All @@ -322,15 +343,7 @@ export function transformESNext(context: TransformationContext): (x: SourceFile
factory.createVariableDeclaration(temp),
], NodeFlags.Const),
node.expression,
isBlock(node.statement) ?
factory.updateBlock(node.statement, [
usingVarStatement,
...node.statement.statements,
]) :
factory.createBlock([
usingVarStatement,
node.statement,
], /*multiLine*/ true),
factory.createBlock(statements, /*multiLine*/ true),
),
visitor,
isStatement,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,9 @@ try {
var env_1 = { stack: [], error: void 0, hasError: false };
try {
var _e = __addDisposableResource(env_1, _e_1, true);
;
{
;
Copy link
Member

Choose a reason for hiding this comment

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

We should consider a block with just an empty statement the same as an empty block and avoid emitting the new block.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Fixed in commit 957cf79. The implementation now considers blocks containing only empty statements as effectively empty and avoids generating the extra wrapping block in those cases.

}
}
catch (e_2) {
env_1.error = e_2;
Expand Down Expand Up @@ -159,7 +161,9 @@ export function test() {
case 3:
_f.trys.push([3, 4, 5, 8]);
_b = __addDisposableResource(env_2, _b_1, true);
;
{
;
}
return [3 /*break*/, 8];
case 4:
e_3 = _f.sent();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,9 @@ for (var _i = 0, x_1 = x; _i < x_1.length; _i++) {
var env_1 = { stack: [], error: void 0, hasError: false };
try {
var _a = __addDisposableResource(env_1, _a_1, true);
;
{
;
}
}
catch (e_1) {
env_1.error = e_1;
Expand Down Expand Up @@ -135,7 +137,9 @@ export function test() {
case 2:
_b.trys.push([2, 3, 4, 7]);
_a = __addDisposableResource(env_2, _a_2, true);
;
{
;
}
return [3 /*break*/, 7];
case 3:
e_2 = _b.sent();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
main.ts(12,7): error TS2481: Cannot initialize outer scoped variable 'baz' in the same scope as block scoped declaration 'baz'.


==== main.ts (1 errors) ====
class Foo {}

for (using foo of []) {
const foo = new Foo();
}

for (using bar of []) {
let bar = "test";
}

for (using baz of []) {
var baz = 42;
~~~
!!! error TS2481: Cannot initialize outer scoped variable 'baz' in the same scope as block scoped declaration 'baz'.
}

==== tslib.d.ts (0 errors) ====
export declare function __addDisposableResource<T>(env: any, value: T, async: boolean): T;
export declare function __disposeResources(env: any): void;

Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOfShadowing.ts] ////

//// [main.ts]
class Foo {}

for (using foo of []) {
const foo = new Foo();
}

for (using bar of []) {
let bar = "test";
}

for (using baz of []) {
var baz = 42;
}

//// [tslib.d.ts]
export declare function __addDisposableResource<T>(env: any, value: T, async: boolean): T;
export declare function __disposeResources(env: any): void;


//// [main.js]
var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose, inner;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async) inner = dispose;
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
env.stack.push({ async: true });
}
return value;
};
var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
return function (env) {
function fail(e) {
env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
var r, s = 0;
function next() {
while (r = env.stack.pop()) {
try {
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
if (r.dispose) {
var result = r.dispose.call(r.value);
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
else s |= 1;
}
catch (e) {
fail(e);
}
}
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError) throw env.error;
}
return next();
};
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
class Foo {
}
for (const foo_1 of []) {
const env_1 = { stack: [], error: void 0, hasError: false };
try {
const foo = __addDisposableResource(env_1, foo_1, false);
{
const foo = new Foo();
}
}
catch (e_1) {
env_1.error = e_1;
env_1.hasError = true;
}
finally {
__disposeResources(env_1);
}
}
for (const bar_1 of []) {
const env_2 = { stack: [], error: void 0, hasError: false };
try {
const bar = __addDisposableResource(env_2, bar_1, false);
{
let bar = "test";
}
}
catch (e_2) {
env_2.error = e_2;
env_2.hasError = true;
}
finally {
__disposeResources(env_2);
}
}
for (const baz_1 of []) {
const env_3 = { stack: [], error: void 0, hasError: false };
try {
const baz = __addDisposableResource(env_3, baz_1, false);
{
var baz = 42;
}
}
catch (e_3) {
env_3.error = e_3;
env_3.hasError = true;
}
finally {
__disposeResources(env_3);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
main.ts(12,7): error TS2481: Cannot initialize outer scoped variable 'baz' in the same scope as block scoped declaration 'baz'.


==== main.ts (1 errors) ====
class Foo {}

for (using foo of []) {
const foo = new Foo();
}

for (using bar of []) {
let bar = "test";
}

for (using baz of []) {
var baz = 42;
~~~
!!! error TS2481: Cannot initialize outer scoped variable 'baz' in the same scope as block scoped declaration 'baz'.
}

==== tslib.d.ts (0 errors) ====
export declare function __addDisposableResource<T>(env: any, value: T, async: boolean): T;
export declare function __disposeResources(env: any): void;

Loading
Loading