diff --git a/scripts/tsc_differential.py b/scripts/tsc_differential.py
new file mode 100644
index 000000000..07a6129e4
--- /dev/null
+++ b/scripts/tsc_differential.py
@@ -0,0 +1,247 @@
+#!/usr/bin/env python3
+"""Differential run: execute TypeScript files with tslang (JIT) and with Node, compare the output.
+
+The tsc sweep (scripts/tsc_compiler_tests.ps1) only checks that a file compiles. This script runs
+each file and compares stdout and the exit status with Node running the same file, transpiled by
+`tsc --noCheck` (TypeScript 7 CLI, no type checking).
+
+Two sources:
+ --sweep
results.csv of a tsc sweep: its passing single-file tests are run
+ (test files are read from --tests-dir)
+ --corpus a folder of .ts files (e.g. tslang/test/tester/tests); Node gets a prelude
+ with `print` and `assert`, and `main()` is called when the file defines it
+
+Results in --out: results.csv, summary.md, diffs/.txt (both outputs of each mismatch).
+
+Categories:
+ match same stdout, both exited 0 (also: both threw, same stdout before)
+ match-silent match, and neither printed anything (runs, but proves little)
+ no-code tslang found nothing to run (declarations only) and Node printed nothing
+ stdout stdout differs
+ tslang-throw Node exited 0, tslang exited non-zero (uncaught error at run time)
+ tslang-crash tslang died by an exception code (access violation, stack overflow, ...)
+ tslang-timeout tslang ran longer than --timeout, Node did not
+ tslang-compile tslang refused the file (JIT compile error) although the sweep compiled it
+ tslang-only-ok Node threw, tslang exited 0
+ node-fail Node could not run it (transpile or run-time error) and tslang failed too: skipped
+"""
+import argparse
+import csv
+import ctypes
+import os
+import re
+import shutil
+import subprocess
+import sys
+import time
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+
+REPO = Path(__file__).resolve().parent.parent
+DEFAULT_TSLANG = REPO / '__build/tslang/windows-msbuild-2026-release/bin/tslang.exe'
+
+NODE_PRELUDE = r'''
+function print(...a) { console.log(...a); }
+function assert(c, m) { if (!c) { throw new Error(m === undefined ? "assert" : m); } }
+'''
+NODE_EPILOGUE = '\nif (typeof main === "function") { main(); }\n'
+
+DIRECTIVE = re.compile(r'^\s*//\s*@(\w+)\s*:', re.I)
+
+
+def single_unit_source(path: Path):
+ """Source of a tsc harness test, or None when it is split into several files."""
+ text = path.read_text(encoding='utf-8', errors='replace')
+ lines = []
+ for line in text.splitlines():
+ m = DIRECTIVE.match(line)
+ if m:
+ if m.group(1).lower() == 'filename':
+ return None
+ continue
+ lines.append(line)
+ return '\n'.join(lines) + '\n'
+
+
+def run(cmd, cwd, timeout, env=None):
+ t0 = time.time()
+ try:
+ p = subprocess.run(cmd, cwd=cwd, capture_output=True, timeout=timeout, env=env)
+ return p.returncode, p.stdout.decode('utf-8', 'replace'), p.stderr.decode('utf-8', 'replace'), time.time() - t0
+ except subprocess.TimeoutExpired as e:
+ out = (e.stdout or b'').decode('utf-8', 'replace')
+ return 'timeout', out, '', time.time() - t0
+
+
+def norm(s: str) -> str:
+ return '\n'.join(l.rstrip() for l in s.replace('\r\n', '\n').strip().split('\n'))
+
+
+def is_crash_code(rc):
+ # Windows exception codes come back as large unsigned values (0xC0000005 ...), POSIX signals as negatives
+ return isinstance(rc, int) and (rc < 0 or rc >= 0xC0000000 or rc in (3, 0x80000003))
+
+
+def classify(t_rc, t_out, t_err, n_rc, n_out):
+ t, n = norm(t_out), norm(n_out)
+ if "entry point 'main' not found" in t_err:
+ # nothing at the top level to run (declarations only)
+ return 'no-code' if not n else 'stdout'
+ if n_rc != 0:
+ if t_rc == 0:
+ return 'tslang-only-ok'
+ if t_rc != 'timeout' and not is_crash_code(t_rc) and t == n:
+ return 'match'
+ return 'node-fail'
+ if t_rc == 'timeout':
+ return 'tslang-timeout'
+ if is_crash_code(t_rc):
+ return 'tslang-crash'
+ if t_rc != 0:
+ if re.search(r': error: ', t_err) and not t:
+ return 'tslang-compile'
+ return 'tslang-throw'
+ if t != n:
+ return 'stdout'
+ return 'match-silent' if not t else 'match'
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument('--sweep', help='folder of a tsc sweep (results.csv)')
+ ap.add_argument('--tests-dir', default=r'E:\Dev3\TypeScript\tsc\testdata\tests\cases\compiler')
+ ap.add_argument('--corpus', help='folder of .ts files')
+ ap.add_argument('--out', required=True)
+ ap.add_argument('--tslang', default=str(DEFAULT_TSLANG))
+ ap.add_argument('--tslang-args', default='', help='extra tslang arguments, e.g. "--mm=rc"')
+ ap.add_argument('--jobs', type=int, default=8)
+ ap.add_argument('--timeout', type=int, default=30)
+ ap.add_argument('--filter', default='', help='regex on the test name')
+ ap.add_argument('--limit', type=int, default=0)
+ args = ap.parse_args()
+
+ if os.name == 'nt': # no crash dialogs from crashing children
+ ctypes.windll.kernel32.SetErrorMode(0x0001 | 0x0002 | 0x8000)
+
+ out = Path(args.out)
+ if out.exists():
+ shutil.rmtree(out)
+ src_dir, js_dir, diff_dir = out / 'src', out / 'js', out / 'diffs'
+ for d in (src_dir, js_dir, diff_dir):
+ d.mkdir(parents=True)
+
+ # 1. collect the sources
+ names = []
+ corpus = bool(args.corpus)
+ if args.sweep:
+ with open(Path(args.sweep) / 'results.csv', newline='', encoding='utf-8') as f:
+ for row in csv.DictReader(f):
+ if row['Status'] == 'pass' and row['Units'] == '1':
+ names.append(row['Test'])
+ base = Path(args.tests_dir)
+ else:
+ base = Path(args.corpus)
+ names = sorted(p.name for p in base.glob('*.ts') if not p.name.endswith('.d.ts'))
+ if args.filter:
+ names = [n for n in names if re.search(args.filter, n)]
+ if args.limit:
+ names = names[:args.limit]
+
+ tests = []
+ for n in names:
+ p = base / n
+ if p.suffix != '.ts':
+ continue
+ text = single_unit_source(p) if args.sweep else p.read_text(encoding='utf-8', errors='replace')
+ if text is None:
+ continue
+ stem = p.stem
+ (src_dir / (stem + '.ts')).write_text(text, encoding='utf-8')
+ tests.append(stem)
+ print(f'{len(tests)} tests', flush=True)
+
+ # 2. transpile for Node, one file per tsc call (tsc --noCheck: types stripped, enums/namespaces/parameter
+ # properties lowered). A batch call drops the whole batch's output when one file can't be emitted.
+ tsc = shutil.which('tsc') or shutil.which('tsc.cmd')
+
+ def transpile(t):
+ try:
+ subprocess.run([tsc, '--noCheck', '--target', 'es2022', '--module', 'commonjs', '--experimentalDecorators',
+ '--rootDir', str(src_dir), '--outDir', str(js_dir), str(src_dir / (t + '.ts'))],
+ capture_output=True, shell=False, timeout=args.timeout)
+ except subprocess.TimeoutExpired:
+ return # tsc 7 hangs on a few inputs; the test then counts as node-fail
+
+ js = js_dir / (t + '.js')
+ if corpus and js.exists():
+ js.write_text(NODE_PRELUDE + js.read_text(encoding='utf-8') + NODE_EPILOGUE, encoding='utf-8')
+
+ with ThreadPoolExecutor(args.jobs) as ex:
+ list(ex.map(transpile, tests))
+ print(f'{sum(1 for _ in js_dir.glob("*.js"))} transpiled', flush=True)
+
+ env = dict(os.environ)
+ for k in ('TSLANG_LIB_PATH', 'DEFAULT_LIB_PATH', 'GC_LIB_PATH', 'LLVM_LIB_PATH'):
+ env.setdefault(k, r'I:\tslang')
+ extra = args.tslang_args.split()
+
+ # 3. run both
+ def one(t):
+ ts = src_dir / (t + '.ts')
+ js = js_dir / (t + '.js')
+ if js.exists():
+ n_rc, n_out, n_err, n_s = run(['node', str(js)], js_dir, args.timeout)
+ else:
+ n_rc, n_out, n_err, n_s = 'no-js', '', 'tsc emitted nothing', 0
+ t_rc, t_out, t_err, t_s = run([args.tslang, *extra, str(ts)], src_dir, args.timeout, env)
+ cat = classify(t_rc, t_out, t_err, n_rc, n_out)
+ if cat not in ('match', 'match-silent', 'node-fail', 'no-code'):
+ (diff_dir / (t + '.txt')).write_text(
+ f'category: {cat}\ntslang exit: {t_rc}\nnode exit: {n_rc}\n'
+ f'===== tslang stdout\n{t_out}\n===== tslang stderr\n{t_err[-4000:]}\n'
+ f'===== node stdout\n{n_out}\n===== node stderr\n{n_err[-2000:]}\n', encoding='utf-8')
+ first = ''
+ if cat == 'stdout':
+ a, b = norm(t_out).split('\n'), norm(n_out).split('\n')
+ for i in range(max(len(a), len(b))):
+ x = a[i] if i < len(a) else ''
+ y = b[i] if i < len(b) else ''
+ if x != y:
+ first = f'line {i + 1}: tslang={x[:120]!r} node={y[:120]!r}'
+ break
+ elif cat in ('tslang-throw', 'tslang-compile', 'tslang-crash'):
+ first = next((l for l in t_err.splitlines() if l.strip()), '')[:200]
+ return dict(test=t, category=cat, tslang_exit=t_rc, node_exit=n_rc, tslang_s=f'{t_s:.2f}', node_s=f'{n_s:.2f}', first=first)
+
+ started = time.time()
+ rows = []
+ with ThreadPoolExecutor(args.jobs) as ex:
+ for i, r in enumerate(ex.map(one, tests), 1):
+ rows.append(r)
+ if i % 200 == 0:
+ print(f' {i}/{len(tests)} ({time.time() - started:.0f}s)', flush=True)
+
+ with open(out / 'results.csv', 'w', newline='', encoding='utf-8') as f:
+ w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
+ w.writeheader()
+ w.writerows(rows)
+
+ counts = {}
+ for r in rows:
+ counts[r['category']] = counts.get(r['category'], 0) + 1
+ lines = [f'# Differential run: tslang vs Node ({len(rows)} tests)', '',
+ f'tslang: `{args.tslang} {args.tslang_args}`'.rstrip(), f'source: `{args.sweep or args.corpus}`', '',
+ '| Category | Tests |', '|---|---:|']
+ for k, v in sorted(counts.items(), key=lambda kv: -kv[1]):
+ lines.append(f'| {k} | {v} |')
+ for cat in ('tslang-crash', 'tslang-timeout', 'tslang-throw', 'stdout', 'tslang-compile', 'tslang-only-ok'):
+ sel = [r for r in rows if r['category'] == cat]
+ if sel:
+ lines += ['', f'## {cat} ({len(sel)})', '']
+ lines += [f'- `{r["test"]}` {r["first"]}'.rstrip() for r in sel]
+ (out / 'summary.md').write_text('\n'.join(lines) + '\n', encoding='utf-8')
+ print('\n'.join(lines[:20]))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tslang/lib/TypeScript/MLIRGenVariables.cpp b/tslang/lib/TypeScript/MLIRGenVariables.cpp
index 9d1a7464a..85c1c32fc 100644
--- a/tslang/lib/TypeScript/MLIRGenVariables.cpp
+++ b/tslang/lib/TypeScript/MLIRGenVariables.cpp
@@ -872,6 +872,15 @@ namespace mlirgen
return mlir::failure();
}
+ // an element read out of an iterable is `T | undefined` (past its end): a pattern of it reads T's value,
+ // as an element access does (`const [[k, v]] = map`; TypeScript types the element T)
+ if (auto optType = dyn_cast(init.getType()))
+ {
+ typeRef = optType.getElementType();
+ type = typeRef;
+ init = builder.create(location, typeRef, init);
+ }
+
mlir::Value arrayLikeLengthValue;
mlir::Type arrayLikeElementType;
auto isIterator = false;
diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp
index 87ea89c04..6f8d558e6 100644
--- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp
+++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp
@@ -412,6 +412,12 @@ class OwnedReturnConsumptionPass
// (`po([undefined])`, `[null]`: elements that are no value at all, so nothing to own or to borrow - such a
// literal given to a call was never given back, own leaked it every call)
auto onlyNoValues = true;
+ // text it holds a copy of (copyBorrowedTextElements), or was given new (`["x" + i]`): its own, as a new value
+ // moved in is. Not counted, a literal of strings alone given to a call (`new Set(["a" + i])`, `len(["x" + i])`)
+ // was owned by nothing and given back by nothing: each call leaked it and its strings
+ // (not beside a value something else had, which the literal would take over: `[s, o]` borrows both)
+ auto holdsText = false;
+ auto anyTaken = false;
for (auto element : arrayOp->getOperands())
{
if (isNoValue(element))
@@ -422,6 +428,7 @@ class OwnedReturnConsumptionPass
if (!mth.ownsHeapMemory(arrayOp->getLoc(), element.getType()) || isBorrowedText(element))
{
onlyNoValues = onlyNoValues && !isBorrowedText(element);
+ holdsText = holdsText || isBorrowedText(element);
continue;
}
@@ -438,10 +445,11 @@ class OwnedReturnConsumptionPass
return false;
}
+ anyTaken = true;
allTakenAreLocals = allTakenAreLocals && isLocalsOwn(element);
}
- return anyNew || onlyNoValues || (allTakenAreLocals && !givenToCall);
+ return anyNew || (holdsText && !anyTaken) || onlyNoValues || (allTakenAreLocals && !givenToCall);
}
// undefined or null, through the casts and the optional that only widen it
@@ -610,7 +618,8 @@ class OwnedReturnConsumptionPass
return false;
}
- // its one use is the call, through casts
+ // its one use is the call, through casts, and the optional an optional parameter takes it as (`new
+ // Set([a, b])` of a `constructor(values?: V[])`: given back by nothing, each call leaked the literal)
while (value.hasOneUse())
{
auto *user = *value.getUsers().begin();
@@ -619,18 +628,30 @@ class OwnedReturnConsumptionPass
return true;
}
- auto userCastOp = mlir::dyn_cast(user);
- if (!userCastOp)
+ if (!mlir::isa(user))
{
return false;
}
- value = userCastOp.getRes();
+ value = user->getResult(0);
}
return false;
}
+ // The new array an argument given as an optional is (`ts.OptionalValue` of it, its one use), or the argument
+ static mlir::Value arrayInsideOptional(mlir::Value argument)
+ {
+ auto optionalValueOp = argument.getDefiningOp();
+ if (optionalValueOp && optionalValueOp->getOperand(0).hasOneUse() &&
+ mlir::isa(optionalValueOp->getOperand(0).getType()))
+ {
+ return optionalValueOp->getOperand(0);
+ }
+
+ return argument;
+ }
+
// -mm=own: may a new array own what it holds, so that giving it back gives its elements back too? One of
// elements that own nothing, or a literal that can own what it holds (holdsOnlyMovedInElements: new values
// moved into it, and text it is given copies of - `["x" + i, mk()]`, `[new C()]`, `["x" + i, s]`). One of
@@ -683,6 +704,9 @@ class OwnedReturnConsumptionPass
}
}
+ // an optional parameter's (`new Set([a, b])`): the array inside the optional
+ argument = arrayInsideOptional(argument);
+
auto *definingOp = argument.getDefiningOp();
// `f([])`: the empty constant array cast to an array - a copy made on the heap there - is the new empty
@@ -2046,9 +2070,9 @@ class OwnedReturnConsumptionPass
continue;
}
- if (compileOptions.isRefCounted() && arrayMadeFor(argument, op, true))
+ if (compileOptions.isRefCounted() && arrayMadeFor(arrayInsideOptional(argument), op, true))
{
- held.push_back({op, argument});
+ held.push_back({op, arrayInsideOptional(argument)});
continue;
}
diff --git a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp
index 9a0d325e2..ebaa7215c 100644
--- a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp
+++ b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp
@@ -1239,6 +1239,29 @@ namespace own_inference
return;
}
+ // an element of an array that borrows it (a rest argument, `console.log(pair().value)`,
+ // classifyArgumentArrays; or a local array literal, classifyLocalBorrowingArrays): rc's
+ // retain for it is gone, and what uses the array reads the field
+ if (mlir::isa(user) && fieldBorrowRetains.contains(user))
+ {
+ return;
+ }
+
+ if (mlir::isa(user) && user->hasAttr(OWN_BORROWING_ARRAY_ATTR_NAME))
+ {
+ reads.push_back(user);
+ forEachUse(user->getResult(0), [&](mlir::Operation *arrayUser, mlir::Value) { reads.push_back(arrayUser); });
+ if (auto found = arrayElementUses.find(user); found != arrayElementUses.end())
+ {
+ for (auto &use : found->second)
+ {
+ reads.push_back(use.op);
+ }
+ }
+
+ return;
+ }
+
auto merged = mergedValuesOf(user, used);
if (!merged.empty())
{
diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt
index 67ed89864..56f62d5f6 100644
--- a/tslang/test/tester/CMakeLists.txt
+++ b/tslang/test/tester/CMakeLists.txt
@@ -1467,6 +1467,16 @@ tslang_add_test(NAME test-jit-rc-00-own-iterable-destructure COMMAND test-runner
tslang_add_test(NAME test-jit-own-00-own-iterable-destructure COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_iterable_destructure.ts")
tslang_add_test(NAME test-compile-00-own-iterable-destructure COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_iterable_destructure.ts")
tslang_add_test(NAME test-compile-own-00-own-iterable-destructure COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_iterable_destructure.ts")
+tslang_add_test(NAME test-jit-00-own-rest-argument-field COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_rest_argument_field.ts")
+tslang_add_test(NAME test-jit-rc-00-own-rest-argument-field COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_rest_argument_field.ts")
+tslang_add_test(NAME test-jit-own-00-own-rest-argument-field COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_rest_argument_field.ts")
+tslang_add_test(NAME test-compile-00-own-rest-argument-field COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_rest_argument_field.ts")
+tslang_add_test(NAME test-compile-own-00-own-rest-argument-field COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_rest_argument_field.ts")
+tslang_add_test(NAME test-jit-00-nested-iterable-array-pattern COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00nested_iterable_array_pattern.ts")
+tslang_add_test(NAME test-jit-rc-00-nested-iterable-array-pattern COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00nested_iterable_array_pattern.ts")
+tslang_add_test(NAME test-jit-own-00-nested-iterable-array-pattern COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00nested_iterable_array_pattern.ts")
+tslang_add_test(NAME test-compile-00-nested-iterable-array-pattern COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00nested_iterable_array_pattern.ts")
+tslang_add_test(NAME test-compile-own-00-nested-iterable-array-pattern COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00nested_iterable_array_pattern.ts")
tslang_add_test(NAME test-jit-00-own-module-const-beside-top-level COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_module_const_beside_top_level.ts")
tslang_add_test(NAME test-jit-rc-00-own-module-const-beside-top-level COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_module_const_beside_top_level.ts")
tslang_add_test(NAME test-jit-own-00-own-module-const-beside-top-level COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_module_const_beside_top_level.ts")
@@ -6880,6 +6890,19 @@ foreach(captured_cells_mm gc rc none)
tslang_add_test(NAME test-compile-captured-cells-${captured_cells_mm} COMMAND test-runner -mm=${captured_cells_mm} "${PROJECT_SOURCE_DIR}/test/tester/captured-cells/captured_cells.ts")
tslang_add_test(NAME test-jit-captured-cells-${captured_cells_mm} COMMAND test-runner -jit -mm=${captured_cells_mm} "${PROJECT_SOURCE_DIR}/test/tester/captured-cells/captured_cells.ts")
endforeach()
+# A new array given to an optional parameter (`new Set([a, b])`) reaches the call as `ts.OptionalValue` of it,
+# and nothing gave it back under rc or own; nor, under own, a literal of strings alone given to any call. The
+# IR is read, as no run shows the leak. It runs in every model.
+foreach(optional_array_mm rc own)
+ add_test(NAME test-${optional_array_mm}-optional-array-argument
+ COMMAND ${CMAKE_COMMAND} -DTSLANG=$ -DMM=${optional_array_mm}
+ "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/optional-array-argument/optional_array_argument.ts"
+ -P "${CMAKE_CURRENT_SOURCE_DIR}/optional-array-argument.cmake")
+endforeach()
+foreach(optional_array_mm gc rc none own)
+ tslang_add_test(NAME test-compile-optional-array-argument-${optional_array_mm} COMMAND test-runner -mm=${optional_array_mm} "${PROJECT_SOURCE_DIR}/test/tester/optional-array-argument/optional_array_argument.ts")
+ tslang_add_test(NAME test-jit-optional-array-argument-${optional_array_mm} COMMAND test-runner -jit -mm=${optional_array_mm} "${PROJECT_SOURCE_DIR}/test/tester/optional-array-argument/optional_array_argument.ts")
+endforeach()
foreach(temp_array_mm gc rc none own)
tslang_add_test(NAME test-compile-temp-array-literal-${temp_array_mm} COMMAND test-runner -mm=${temp_array_mm} "${PROJECT_SOURCE_DIR}/test/tester/temp-array-literal/temp_array_literal.ts")
tslang_add_test(NAME test-jit-temp-array-literal-${temp_array_mm} COMMAND test-runner -jit -mm=${temp_array_mm} "${PROJECT_SOURCE_DIR}/test/tester/temp-array-literal/temp_array_literal.ts")
diff --git a/tslang/test/tester/optional-array-argument.cmake b/tslang/test/tester/optional-array-argument.cmake
new file mode 100644
index 000000000..f8ed46815
--- /dev/null
+++ b/tslang/test/tester/optional-array-argument.cmake
@@ -0,0 +1,48 @@
+# A new array given to an optional parameter (optional-array-argument/optional_array_argument.ts): the call
+# takes `ts.OptionalValue` of it, and nothing gave the array back (`new Set([a, b])` leaked every call). No run
+# shows the leak, so the IR is read after OwnedReturnConsumptionPass (--emit=mlir): under rc each new array in
+# `reads` is retained once and released once around its call; under own each is an owned result that is given
+# back (released) after it.
+cmake_minimum_required(VERSION 3.17.3)
+execute_process(COMMAND "${TSLANG}" --emit=mlir --no-default-lib -mm=${MM} "${FILE}"
+ OUTPUT_VARIABLE out ERROR_VARIABLE err RESULT_VARIABLE result)
+# the IR is printed to stderr
+string(APPEND out "${err}")
+if(NOT result EQUAL 0)
+ message(FATAL_ERROR "tslang failed (${result}):\n${out}")
+endif()
+
+string(FIND "${out}" "ts.Func @reads " begin)
+if(begin EQUAL -1)
+ message(FATAL_ERROR "no function `reads` in:\n${out}")
+endif()
+string(SUBSTRING "${out}" ${begin} -1 body)
+string(SUBSTRING "${body}" 1 -1 rest)
+string(FIND "${rest}" "ts.Func @" end)
+if(NOT end EQUAL -1)
+ math(EXPR end "${end} + 1")
+ string(SUBSTRING "${body}" 0 ${end} body)
+endif()
+
+string(REGEX MATCHALL "%[0-9]+ = \"ts[.]CreateArray\"[(]%[^\n]*" made "${body}")
+list(LENGTH made count)
+if(NOT count EQUAL 3)
+ message(FATAL_ERROR "expected 3 new arrays in `reads`, found ${count}:\n${body}")
+endif()
+
+foreach(line ${made})
+ string(REGEX MATCH "^(%[0-9]+)" array "${line}")
+ string(REGEX MATCHALL "\"ts[.]Release\"[(]${array}[)]" releases "${body}")
+ list(LENGTH releases l)
+ if(NOT l EQUAL 1)
+ message(FATAL_ERROR "${array} is released ${l} times, not once:\n${body}")
+ endif()
+
+ if(MM STREQUAL "rc")
+ string(REGEX MATCHALL "\"ts[.]Retain\"[(]${array}[)]" retains "${body}")
+ list(LENGTH retains r)
+ if(NOT r EQUAL 1)
+ message(FATAL_ERROR "${array} is retained ${r} times, not once:\n${body}")
+ endif()
+ endif()
+endforeach()
diff --git a/tslang/test/tester/optional-array-argument/optional_array_argument.ts b/tslang/test/tester/optional-array-argument/optional_array_argument.ts
new file mode 100644
index 000000000..13d895673
--- /dev/null
+++ b/tslang/test/tester/optional-array-argument/optional_array_argument.ts
@@ -0,0 +1,33 @@
+// A new array given to an optional parameter (`new Set([a, b])` of DefaultLib's `constructor(values?: V[])`)
+// reaches the call as `ts.OptionalValue` of it. Nothing gave it back: rc held only an array given as it is,
+// and own owned only such a one, so every call leaked the literal (2M rounds of `new Set(["a" + i])`:
+// 220 MB). Read by optional-array-argument.cmake under rc and own: each array in `reads` is given back
+// after its call. It runs in every model.
+class Box {
+ n: number;
+ constructor(values?: string[]) {
+ this.n = values ? values.length : 0;
+ }
+}
+
+function len(values?: string[]): number {
+ return values ? values.length : 0;
+}
+
+function lenNumbers(values?: number[]): number {
+ return values ? values.length : 0;
+}
+
+function reads(i: number): number {
+ return len(["a" + i, "b"]) + lenNumbers([i, i + 1]) + new Box(["c" + i]).n;
+}
+
+function main() {
+ let total: number = 0;
+ for (let i = 0; i < 20000; i++) {
+ total += reads(i);
+ }
+
+ assert(total == 100000, "total");
+ print("done.");
+}
diff --git a/tslang/test/tester/tests/00nested_iterable_array_pattern.ts b/tslang/test/tester/tests/00nested_iterable_array_pattern.ts
new file mode 100644
index 000000000..c8154c66b
--- /dev/null
+++ b/tslang/test/tester/tests/00nested_iterable_array_pattern.ts
@@ -0,0 +1,32 @@
+// A nested array pattern of an iterable (`const [[k, v]] = map`): the element read out of an iterable is
+// `T | undefined` (past its end), and the inner pattern refused it ("an array pattern of a value of type
+// '[string, number] | undefined' is not supported"), under every memory model. A Map is such an
+// iterable. The inner pattern now reads T's value, as TypeScript types the element T.
+function* pairs(i: number) {
+ yield ["a" + i, 1] as [string, number];
+ yield ["b" + i, 2] as [string, number];
+}
+
+function entries(i: number): string {
+ const [[k0, v0], [k1, v1]] = pairs(i);
+ return k0 + "=" + v0 + "," + k1 + "=" + v1;
+}
+
+function firstOnly(i: number): string {
+ const [[key]] = pairs(i);
+ return key;
+}
+
+function main() {
+ assert(entries(1) == "a1=1,b1=2", "two entries");
+ assert(firstOnly(7) == "a7", "first key");
+
+ let n: number = 0;
+ for (let i = 0; i < 20000; i++) {
+ n += entries(i).length + firstOnly(i).length;
+ }
+
+ assert(n > 0, "many times");
+
+ print("done.");
+}
diff --git a/tslang/test/tester/tests/00own_rest_argument_field.ts b/tslang/test/tester/tests/00own_rest_argument_field.ts
new file mode 100644
index 000000000..192fec262
--- /dev/null
+++ b/tslang/test/tester/tests/00own_rest_argument_field.ts
@@ -0,0 +1,71 @@
+// A field of a record returned by a call, passed straight to a rest parameter (`console.log(mk().value)`,
+// `const v = mk().value; console.log(v)` in a function, `const [a] = set; console.log(a)`): the rest
+// array borrows the field for the call (classifyArgumentArrays), and the record is given back after it.
+// -mm=own refused it ("a value takes a second reference"): the field's one use, the borrowing array,
+// was not counted as a read of the record. Runtime strings, not literals: a literal is immortal and
+// hides a wrong count.
+function mk(i: number) {
+ return { value: "x" + i, done: false };
+}
+
+function* strings(k: number) {
+ yield "g" + k;
+ yield "h" + k;
+}
+
+function count(...items: string[]): number {
+ let n: number = 0;
+ for (const s of items) {
+ n += s.length;
+ }
+
+ return n;
+}
+
+function named(i: number): number {
+ const v = mk(i).value;
+ return count(v);
+}
+
+function direct(i: number): number {
+ return count(mk(i).value, mk(i + 1).value);
+}
+
+function destructured(i: number): number {
+ const { value } = mk(i);
+ return count(value);
+}
+
+function held(i: number): number {
+ const r = mk(i);
+ return count(r.value);
+}
+
+function fromNext(i: number): number {
+ const it = strings(i);
+ const w = it.next().value;
+ return count(w ?? "");
+}
+
+function fromPattern(i: number): number {
+ const [a, b] = strings(i);
+ return count(a ?? "", b ?? "");
+}
+
+function main() {
+ assert(named(5) == 2, "named");
+ assert(direct(5) == 4, "direct");
+ assert(destructured(5) == 2, "destructured");
+ assert(held(5) == 2, "held");
+ assert(fromNext(5) == 2, "next().value");
+ assert(fromPattern(5) == 4, "array pattern of an iterable");
+
+ let n: number = 0;
+ for (let i = 0; i < 20000; i++) {
+ n += named(i) + direct(i) + destructured(i) + held(i) + fromNext(i) + fromPattern(i);
+ }
+
+ assert(n > 0, "many times");
+
+ print("done.");
+}