File size: 64,446 Bytes
d0faac4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 | You are working in `/workspace/typescript`, a source tree checked out at
the base commit for this task. Implement the requested behavior in the source
tree, then run:
```bash
lolbench-submit
```
Do not stop after editing files, running tests, or describing the solution. The
task is complete only when `lolbench-submit` has created
`/logs/artifacts/solution.patch`. If that file does not exist, continue
working and run `lolbench-submit` again.
That command writes your implementation diff to
`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifier
will grade. Before running `lolbench-submit`, clean or revert any test files
you created or modified; test files must not be included in the final
`solution.patch`.
This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources.
Now please implement the following requirements in the source tree:
---
# ECMAScript Explicit Resource Management
> **NOTE:** This proposal has subsumed the [Async Explicit Resource Management](https://github.com/tc39/proposal-async-explicit-resource-management)
> proposal. This proposal repository should be used for further discussion of both sync and async of explicit resource
> management.
This proposal intends to address a common pattern in software development regarding
the lifetime and management of various resources (memory, I/O, etc.). This pattern
generally includes the allocation of a resource and the ability to explicitly
release critical resources.
For example, ECMAScript Generator Functions and Async Generator Functions expose this pattern through the
`return` method, as a means to explicitly evaluate `finally` blocks to ensure
user-defined cleanup logic is preserved:
```js
// sync generators
function * g() {
const handle = acquireFileHandle(); // critical resource
try {
...
}
finally {
handle.release(); // cleanup
}
}
const obj = g();
try {
const r = obj.next();
...
}
finally {
obj.return(); // calls finally blocks in `g`
}
```
```js
// async generators
async function * g() {
const handle = acquireStream(); // critical resource
try {
...
}
finally {
await stream.close(); // cleanup
}
}
const obj = g();
try {
const r = await obj.next();
...
}
finally {
await obj.return(); // calls finally blocks in `g`
}
```
As such, we propose the adoption of a novel syntax to simplify this common pattern:
```js
// sync disposal
function * g() {
using handle = acquireFileHandle(); // block-scoped critical resource
} // cleanup
{
using obj = g(); // block-scoped declaration
const r = obj.next();
} // calls finally blocks in `g`
```
```js
// async disposal
async function * g() {
using stream = acquireStream(); // block-scoped critical resource
...
} // cleanup
{
await using obj = g(); // block-scoped declaration
const r = await obj.next();
} // calls finally blocks in `g`
```
In addition, we propose the addition of two disposable container objects to assist
with managing multiple resources:
- `DisposableStack` — A stack-based container of disposable resources.
- `AsyncDisposableStack` — A stack-based container of asynchronously disposable resources.
# Motivations
This proposal is motivated by a number of cases:
- Inconsistent patterns for resource management:
- ECMAScript Iterators: `iterator.return()`
- WHATWG Stream Readers: `reader.releaseLock()`
- NodeJS FileHandles: `handle.close()`
- Emscripten C++ objects handles: `Module._free(ptr) obj.delete() Module.destroy(obj)`
- Avoiding common footguns when managing resources:
```js
const reader = stream.getReader();
...
reader.releaseLock(); // Oops, should have been in a try/finally
```
- Scoping resources:
```js
const handle = ...;
try {
... // ok to use `handle`
}
finally {
handle.close();
}
// not ok to use `handle`, but still in scope
```
- Avoiding common footguns when managing multiple resources:
```js
const a = ...;
const b = ...;
try {
...
}
finally {
a.close(); // Oops, issue if `b.close()` depends on `a`.
b.close(); // Oops, `b` never reached if `a.close()` throws.
}
```
- Avoiding lengthy code when managing multiple resources correctly:
```js
// sync disposal
{ // block avoids leaking `a` or `b` to outer scope
const a = ...;
try {
const b = ...;
try {
...
}
finally {
b.close(); // ensure `b` is closed before `a` in case `b`
// depends on `a`
}
}
finally {
a.close(); // ensure `a` is closed even if `b.close()` throws
}
}
// both `a` and `b` are out of scope
```
Compared to:
```js
// avoids leaking `a` or `b` to outer scope
// ensures `b` is disposed before `a` in case `b` depends on `a`
// ensures `a` is disposed even if disposing `b` throws
using a = ..., b = ...;
...
```
```js
// async sync disposal
{ // block avoids leaking `a` or `b` to outer scope
const a = ...;
try {
const b = ...;
try {
...
}
finally {
await b.close(); // ensure `b` is closed before `a` in case `b`
// depends on `a`
}
}
finally {
await a.close(); // ensure `a` is closed even if `b.close()` throws
}
}
// both `a` and `b` are out of scope
```
Compared to:
```js
// avoids leaking `a` or `b` to outer scope
// ensures `b` is disposed before `a` in case `b` depends on `a`
// ensures `a` is disposed even if disposing `b` throws
await using a = ..., b = ...;
...
```
- Non-blocking memory/IO applications:
```js
import { ReaderWriterLock } from "...";
const lock = new ReaderWriterLock();
export async function readData() {
// wait for outstanding writer and take a read lock
using lockHandle = await lock.read();
... // any number of readers
await ...;
... // still in read lock after `await`
} // release the read lock
export async function writeData(data) {
// wait for all readers and take a write lock
using lockHandle = await lock.write();
... // only one writer
await ...;
... // still in write lock after `await`
} // release the write lock
```
- Potential for use with the [Fixed Layout Objects Proposal](https://github.com/tc39/proposal-structs) and
`shared struct`:
```js
// main.js
shared struct class SharedData {
ready = false;
processed = false;
}
const worker = new Worker('worker.js');
const m = new Atomics.Mutex();
const cv = new Atomics.ConditionVariable();
const data = new SharedData();
worker.postMessage({ m, cv, data });
// send data to worker
{
// wait until main can get a lock on 'm'
using lck = m.lock();
// mark data for worker
data.ready = true;
console.log("main is ready");
} // unlocks 'm'
// notify potentially waiting worker
cv.notifyOne();
{
// reacquire lock on 'm'
using lck = m.lock();
// release the lock on 'm' and wait for the worker to finish processing
cv.wait(m, () => data.processed);
} // unlocks 'm'
```
```js
// worker.js
onmessage = function (e) {
const { m, cv, data } = e.data;
{
// wait until worker can get a lock on 'm'
using lck = m.lock();
// release the lock on 'm' and wait until main() sends data
cv.wait(m, () => data.ready);
// after waiting we once again own the lock on 'm'
console.log("worker thread is processing data");
// send data back to main
data.processed = true;
console.log("worker thread is done");
} // unlocks 'm'
}
```
# Prior Art
- C#:
- [`using` statement](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement)
- [`using` declaration](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/using#using-declaration)
- Java: [`try`-with-resources statement](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)
- Python: [`with` statement](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement)
# Definitions
- _Resource_ — An object with a specific lifetime, at the end of which either a lifetime-sensitive operation
should be performed or a non-garbage-collected reference (such as a file handle, socket, etc.) should be closed or
freed.
- _Resource Management_ — A process whereby "resources" are released, triggering any lifetime-sensitive operations
or freeing any related non-garbage-collected references.
- _Implicit Resource Management_ — Indicates a system whereby the lifetime of a "resource" is managed implicitly
by the runtime as part of garbage collection, such as:
- `WeakMap` keys
- `WeakSet` values
- `WeakRef` values
- `FinalizationRegistry` entries
- _Explicit Resource Management_ — Indicates a system whereby the lifetime of a "resource" is managed explicitly
by the user either **imperatively** (by directly calling a method like `Symbol.dispose`) or **declaratively** (through
a block-scoped declaration like `using`).
# Syntax
## `using` Declarations
```js
// a synchronously-disposed, block-scoped resource
using x = expr1; // resource w/ local binding
using y = expr2, z = expr4; // multiple resources
```
# Grammar
Please refer to the [specification text][Specification] for the most recent version of the grammar.
## `await using` Declarations
```js
// an asynchronously-disposed, block-scoped resource
await using x = expr1; // resource w/ local binding
await using y = expr2, z = expr4; // multiple resources
```
An `await using` declaration can appear in the following contexts:
- The top level of a _Module_ anywhere _VariableStatement_ is allowed, as long as it is not immediately nested inside
of a _CaseClause_ or _DefaultClause_.
- In the body of an async function or async generator anywhere a _VariableStatement_ is allowed, as long as it is not
immediately nested inside of a _CaseClause_ or _DefaultClause_.
- In the head of a `for-of` or `for-await-of` statement.
## `await using` in `for-of` and `for-await-of` Statements
```js
for (await using x of y) ...
for await (await using x of y) ...
```
You can use an `await using` declaration in a `for-of` or `for-await-of` statement inside of an async context to
explicitly bind each iterated value as an async disposable resource. `for-await-of` does not implicitly make a non-async
`using` declaration into an async `await using` declaration, as the `await` markers in `for-await-of` and `await using`
are explicit indicators for distinct cases: `for await` *only* indicates async iteration, while `await using` *only*
indicates async disposal. For example:
```js
// sync iteration, sync disposal
for (using x of y) ; // no implicit `await` at end of each iteration
// sync iteration, async disposal
for (await using x of y) ; // implicit `await` at end of each iteration
// async iteration, sync disposal
for await (using x of y) ; // implicit `await` at end of each iteration
// async iteration, async disposal
for await (await using x of y) ; // implicit `await` at end of each iteration
```
While there is some overlap in that the last three cases introduce some form of implicit `await` during execution, it
is intended that the presence or absence of the `await` modifier in a `using` declaration is an explicit indicator as to
whether we are expecting the iterated value to have an `@@asyncDispose` method. This distinction is in line with the
behavior of `for-of` and `for-await-of`:
```js
const iter = { [Symbol.iterator]() { return [].values(); } };
const asyncIter = { [Symbol.asyncIterator]() { return [].values(); } };
for (const x of iter) ; // ok: `iter` has @@iterator
for (const x of asyncIter) ; // throws: `asyncIter` does not have @@iterator
for await (const x of iter) ; // ok: `iter` has @@iterator (fallback)
for await (const x of asyncIter) ; // ok: `asyncIter` has @@asyncIterator
```
`using` and `await using` have the same distinction:
```js
const res = { [Symbol.dispose]() {} };
const asyncRes = { [Symbol.asyncDispose]() {} };
using x = res; // ok: `res` has @@dispose
using x = asyncRes; // throws: `asyncRes` does not have @@dispose
await using x = res; // ok: `res` has @@dispose (fallback)
await using x = asyncres; // ok: `asyncRes` has @@asyncDispose
```
This results in a matrix of behaviors based on the presence of each `await` marker:
```js
const res = { [Symbol.dispose]() {} };
const asyncRes = { [Symbol.asyncDispose]() {} };
const iter = { [Symbol.iterator]() { return [res, asyncRes].values(); } };
const asyncIter = { [Symbol.asyncIterator]() { return [res, asyncRes].values(); } };
for (using x of iter) ;
// sync iteration, sync disposal
// - `iter` has @@iterator: ok
// - `res` has @@dispose: ok
// - `asyncRes` does not have @@dispose: *error*
for (using x of asyncIter) ;
// sync iteration, sync disposal
// - `asyncIter` does not have @@iterator: *error*
for (await using x of iter) ;
// sync iteration, async disposal
// - `iter` has @@iterator: ok
// - `res` has @@dispose (fallback): ok
// - `asyncRes` has @@asyncDispose: ok
for (await using x of asyncIter) ;
// sync iteration, async disposal
// - `asyncIter` does not have @@iterator: error
for await (using x of iter) ;
// async iteration, sync disposal
// - `iter` has @@iterator (fallback): ok
// - `res` has @@dispose: ok
// - `asyncRes` does not have @@dispose: error
for await (using x of asyncIter) ;
// async iteration, sync disposal
// - `asyncIter` has @@asyncIterator: ok
// - `res` has @@dispose: ok
// - `asyncRes` does not have @@dispose: error
for await (await using x of iter) ;
// async iteration, async disposal
// - `iter` has @@iterator (fallback): ok
// - `res` has @@dispose (fallback): ok
// - `asyncRes` does has @@asyncDispose: ok
for await (await using x of asyncIter) ;
// async iteration, async disposal
// - `asyncIter` has @@asyncIterator: ok
// - `res` has @@dispose (fallback): ok
// - `asyncRes` does has @@asyncDispose: ok
```
Or, in table form:
| Syntax | Iteration | Disposal |
|:---------------------------------|:------------------------------:|:----------------------------:|
| `for (using x of y)` | `@@iterator` | `@@dispose` |
| `for (await using x of y)` | `@@iterator` | `@@asyncDispose`/`@@dispose` |
| `for await (using x of y)` | `@@asyncIterator`/`@@iterator` | `@@dispose` |
| `for await (await using x of y)` | `@@asyncIterator`/`@@iterator` | `@@asyncDispose`/`@@dispose` |
# Semantics
## `using` Declarations
### `using` Declarations with Explicit Local Bindings
```grammarkdown
UsingDeclaration :
`using` BindingList `;`
LexicalBinding :
BindingIdentifier Initializer
```
When a `using` declaration is parsed with _BindingIdentifier_ _Initializer_, the bindings created in the declaration
are tracked for disposal at the end of the containing _Block_ or _Module_ (a `using` declaration cannot be used
at the top level of a _Script_):
```js
{
... // (1)
using x = expr1;
... // (2)
}
```
Internally, the TypeScript parser marks a `using` declaration list with the `NodeFlags.Using` flag (defined as `1 << 2`) and an `await using` declaration list with `NodeFlags.AwaitUsing`, defined as the combination `Const | Using`. Both are folded into the block-scoped and constant flag groups — `BlockScoped` is `Let | Const | Using` and `Constant` is `Const | Using` — so a `using` or `await using` binding is block-scoped and, like a `const`, immutable; reassigning one is an error.
The above example has similar runtime semantics as the following transposed representation:
```js
{
const $$try = { stack: [], error: undefined, hasError: false };
try {
... // (1)
const x = expr1;
if (x !== null && x !== undefined) {
const $$dispose = x[Symbol.dispose];
if (typeof $$dispose !== "function") {
throw new TypeError();
}
$$try.stack.push({ value: x, dispose: $$dispose });
}
... // (2)
}
catch ($$error) {
$$try.error = $$error;
$$try.hasError = true;
}
finally {
while ($$try.stack.length) {
const { value: $$expr, dispose: $$dispose } = $$try.stack.pop();
try {
$$dispose.call($$expr);
}
catch ($$error) {
$$try.error = $$try.hasError ? new SuppressedError($$error, $$try.error) : $$error;
$$try.hasError = true;
}
}
if ($$try.hasError) {
throw $$try.error;
}
}
}
```
If exceptions are thrown both in the block following the `using` declaration and in the call to
`[Symbol.dispose]()`, all exceptions are reported.
In the TypeScript compiler this transposition is not inlined at each declaration site as shown above. When a `using` declaration is downleveled for an output target that lacks native support, the transform routes the logic through two named runtime helpers, `__addDisposableResource` and `__disposeResources`. `__addDisposableResource(env, value, async)` records a single resource — resolving the value's `[Symbol.asyncDispose]` method when `async` is `true` (falling back to `[Symbol.dispose]`) and its `[Symbol.dispose]` method otherwise; a `using` declaration passes `async` as `false`, while an `await using` declaration passes it as `true`. `__disposeResources(env)` then disposes the recorded resources in reverse order when the block exits. When a disposer throws while another error is already pending, it combines them as `new SuppressedError(error, suppressed, "An error was suppressed during disposal.")`, using that exact string as the default message for a disposal-suppressed error, and rethrows once the remaining resources have been disposed.
### `using` Declarations with Multiple Resources
A `using` declaration can mix multiple explicit bindings in the same declaration:
```js
{
...
using x = expr1, y = expr2;
...
}
```
These bindings are again used to perform resource disposal when the _Block_ or _Module_ exits, however in this case
`[Symbol.dispose]()` is invoked in the reverse order of their declaration. This is _approximately_ equivalent to the
following:
```js
{
... // (1)
using x = expr1;
using y = expr2;
... // (2)
}
```
Both of the above cases would have similar runtime semantics as the following transposed representation:
```js
{
const $$try = { stack: [], error: undefined, hasError: false };
try {
... // (1)
const x = expr1;
if (x !== null && x !== undefined) {
const $$dispose = x[Symbol.dispose];
if (typeof $$dispose !== "function") {
throw new TypeError();
}
$$try.stack.push({ value: x, dispose: $$dispose });
}
const y = expr2;
if (y !== null && y !== undefined) {
const $$dispose = y[Symbol.dispose];
if (typeof $$dispose !== "function") {
throw new TypeError();
}
$$try.stack.push({ value: y, dispose: $$dispose });
}
... // (2)
}
catch ($$error) {
$$try.error = $$error;
$$try.hasError = true;
}
finally {
while ($$try.stack.length) {
const { value: $$expr, dispose: $$dispose } = $$try.stack.pop();
try {
$$dispose.call($$expr);
}
catch ($$error) {
$$try.error = $$try.hasError ? new SuppressedError($$error, $$try.error) : $$error;
$$try.hasError = true;
}
}
if ($$try.hasError) {
throw $$try.error;
}
}
}
```
Since we must always ensure that we properly release resources, we must ensure that any abrupt completion that might
occur during binding initialization results in evaluation of the cleanup step. When there are multiple declarations in
the list, we track each resource in the order they are declared. As a result, we must release these resources in reverse
order.
### `using` Declarations and `null` or `undefined` Values
This proposal has opted to ignore `null` and `undefined` values provided to the `using` declarations. This is similar to
the behavior of `using` in C#, which also allows `null`. One primary reason for this behavior is to simplify a common
case where a resource might be optional, without requiring duplication of work or needless allocations:
```js
if (isResourceAvailable()) {
using resource = getResource();
... // (1)
resource.doSomething()
... // (2)
}
else {
// duplicate code path above
... // (1) above
... // (2) above
}
```
Compared to:
```js
using resource = isResourceAvailable() ? getResource() : undefined;
... // (1) do some work with or without resource
resource?.doSomething();
... // (2) do some other work with or without resource
```
### `using` Declarations and Values Without `[Symbol.dispose]`
If a resource does not have a callable `[Symbol.dispose]` member, a `TypeError` would be thrown **immediately** when the
resource is tracked.
### `using` Declarations in `for-of` and `for-await-of` Loops
A `using` declaration _may_ occur in the _ForDeclaration_ of a `for-of` or `for-await-of` loop:
```js
for (using x of iterateResources()) {
// use x
}
```
In this case, the value bound to `x` in each iteration will be _synchronously_ disposed at the end of each iteration.
This will not dispose resources that are not iterated, such as if iteration is terminated early due to `return`,
`break`, or `throw`.
`using` declarations _may not_ be used in in the head of a `for-in` loop.
## `await using` Declarations
### `await using` Declarations with Explicit Local Bindings
```grammarkdown
UsingDeclaration :
`await` `using` BindingList `;`
LexicalBinding :
BindingIdentifier Initializer
```
When an `await using` declaration is parsed with _BindingIdentifier_ _Initializer_, the bindings created in the
declaration are tracked for disposal at the end of the containing async function body, _Block_, or _Module_:
```js
{
... // (1)
await using x = expr1;
... // (2)
}
```
The above example has similar runtime semantics as the following transposed representation:
```js
{
const $$try = { stack: [], error: undefined, hasError: false };
try {
... // (1)
const x = expr1;
if (x !== null && x !== undefined) {
let $$dispose = x[Symbol.asyncDispose];
if (typeof $$dispose !== "function") {
$$dispose = x[Symbol.dispose];
}
if (typeof $$dispose !== "function") {
throw new TypeError();
}
$$try.stack.push({ value: x, dispose: $$dispose });
}
... // (2)
}
catch ($$error) {
$$try.error = $$error;
$$try.hasError = true;
}
finally {
while ($$try.stack.length) {
const { value: $$expr, dispose: $$dispose } = $$try.stack.pop();
try {
await $$dispose.call($$expr);
}
catch ($$error) {
$$try.error = $$try.hasError ? new SuppressedError($$error, $$try.error) : $$error;
$$try.hasError = true;
}
}
if ($$try.hasError) {
throw $$try.error;
}
}
}
```
If exceptions are thrown both in the statements following the `await using` declaration and in the call to
`[Symbol.asyncDispose]()`, all exceptions are reported.
### `await using` Declarations with Multiple Resources
An `await using` declaration can mix multiple explicit bindings in the same declaration:
```js
{
...
await using x = expr1, y = expr2;
...
}
```
These bindings are again used to perform resource disposal when the _Block_ or _Module_ exits, however in this case each
resource's `[Symbol.asyncDispose]()` is invoked in the reverse order of their declaration. This is _approximately_
equivalent to the following:
```js
{
... // (1)
await using x = expr1;
await using y = expr2;
... // (2)
}
```
Both of the above cases would have similar runtime semantics as the following transposed representation:
```js
{
const $$try = { stack: [], error: undefined, hasError: false };
try {
... // (1)
const x = expr1;
if (x !== null && x !== undefined) {
let $$dispose = x[Symbol.asyncDispose];
if (typeof $$dispose !== "function") {
$$dispose = x[Symbol.dispose];
}
if (typeof $$dispose !== "function") {
throw new TypeError();
}
$$try.stack.push({ value: x, dispose: $$dispose });
}
const y = expr2;
if (y !== null && y !== undefined) {
let $$dispose = y[Symbol.asyncDispose];
if (typeof $$dispose !== "function") {
$$dispose = y[Symbol.dispose];
}
if (typeof $$dispose !== "function") {
throw new TypeError();
}
$$try.stack.push({ value: y, dispose: $$dispose });
}
... // (2)
}
catch ($$error) {
$$try.error = $$error;
$$try.hasError = true;
}
finally {
while ($$try.stack.length) {
const { value: $$expr, dispose: $$dispose } = $$try.stack.pop();
try {
await $$dispose.call($$expr);
}
catch ($$error) {
$$try.error = $$try.hasError ? new SuppressedError($$error, $$try.error) : $$error;
$$try.hasError = true;
}
}
if ($$try.hasError) {
throw $$try.error;
}
}
}
```
Since we must always ensure that we properly release resources, we must ensure that any abrupt completion that might
occur during binding initialization results in evaluation of the cleanup step. When there are multiple declarations in
the list, we track each resource in the order they are declared. As a result, we must release these resources in reverse
order.
### `await using` Declarations and `null` or `undefined` Values
This proposal has opted to ignore `null` and `undefined` values provided to `await using` declarations. This is
consistent with the proposed behavior for the `using` declarations in this proposal. Like in the sync case, this allows
simplifying a common case where a resource might be optional, without requiring duplication of work or needless
allocations:
```js
if (isResourceAvailable()) {
await using resource = getResource();
... // (1)
resource.doSomething()
... // (2)
}
else {
// duplicate code path above
... // (1) above
... // (2) above
}
```
Compared to:
```js
await using resource = isResourceAvailable() ? getResource() : undefined;
... // (1) do some work with or without resource
resource?.doSomething();
... // (2) do some other work with or without resource
```
### `await using` Declarations and Values Without `[Symbol.asyncDispose]` or `[Symbol.dispose]`
If a resource does not have a callable `[Symbol.asyncDispose]` or `[Symbol.asyncDispose]` member, a `TypeError` would be thrown **immediately** when the resource is tracked.
### `await using` Declarations in `for-of` and `for-await-of` Loops
An `await using` declaration _may_ occur in the _ForDeclaration_ of a `for-await-of` loop:
```js
for await (await using x of iterateResources()) {
// use x
}
```
In this case, the value bound to `x` in each iteration will be _asynchronously_ disposed at the end of each iteration.
This will not dispose resources that are not iterated, such as if iteration is terminated early due to `return`,
`break`, or `throw`.
`await using` declarations _may not_ be used in in the head of a `for-of` or `for-in` loop.
### Implicit Async Interleaving Points ("implicit `await`")
The `await using` syntax introduces an implicit async interleaving point (i.e., an implicit `await`) whenever control
flow exits an async function body, _Block_, or _Module_ containing an `await using` declaration. This means that two
statements that currently execute in the same microtask, such as:
```js
async function f() {
{
a();
} // exit block
b(); // same microtask as call to `a()`
}
```
will instead execute in different microtasks if an `await using` declaration is introduced:
```js
async function f() {
{
await using x = ...;
a();
} // exit block, implicit `await`
b(); // different microtask from call to `a()`.
}
```
It is important that such an implicit interleaving point be adequately indicated within the syntax. We believe that
the presence of `await using` within such a block is an adequate indicator, since it should be fairly easy to recognize
a _Block_ containing an `await using` statement in well-formatted code.
It is also feasible for editors to use features such as syntax highlighting, editor decorations, and inlay hints to
further highlight such transitions, without needing to specify additional syntax.
Further discussion around the `await using` syntax and how it pertains to implicit async interleaving points can be
found in [#1](https://github.com/tc39/proposal-async-explicit-resource-management/issues/1).
# Examples
The following show examples of using this proposal with various APIs, assuming those APIs adopted this proposal.
### WHATWG Streams API
```js
{
using reader = stream.getReader();
const { value, done } = reader.read();
} // 'reader' is disposed
```
### NodeJS FileHandle
```js
{
using f1 = await fs.promises.open(s1, constants.O_RDONLY),
f2 = await fs.promises.open(s2, constants.O_WRONLY);
const buffer = Buffer.alloc(4092);
const { bytesRead } = await f1.read(buffer);
await f2.write(buffer, 0, bytesRead);
} // 'f2' is disposed, then 'f1' is disposed
```
### NodeJS Streams
```js
{
await using writable = ...;
writable.write(...);
} // 'writable.end()' is called and its result is awaited
```
### Logging and tracing
```js
// audit privileged function call entry and exit
function privilegedActivity() {
using activity = auditLog.startActivity("privilegedActivity"); // log activity start
...
} // log activity end
```
### Async Coordination
```js
import { Semaphore } from "...";
const sem = new Semaphore(1); // allow one participant at a time
export async function tryUpdate(record) {
using lck = await sem.wait(); // asynchronously block until we are the sole participant
...
} // synchronously release semaphore and notify the next participant
```
### Three-Phase Commit Transactions
```js
// roll back transaction if either action fails
async function transfer(account1, account2) {
await using tx = transactionManager.startTransaction(account1, account2);
await account1.debit(amount);
await account2.credit(amount);
// mark transaction success if we reach this point
tx.succeeded = true;
} // await transaction commit or rollback
```
### Shared Structs
**main_thread.js**
```js
// main_thread.js
shared struct Data {
mut;
cv;
ready = 0;
processed = 0;
// ...
}
const data = Data();
data.mut = Atomics.Mutex();
data.cv = Atomics.ConditionVariable();
// start two workers
startWorker1(data);
startWorker2(data);
```
**worker1.js**
```js
const data = ...;
const { mut, cv } = data;
{
// lock mutex
using lck = Atomics.Mutex.lock(mut);
// NOTE: at this point we currently own the lock
// load content into data and signal we're ready
// ...
Atomics.store(data, "ready", 1);
} // release mutex
// NOTE: at this point we no longer own the lock
// notify worker 2 that it should wake
Atomics.ConditionVariable.notifyOne(cv);
{
// reacquire lock on mutex
using lck = Atomics.Mutex.lock(mut);
// NOTE: at this point we currently own the lock
// release mutex and wait until condition is met to reacquire it
Atomics.ConditionVariable.wait(mut, () => Atomics.load(data, "processed") === 1);
// NOTE: at this point we currently own the lock
// Do something with the processed data
// ...
} // release mutex
// NOTE: at this point we no longer own the lock
```
**worker2.js**
```js
const data = ...;
const { mut, cv } = data;
{
// lock mutex
using lck = Atomics.Mutex.lock(mut);
// NOTE: at this point we currently own the lock
// release mutex and wait until condition is met to reacquire it
Atomics.ConditionVariable.wait(mut, () => Atomics.load(data, "ready") === 1);
// NOTE: at this point we currently own the lock
// read in values from data, perform our processing, then indicate we are done
// ...
Atomics.store(data, "processed", 1);
} // release mutex
// NOTE: at this point we no longer own the lock
```
# API
## Additions to `Symbol`
This proposal adds the `dispose` and `asyncDispose` properties to the `Symbol` constructor, whose values are the
`@@dispose` and `@@asyncDispose` internal symbols:
**Well-known Symbols**
| Specification Name | \[\[Description]] | Value and Purpose |
|:-|:-|:-|
| _@@dispose_ | *"Symbol.dispose"* | A method that explicitly disposes of resources held by the object. Called by the semantics of `using` declarations and by `DisposableStack` objects. |
| _@@asyncDispose_ | *"Symbol.asyncDispose"* | A method that asynchronosly explicitly disposes of resources held by the object. Called by the semantics of `await using` declarations and by `AsyncDisposableStack` objects. |
**TypeScript Definition**
```ts
interface SymbolConstructor {
readonly asyncDispose: unique symbol;
readonly dispose: unique symbol;
}
```
## The `SuppressedError` Error
If an exception occurs during resource disposal, it is possible that it might suppress an existing exception thrown
from the body, or from the disposal of another resource. Languages like Java allow you to access a suppressed exception
via a [`getSuppressed()`](https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#getSuppressed()) method on
the exception. However, ECMAScript allows you to throw any value, not just `Error`, so there is no convenient place to
attach a suppressed exception. To better surface these suppressed exceptions and support both logging and error
recovery, this proposal seeks to introduce a new `SuppressedError` built-in `Error` subclass which would contain both
the error that was most recently thrown, as well as the error that was suppressed:
```js
class SuppressedError extends Error {
/**
* Wraps an error that suppresses another error, and the error that was suppressed.
* @param {*} error The error that resulted in a suppression.
* @param {*} suppressed The error that was suppressed.
* @param {string} message The message for the error.
* @param {{ cause?: * }} [options] Options for the error.
*/
constructor(error, suppressed, message, options);
/**
* The name of the error (i.e., `"SuppressedError"`).
* @type {string}
*/
name = "SuppressedError";
/**
* The error that resulted in a suppression.
* @type {*}
*/
error;
/**
* The error that was suppressed.
* @type {*}
*/
suppressed;
/**
* The message for the error.
* @type {*}
*/
message;
}
```
We've chosen to use `SuppressedError` over `AggregateError` for several reasons:
- `AggregateError` is designed to hold a list of multiple errors, with no correlation between those errors, while
`SuppressedError` is intended to hold references to two errors with a direct correlation.
- `AggregateError` is intended to ideally hold a flat list of errors. `SuppressedError` is intended to hold a jagged set
of errors (i.e., `e.suppressed.suppressed.suppressed` if there were successive error suppressions).
- The only error correlation on `AggregateError` is through `cause`, however a `SuppressedError` isn't "caused" by the
error it suppresses. In addition, `cause` is intended to be optional, while the `error` of a `SuppressedError` must
always be defined.
## Built-in Disposables
### `%IteratorPrototype%.@@dispose()`
We also propose to add `Symbol.dispose` to the built-in `%IteratorPrototype%` as if it had the following behavior:
```js
%IteratorPrototype%[Symbol.dispose] = function () {
this.return();
}
```
### `%AsyncIteratorPrototype%.@@asyncDispose()`
We propose to add `Symbol.asyncDispose` to the built-in `%AsyncIteratorPrototype%` as if it had the following behavior:
```js
%AsyncIteratorPrototype%[Symbol.asyncDispose] = async function () {
await this.return();
}
```
### Other Possibilities
We could also consider adding `Symbol.dispose` to such objects as the return value from `Proxy.revocable()`, but that
is currently out of scope for the current proposal.
## The Common `Disposable` and `AsyncDisposable` Interfaces
### The `Disposable` Interface
An object is _disposable_ if it conforms to the following interface:
| Property | Value | Requirements |
|:-|:-|:-|
| `@@dispose` | A function that performs explicit cleanup. | The function should return `undefined`. |
**TypeScript Definition**
```ts
interface Disposable {
/**
* Disposes of resources within this object.
*/
[Symbol.dispose](): void;
}
```
### The `AsyncDisposable` Interface
An object is _async disposable_ if it conforms to the following interface:
| Property | Value | Requirements |
|:-|:-|:-|
| `@@asyncDispose` | An async function that performs explicit cleanup. | The function should return a `Promise`. |
**TypeScript Definition**
```ts
interface AsyncDisposable {
/**
* Disposes of resources within this object.
*/
[Symbol.asyncDispose](): Promise<void>;
}
```
## The `DisposableStack` and `AsyncDisposableStack` container objects
This proposal adds two global objects that can act as containers to aggregate disposables, guaranteeing that every
disposable resource in the container is disposed when the respective disposal method is called. If any disposable in the
container throws an error during dispose, it would be thrown at the end (possibly wrapped in a `SuppressedError` if
multiple errors were thrown):
```js
class DisposableStack {
constructor();
/**
* Gets a value indicating whether the stack has been disposed.
* @returns {boolean}
*/
get disposed();
/**
* Alias for `[Symbol.dispose]()`.
*/
dispose();
/**
* Adds a resource to the top of the stack. Has no effect if provided `null` or `undefined`.
* @template {Disposable | null | undefined} T
* @param {T} value - A `Disposable` object, `null`, or `undefined`.
* @returns {T} The provided value.
*/
use(value);
/**
* Adds a non-disposable resource and a disposal callback to the top of the stack.
* @template T
* @param {T} value - A resource to be disposed.
* @param {(value: T) => void} onDispose - A callback invoked to dispose the provided value.
* @returns {T} The provided value.
*/
adopt(value, onDispose);
/**
* Adds a disposal callback to the top of the stack.
* @param {() => void} onDispose - A callback to evaluate when this object is disposed.
* @returns {void}
*/
defer(onDispose);
/**
* Moves all resources currently in this stack into a new `DisposableStack`.
* @returns {DisposableStack} The new `DisposableStack`.
*/
move();
/**
* Disposes of resources within this object.
* @returns {void}
*/
[Symbol.dispose]();
[Symbol.toStringTag];
}
```
`AsyncDisposableStack` is the async version of `DisposableStack` and is a container used to aggregate async disposables,
guaranteeing that every disposable resource in the container is disposed when the respective disposal method is called.
If any disposable in the container throws an error during dispose, or results in a rejected `Promise`, it would be
thrown at the end (possibly wrapped in a `SuppressedError` if multiple errors were thrown):
These classes provided the following capabilities:
- Aggregation
- Interoperation and customization
- Assist in complex construction
> **NOTE:** `DisposableStack` is inspired by Python's
> [`ExitStack`](https://docs.python.org/3/library/contextlib.html#contextlib.ExitStack).
> **NOTE:** `AsyncDisposableStack` is inspired by Python's
> [`AsyncExitStack`](https://docs.python.org/3/library/contextlib.html#contextlib.AsyncExitStack).
### Aggregation
The `DisposableStack` and `AsyncDisposableStack` classes provid the ability to aggregate multiple disposable resources
into a single container. When the `DisposableStack` container is disposed, each object in the container is also
guaranteed to be disposed (barring early termination of the program). If any resource throws an error during dispose,
it will be collected and rethrown after all resources are disposed. If there were multiple errors, they will be wrapped
in nested `SuppressedError` objects.
For example:
```js
// sync
const stack = new DisposableStack();
const resource1 = stack.use(getResource1());
const resource2 = stack.use(getResource2());
const resource3 = stack.use(getResource3());
stack[Symbol.dispose](); // disposes of resource3, then resource2, then resource1
```
```js
// async
const stack = new AsyncDisposableStack();
const resource1 = stack.use(getResource1());
const resource2 = stack.use(getResource2());
const resource3 = stack.use(getResource3());
await stack[Symbol.asyncDispose](); // dispose and await disposal result of resource3, then resource2, then resource1
```
If all of `resource1`, `resource2` and `resource3` were to throw during disposal, this would produce an exception
similar to the following:
```js
new SuppressedError(
/*error*/ exception_from_resource3_disposal,
/*suppressed*/ new SuppressedError(
/*error*/ exception_from_resource2_disposal,
/*suppressed*/ exception_from_resource1_disposal
)
)
```
### Interoperation and Customization
The `DisposableStack` and `AsyncDisposableStack` classes also provide the ability to create a disposable resource from a
simple callback. This callback will be executed when the stack's disposal method is executed.
The ability to create a disposable resource from a callback has several benefits:
- It allows developers to leverage `using`/`await using` while working with existing resources that do not conform to the
`Symbol.dispose`/`Symbol.asyncDispose` mechanic:
```js
{
using stack = new DisposableStack();
const reader = stack.adopt(createReader(), reader => reader.releaseLock());
...
}
```
- It grants user the ability to schedule other cleanup work to evaluate at the end of the block similar to Go's
`defer` statement:
```js
function f() {
using stack = new DisposableStack();
console.log("enter");
stack.defer(() => console.log("exit"));
...
}
```
### Assist in Complex Construction
A user-defined disposable class might need to allocate and track multiple nested resources that should be disposed when
the class instance is disposed. However, properly managing the lifetime of these nested resources in the class
constructor can sometimes be difficult. The `move` method of `DisposableStack`/`AsyncDisposableStack` helps to more
easily manage lifetime in these scenarios:
```js
// sync
class PluginHost {
#disposed = false;
#disposables;
#channel;
#socket;
constructor() {
// Create a DisposableStack that is disposed when the constructor exits.
// If construction succeeds, we move everything out of `stack` and into
// `#disposables` to be disposed later.
using stack = new DisposableStack();
// Create an IPC adapter around process.send/process.on("message").
// When disposed, it unsubscribes from process.on("message").
this.#channel = stack.use(new NodeProcessIpcChannelAdapter(process));
// Create a pseudo-websocket that sends and receives messages over
// a NodeJS IPC channel.
this.#socket = stack.use(new NodePluginHostIpcSocket(this.#channel));
// If we made it here, then there were no errors during construction and
// we can safely move the disposables out of `stack` and into `#disposables`.
this.#disposables = stack.move();
// If construction failed, then `stack` would be disposed before reaching
// the line above. Event handlers would be removed, allowing `#channel` and
// `#socket` to be GC'd.
}
loadPlugin(file) {
// A disposable should try to ensure access is consistent with its "disposed" state, though this isn't strictly
// necessary since some disposables could be reusable (i.e., a Connection with an `open()` method, etc.).
if (this.#disposed) throw new ReferenceError("Object is disposed.");
// ...
}
[Symbol.dispose]() {
if (!this.#disposed) {
this.#disposed = true;
const disposables = this.#disposables;
// NOTE: we can free `#socket` and `#channel` here since they will be disposed by the call to
// `disposables[Symbol.dispose]()`, below. This isn't strictly a requirement for every Disposable, but is
// good housekeeping since these objects will no longer be useable.
this.#socket = undefined;
this.#channel = undefined;
this.#disposables = undefined;
// Dispose all resources in `disposables`
disposables[Symbol.dispose]();
}
}
}
```
```js
// async
const privateConstructorSentinel = {};
class AsyncPluginHost {
#disposed = false;
#disposables;
#channel;
#socket;
/** @private */
constructor(arg) {
if (arg !== privateConstructorSentinel) throw new TypeError("Use AsyncPluginHost.create() instead");
}
// NOTE: there's no such thing as an async constructor
static async create() {
const host = new AsyncPluginHost(privateConstructorSentinel);
// Create an AsyncDisposableStack that is disposed when the constructor exits.
// If construction succeeds, we move everything out of `stack` and into
// `#disposables` to be disposed later.
await using stack = new AsyncDisposableStack();
// Create an IPC adapter around process.send/process.on("message").
// When disposed, it unsubscribes from process.on("message").
host.#channel = stack.use(new NodeProcessIpcChannelAdapter(process));
// Create a pseudo-websocket that sends and receives messages over
// a NodeJS IPC channel.
host.#socket = stack.use(new NodePluginHostIpcSocket(host.#channel));
// If we made it here, then there were no errors during construction and
// we can safely move the disposables out of `stack` and into `#disposables`.
host.#disposables = stack.move();
// If construction failed, then `stack` would be asynchronously disposed before reaching
// the line above. Event handlers would be removed, allowing `#channel` and
// `#socket` to be GC'd.
return host;
}
loadPlugin(file) {
// A disposable should try to ensure access is consistent with its "disposed" state, though this isn't strictly
// necessary since some disposables could be reusable (i.e., a Connection with an `open()` method, etc.).
if (this.#disposed) throw new ReferenceError("Object is disposed.");
// ...
}
async [Symbol.asyncDispose]() {
if (!this.#disposed) {
this.#disposed = true;
const disposables = this.#disposables;
// NOTE: we can free `#socket` and `#channel` here since they will be disposed by the call to
// `disposables[Symbol.asyncDispose]()`, below. This isn't strictly a requirement for every disposable, but is
// good housekeeping since these objects will no longer be useable.
this.#socket = undefined;
this.#channel = undefined;
this.#disposables = undefined;
// Dispose all resources in `disposables`
await disposables[Symbol.asyncDispose]();
}
}
}
```
### Subclassing `Disposable` Classes
You can also use a `DisposableStack` to assist with disposal in a subclass constructor whose superclass is disposable:
```js
class DerivedPluginHost extends PluginHost {
constructor() {
super();
// Create a DisposableStack to cover the subclass constructor.
using stack = new DisposableStack();
// Defer a callback to dispose resources on the superclass. We use `defer` so that we can invoke the version of
// `[Symbol.dispose]` on the superclass and not on this or any subclasses.
stack.defer(() => super[Symbol.dispose]());
// If any operations throw during subclass construction, the instance will still be disposed, and superclass
// resources will be freed
doSomethingThatCouldPotentiallyThrow();
// As the last step before exiting, empty out the DisposableStack so that we don't dispose ourselves.
stack.move();
}
}
```
Here, we can use `stack` to track the result of `super()` (i.e., the `this` value). If any exception occurs during
subclass construction, we can ensure that `[Symbol.dispose]()` is called, freeing resources. If the subclass also needs
to track its own disposable resources, this example is modified slightly:
```js
class DerivedPluginHostWithOwnDisposables extends PluginHost {
#logger;
#disposables;
constructor() {
super()
// Create a DisposableStack to cover the subclass constructor.
using stack = new DisposableStack();
// Defer a callback to dispose resources on the superclass. We use `defer` so that we can invoke the version of
// `[Symbol.dispose]` on the superclass and not on this or any subclasses.
stack.defer(() => super[Symbol.dispose]());
// Create a logger that uses the file system and add it to our own disposables.
this.#logger = stack.use(new FileLogger());
// If any operations throw during subclass construction, the instance will still be disposed, and superclass
// resources will be freed
doSomethingThatCouldPotentiallyThrow();
// Persist our own disposables. If construction fails prior to the call to `stack.move()`, our own disposables
// will be disposed before they are set, and then the superclass `[Symbol.dispose]` will be invoked.
this.#disposables = stack.move();
}
[Symbol.dispose]() {
this.#logger = undefined;
// Dispose of our resources and those of our superclass. We do not need to invoke `super[Symbol.dispose]()` since
// that is already tracked by the `stack.defer` call in the constructor.
this.#disposables[Symbol.dispose]();
}
}
```
In this example, we can simply add new resources to the `stack` and move its contents into the subclass instance's
`this.#disposables`. In the subclass `[Symbol.dispose]()` method we don't need to call `super[Symbol.dispose]()` since
that has already been tracked by the `stack.defer` call in the constructor.
# Relation to `Iterator` and `for..of`
Iterators in ECMAScript also employ a "cleanup" step by way of supplying a `return` method. This means that there is
some similarity between a `using` declaration and a `for..of` statement:
```js
// using
function f() {
using x = ...;
// use x
} // x is disposed
// for..of
function makeDisposableScope() {
const resources = [];
let state = 0;
return {
next() {
switch (state) {
case 0:
state++;
return {
done: false,
value: {
use(value) {
resources.unshift(value);
return value;
}
}
};
case 1:
state++;
for (const value of resources) {
value?.[Symbol.dispose]();
}
default:
state = -1;
return { done: true };
}
},
return() {
switch (state) {
case 1:
state++;
for (const value of resources) {
value?.[Symbol.dispose]();
}
default:
state = -1;
return { done: true };
}
},
[Symbol.iterator]() { return this; }
}
}
function f() {
for (const { use } of makeDisposableScope()) {
const x = use(...);
// use x
} // x is disposed
}
```
However there are a number drawbacks to using `for..of` as an alternative:
- Exceptions in the body are swallowed by exceptions from disposables.
- `for..of` implies iteration, which can be confusing when reading code.
- Conflating `for..of` and resource management could make it harder to find documentation, examples, StackOverflow
answers, etc.
- A `for..of` implementation like the one above cannot control the scope of `use`, which can make lifetimes confusing:
```js
for (const { use } of ...) {
const x = use(...); // ok
setImmediate(() => {
const y = use(...); // wrong lifetime
});
}
```
- Significantly more boilerplate compared to `using`.
- Mandates introduction of a new block scope, even at the top level of a function body.
- Control flow analysis of a `for..of` loop cannot infer definite assignment since a loop could potentially have zero
elements:
```js
// using
function f1() {
/** @type {string | undefined} */
let x;
{
using y = ...;
x = y.text;
}
x.toString(); // x is definitely assigned
}
// for..of
function f2() {
/** @type {string | undefined} */
let x;
for (const { use } of ...) {
const y = use(...);
x = y.text;
}
x.toString(); // possibly an error in a static analyzer since `x` is not guaranteed to have been assigned.
}
```
- Using `continue` and `break` is more difficult if you need to dispose of an iterated value:
```js
// using
for (using x of iterable) {
if (!x.ready) continue;
if (x.done) break;
...
}
// for..of
outer: for (const x of iterable) {
for (const { use } of ...) {
use(x);
if (!x.ready) continue outer;
if (!x.done) break outer;
...
}
}
```
# Relation to DOM APIs
This proposal does not necessarily require immediate support in the HTML DOM specification, as existing APIs can still
be adapted by using `DisposableStack` or `AsyncDisposableStack`. However, there are a number of APIs that could benefit
from this proposal and should be considered by the relevant standards bodies. The following is by no means a complete
list, and primarily offers suggestions for consideration. The actual implementation is at the discretion of the relevant
standards bodies.
- `AudioContext` — `@@asyncDispose()` as an alias or [wrapper][] for `close()`.
- NOTE: `close()` here is asynchronous, but uses the same name as similar synchronous methods on other objects.
- `BroadcastChannel` — `@@dispose()` as an alias or [wrapper][] for `close()`.
- `EventSource` — `@@dispose()` as an alias or [wrapper][] for `close()`.
- `FileReader` — `@@dispose()` as an alias or [wrapper][] for `abort()`.
- `IDbTransaction` — `@@dispose()` could invoke `abort()` if the transaction is still in the active state:
```js
{
using tx = db.transaction(storeNames);
// ...
if (...) throw new Error();
// ...
tx.commit();
} // implicit tx.abort() if we don't reach the explicit tx.commit()
```
- `ImageBitmap` — `@@dispose()` as an alias or [wrapper][] for `close()`.
- `IntersectionObserver` — `@@dispose()` as an alias or [wrapper][] for `disconnect()`.
- `MediaKeySession` — `@@asyncDispose()` as an alias or [wrapper][] for `close()`.
- NOTE: `close()` here is asynchronous, but uses the same name as similar synchronous methods on other objects.
- `MessagePort` — `@@dispose()` as an alias or [wrapper][] for `close()`.
- `MutationObserver` — `@@dispose()` as an alias or [wrapper][] for `disconnect()`.
- `PaymentRequest` — `@@asyncDispose()` could invoke `abort()` if the payment is still in the active state.
- NOTE: `abort()` here is asynchronous, but uses the same name as similar synchronous methods on other objects.
- `PerformanceObserver` — `@@dispose()` as an alias or [wrapper][] for `disconnect()`.
- `PushSubscription` — `@@asyncDispose()` as an alias or [wrapper][] for `unsubscribe()`.
- `ReadableStream` — `@@asyncDispose()` as an alias or [wrapper][] for `cancel()`.
- `ReadableStreamDefaultReader` — Either `@@dispose()` as an alias or [wrapper][] for `releaseLock()`, or
`@@asyncDispose()` as a [wrapper][] for `cancel()` (but probably not both).
- `RTCPeerConnection` — `@@dispose()` as an alias or [wrapper][] for `close()`.
- `RTCRtpTransceiver` — `@@dispose()` as an alias or [wrapper][] for `stop()`.
- `ReadableStreamDefaultController` — `@@dispose()` as an alias or [wrapper][] for `close()`.
- `ReadableStreamDefaultReader` — Either `@@dispose()` as an alias or [wrapper][] for `releaseLock()`, or
- `ResizeObserver` — `@@dispose()` as an alias or [wrapper][] for `disconnect()`.
- `ServiceWorkerRegistration` — `@@asyncDispose()` as a [wrapper][] for `unregister()`.
- `SourceBuffer` — `@@dispose()` as a [wrapper][] for `abort()`.
- `TransformStreamDefaultController` — `@@dispose()` as an alias or [wrapper][] for `terminate()`.
- `WebSocket` — `@@dispose()` as a [wrapper][] for `close()`.
- `Worker` — `@@dispose()` as an alias or [wrapper][] for `terminate()`.
- `WritableStream` — `@@asyncDispose()` as an alias or [wrapper][] for `close()`.
- NOTE: `close()` here is asynchronous, but uses the same name as similar synchronous methods on other objects.
- `WritableStreamDefaultWriter` — Either `@@dispose()` as an alias or [wrapper][] for `releaseLock()`, or
`@@asyncDispose()` as a [wrapper][] for `close()` (but probably not both).
- `XMLHttpRequest` — `@@dispose()` as an alias or [wrapper][] for `abort()`.
In addition, several new APIs could be considered that leverage this functionality:
- `EventTarget.prototype.addEventListener(type, listener, { subscription: true }) -> Disposable` — An option
passed to `addEventListener` could
return a `Disposable` that removes the event listener when disposed.
- `Performance.prototype.measureBlock(measureName, options) -> Disposable` — Combines `mark` and `measure` into a
block-scoped disposable:
```js
function f() {
using measure = performance.measureBlock("f"); // marks on entry
// ...
} // marks and measures on exit
```
- `SVGSVGElement` — A new method producing a [single-use disposer][] for `pauseAnimations()` and `unpauseAnimations()`.
- `ScreenOrientation` — A new method producing a [single-use disposer][] for `lock()` and `unlock()`.
### Definitions
A _wrapper for `x()`_ is a method that invokes `x()`, but only if the object is in a state
such that calling `x()` will not throw as a result of repeated evaluation.
A _callback-adapting wrapper_ is a _wrapper_ that adapts a continuation passing-style method
that accepts a callback into a `Promise`-producing method.
A _single-use disposer for `x()` and `y()`_ indicates a newly constructed disposable object
that invokes `x()` when constructed and `y()` when disposed the first time (and does nothing if the object is disposed
more than once).
# Relation to NodeJS APIs
This proposal does not necessarily require immediate support in NodeJS, as existing APIs can still be adapted by using
`DisposableStack` or `AsyncDisposableStack`. However, there are a number of APIs that could benefit from this proposal
and should be considered by the NodeJS maintainers. The following is by no means a complete list, and primarily offers
suggestions for consideration. The actual implementation is at the discretion of the NodeJS maintainers.
- Anything with `ref()` and `unref()` methods — A new method or API that produces a [single-use disposer][] for
`ref()` and `unref()`.
- Anything with `cork()` and `uncork()` methods — A new method or API that produces a [single-use disposer][] for
`cork()` and `uncork()`.
- `async_hooks.AsyncHook` — either `@@dispose()` as an alias or [wrapper][] for `disable()`, or a new method that
produces a [single-use disposer][] for `enable()` and `disable()`.
- `child_process.ChildProcess` — `@@dispose()` as an alias or [wrapper][] for `kill()`.
- `cluster.Worker` — `@@dispose()` as an alias or [wrapper][] for `kill()`.
- `crypto.Cipher`, `crypto.Decipher` — `@@dispose()` as a [wrapper][] for `final()`.
- `crypto.Hash`, `crypto.Hmac` — `@@dispose()` as a [wrapper][] for `digest()`.
- `dns.Resolver`, `dnsPromises.Resolver` — `@@dispose()` as an alias or [wrapper][] for `cancel()`.
- `domain.Domain` — A new method or API that produces a [single-use disposer][] for `enter()` and `exit()`.
- `events.EventEmitter` — A new method or API that produces a [single-use disposer][] for `on()` and `off()`.
- `fs.promises.FileHandle` — `@@asyncDispose()` as an alias or [wrapper][] for `close()`.
- `fs.Dir` — `@@asyncDispose()` as an alias or [wrapper][] for `close()`, `@@dispose()` as an alias or [wrapper][]
for `closeSync()`.
- `fs.FSWatcher` — `@@dispose()` as an alias or [wrapper][] for `close()`.
- `http.Agent` — `@@dispose()` as an alias or [wrapper][] for `destroy()`.
- `http.ClientRequest` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()`.
- `http.Server` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`.
- `http.ServerResponse` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `end()`.
- `http.IncomingMessage` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()`.
- `http.OutgoingMessage` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()`.
- `http2.Http2Session` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`.
- `http2.Http2Stream` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`.
- `http2.Http2Server` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`.
- `http2.Http2SecureServer` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`.
- `http2.Http2ServerRequest` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for
`destroy()`.
- `http2.Http2ServerResponse` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `end()`.
- `https.Server` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`.
- `inspector` — A new API that produces a [single-use disposer][] for `open()` and `close()`.
- `stream.Writable` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()` or
`@@asyncDispose` only as a [callback-adapting wrapper][] for `end()` (depending on whether the disposal behavior
should be to drop immediately or to flush any pending writes).
- `stream.Readable` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()`.
- ... and many others in `net`, `readline`, `tls`, `udp`, and `worker_threads`.
## Linked Issue #1 — Async using syntax
I've seen different syntax suggestions related to async disposal spread over different issues, in particular tc39/proposal-explicit-resource-management#16 tc39/proposal-explicit-resource-management#76 tc39/proposal-explicit-resource-management#84 tc39/proposal-async-explicit-resource-management#4. I wanted to concentrate the discussion in a single issue.
I'd first like to discuss the ongoing assumption that `using` an async-disposable requires specific syntax.
The way I model the `using` syntax is that a block containing a `using` declaration implicitly creates a `DisposableStack`. Every `using` declaration implicitly results in a `.use()` on the stack, and that exiting the block implicitly calls `[Symbol.dispose]()` on the stack.
Now if we assume that we have a concept of "async blocks", instead of a `DisposableStack` being implicitly created, it'd be an `AsyncDisposableStack`. At that point any `using` declaration would similarly call the `.use()` of the implicit async disposable stack, which is a synchronous operation, and it's the exit of the "async block" which awaits the `[Symbol.asyncDispose]()` call.
As such I would be against any syntax that uses the `await` keyword for the `using` declaration, as nothing is awaited at the declaration time. Similarly I would be against any syntax that doesn't use the `await` keyword on the block as a marker of interleaving. I would be ok with a `async using` declaration to be explicit, but I would consider that unnecessary verbosity.
Given the mental model above, I believe it would be entirely natural that `for await (using r of ...)`, and `using` declarations inside `for-await-of` blocks in general, would implicitly use an `AsyncDisposableStack`. `for-await-of` is conceptually the only "async block" in the language at the moment. Then it become a matter of specifying what the syntax of an "async block" not tied to iteration looks like.
*Source: https://github.com/tc39/proposal-async-explicit-resource-management/issues/1*
|