Promise-returning functions without async: rejections, not throws #11

Merged
sionzee merged 2 commits from promise-returning-functions into main 2026-11-03 21:59:06 +01:00
Owner

Rebased onto main at 04a5576. #5 is merged now, so its commit was dropped. This PR also contains #18 ("Narrow try/catch by error kind"), which was squash-merged into this branch. The branch has two commits: this PR's own change, then #18's. Nothing needed changing beyond the rebase (details under Tests).

Closes the second and third items of README "Known gaps":

  1. Only the async keyword marked a function as async, so a plain function returning a promise counted as throwing. try { f() } without await looked like it caught the rejection, and an unawaited f() raised no floating-rejection.
  2. (#18) Any catch counted as handling every error kind. if (e instanceof NotFound) return x; throw e; hid Forbidden from the analysis, catch (e) { throw e } looked like a handler, and so did try { ... } finally { ... } with no catch.

What changed: promise-returning functions

Instead of one async flag per function, every propagated error kind (and every failure behind unhandled-failure) records whether it is thrown or comes back as a rejection:

  • a throw (or a call's error) inside an async function, a new Promise(executor) executor, or a callback run right away inside one of those, rejects;
  • another call's rejection handed back with return, an arrow expression body, .then(ok) or .finally(...) stays a rejection of the caller, async or not;
  • Promise.all / race / any pass their elements' rejections on (awaited or returned when the outer call is); Promise.allSettled handles them;
  • a promise returned from a forEach / filter / some / find / sort ... callback is dropped (only map, flatMap, reduce keep it), so it floats.

At a call site, a try (or unsafe) catches thrown kinds, and catches rejections only when they are awaited inside it. .catch(...) / .then(ok, fail) catch only rejections, and unsafeAsync catches both. So a function that checks its input and throws before making its promise is handled correctly: try catches that part, .catch the rest. It also means a plain function declared Promise<T> that only throws synchronously is (correctly) treated as throwing. The declared return type is not used; where each error comes from decides.

For each kind, safe-ts check's map lists what each call catches. Kinds a call doesn't catch are reported: floating-rejection for unawaited rejections, uncaught-propagation for the rest at top level or in detached callbacks. unhandled-failure across modules now says "can reject" / "can throw or reject", and offers the floating-rejection fixes when the rejection isn't awaited. A function that hands back rejections is shown as (async) in the map.

What changed: narrowing catches (#18)

  • Reading the catch (analyze.rs, catch_rethrows): for each catch (e), when does it rethrow e? This is followed through blocks, if/else, return and throw e (a throw of anything else handles e). Conditions are built from e instanceof X (X or ns.X), !, && and ||. Any other test, and loops / switch / labels / nested try that contain a throw e, count as maybe rethrowing (three-valued logic). A catch that never rethrows handles everything, as before. One that always rethrows, and finally without catch, handle nothing. The rest are recorded per site.
  • Deciding per kind (project.rs): e instanceof X is evaluated for each PropagateError kind along the thrown class's extends chain, across files and re-exports. Gone extends NotFound is caught by instanceof NotFound, not the other way round, and instanceof PropagateError / Error catch all kinds. A kind counts as caught only if the catch's rethrow condition is definitely false for it. Otherwise it keeps propagating. This combines with the rejection rules above: a rejection is only caught by a try that awaits it.
  • Other failures (built-ins, feature-pack library calls, legacy code) inside a narrowing try count as handled only if the catch keeps them whatever they are, or keeps instanceof Error. A test against a project PropagateError class is known not to match them.

Rule change to review: throw e of the unchanged catch (e) binding is no longer a no-throw. Without that, the else throw e pattern can't be written in checked code at all. It stays sound: the analysis now knows the try doesn't handle what is rethrown, so the rethrown kinds are reported where they end up. The no-throw page's rethrow example now shows the unhandled-failure on JSON.parse instead. Reassigned bindings (e = ...) and throw of anything else are still no-throw.

Not covered (documented in README "Known gaps", floating-rejection and uncaught-propagation)

  • Where a promise goes once stored or passed on. A promise kept in a variable and awaited later, or passed to anything except await / return / .then / .catch / .finally / Promise.all and siblings, is reported as floating (unchanged). A .then(...) callback still counts as detached.
  • Tests other than instanceof (e.name === ..., isRetryable(e)), aliases of e, and loops/switch in a catch aren't read in detail. If they can reach throw e, every kind counts as rethrown.
  • The error class of built-in and library failures isn't tracked, so if (e instanceof SyntaxError) return; throw e; around JSON.parse is still reported. This is a false positive, in the safe direction.

Tests

Rebased onto main at 04a5576 (git rebase --onto origin/main 3553552, dropping #5's commit, which is identical to main's 6d2ba9d). There were no conflicts, and no changes were needed for what main gained. I checked the overlap: #8's megamorphic.rs and #10's devchecks.rs don't use the throw/rejection analysis. #10's project.rs change (the transform_with / dev-check plumbing) is separate from the propagation code. #5's calls and #8's shapes fixtures pass on top of this analysis.

  • cargo nextest run --workspace: 102 passed, 0 failed. This includes fixtures_match_annotations over all fixtures: this PR's promises, #18's catches and the updated throws, plus main's calls, shapes, json_imports, features and lints. It also includes docs.rs (checked doc examples).
  • npm run check (demo): same output as main, apart from timings.
  • safe-ts check examples/vue/src/main.ts: no problems.
  • npm run test:std: 130/130 passed.
  • npm run test:vite: passed.
  • npm run test:docs: passed (223 documentation examples compile, wasm build, VitePress build).
  • npm run typecheck: passed.
  • npm run bench:check: not run; no benches and no transform code are touched.

Fixtures from before the rebase: tests/fixtures/promises covers return / .then / arrow body / executor, a function that throws one kind and rejects another (with .catch only, and with try + .catch), try with and without await, forEach vs map + Promise.all, Promise.allSettled, a legacy failure handed back by a plain function, and top-level calls. tests/fixtures/catches covers else throw, early return then throw e, a negated test with ns.X, ||, a subclass-only test, instanceof PropagateError, a handled branch that falls through to the rethrow, an unknown test, a catch without rethrow, finally only, nested tries, async with await, and JSON.parse / legacy calls under narrowing catches. Both fixtures failed against the code they replace (checked when they were written).

🤖 Generated with Claude Code

> **Rebased onto `main` at 04a5576.** #5 is merged now, so its commit was dropped. This PR also contains **#18** ("Narrow try/catch by error kind"), which was squash-merged into this branch. The branch has two commits: this PR's own change, then #18's. Nothing needed changing beyond the rebase (details under Tests). Closes the second and third items of README "Known gaps": 1. Only the `async` keyword marked a function as async, so a plain function returning a promise counted as throwing. `try { f() }` without `await` looked like it caught the rejection, and an unawaited `f()` raised no `floating-rejection`. 2. (#18) Any `catch` counted as handling every error kind. `if (e instanceof NotFound) return x; throw e;` hid `Forbidden` from the analysis, `catch (e) { throw e }` looked like a handler, and so did `try { ... } finally { ... }` with no `catch`. ## What changed: promise-returning functions Instead of one async flag per function, every propagated error kind (and every failure behind `unhandled-failure`) records whether it is **thrown** or comes back as a **rejection**: - a throw (or a call's error) inside an `async` function, a `new Promise(executor)` executor, or a callback run right away inside one of those, rejects; - another call's rejection handed back with `return`, an arrow expression body, `.then(ok)` or `.finally(...)` stays a rejection of the caller, `async` or not; - `Promise.all` / `race` / `any` pass their elements' rejections on (awaited or returned when the outer call is); `Promise.allSettled` handles them; - a promise returned from a `forEach` / `filter` / `some` / `find` / `sort` ... callback is dropped (only `map`, `flatMap`, `reduce` keep it), so it floats. At a call site, a `try` (or `unsafe`) catches thrown kinds, and catches rejections only when they are awaited inside it. `.catch(...)` / `.then(ok, fail)` catch only rejections, and `unsafeAsync` catches both. So a function that checks its input and throws *before* making its promise is handled correctly: `try` catches that part, `.catch` the rest. It also means a plain function declared `Promise<T>` that only throws synchronously is (correctly) treated as throwing. The declared return type is not used; where each error comes from decides. For each kind, `safe-ts check`'s map lists what each call catches. Kinds a call doesn't catch are reported: `floating-rejection` for unawaited rejections, `uncaught-propagation` for the rest at top level or in detached callbacks. `unhandled-failure` across modules now says "can reject" / "can throw or reject", and offers the floating-rejection fixes when the rejection isn't awaited. A function that hands back rejections is shown as `(async)` in the map. ## What changed: narrowing catches (#18) - **Reading the catch** (`analyze.rs`, `catch_rethrows`): for each `catch (e)`, when does it rethrow `e`? This is followed through blocks, `if`/`else`, `return` and `throw e` (a `throw` of anything else handles `e`). Conditions are built from `e instanceof X` (`X` or `ns.X`), `!`, `&&` and `||`. Any other test, and loops / `switch` / labels / nested `try` that contain a `throw e`, count as *maybe* rethrowing (three-valued logic). A catch that never rethrows handles everything, as before. One that always rethrows, and `finally` without `catch`, handle nothing. The rest are recorded per site. - **Deciding per kind** (`project.rs`): `e instanceof X` is evaluated for each `PropagateError` kind along the thrown class's `extends` chain, across files and re-exports. `Gone extends NotFound` is caught by `instanceof NotFound`, not the other way round, and `instanceof PropagateError` / `Error` catch all kinds. A kind counts as caught only if the catch's rethrow condition is definitely false for it. Otherwise it keeps propagating. This combines with the rejection rules above: a rejection is only caught by a `try` that awaits it. - **Other failures** (built-ins, feature-pack library calls, legacy code) inside a narrowing `try` count as handled only if the catch keeps them whatever they are, or keeps `instanceof Error`. A test against a project `PropagateError` class is known not to match them. **Rule change to review:** `throw e` of the unchanged `catch (e)` binding is no longer a `no-throw`. Without that, the `else throw e` pattern can't be written in checked code at all. It stays sound: the analysis now knows the `try` doesn't handle what is rethrown, so the rethrown kinds are reported where they end up. The `no-throw` page's rethrow example now shows the `unhandled-failure` on `JSON.parse` instead. Reassigned bindings (`e = ...`) and `throw` of anything else are still `no-throw`. ## Not covered (documented in README "Known gaps", `floating-rejection` and `uncaught-propagation`) - Where a promise goes once stored or passed on. A promise kept in a variable and awaited later, or passed to anything except `await` / `return` / `.then` / `.catch` / `.finally` / `Promise.all` and siblings, is reported as floating (unchanged). A `.then(...)` callback still counts as detached. - Tests other than `instanceof` (`e.name === ...`, `isRetryable(e)`), aliases of `e`, and loops/`switch` in a `catch` aren't read in detail. If they can reach `throw e`, every kind counts as rethrown. - The error class of built-in and library failures isn't tracked, so `if (e instanceof SyntaxError) return; throw e;` around `JSON.parse` is still reported. This is a false positive, in the safe direction. ## Tests Rebased onto `main` at 04a5576 (`git rebase --onto origin/main 3553552`, dropping #5's commit, which is identical to main's 6d2ba9d). There were no conflicts, and no changes were needed for what main gained. I checked the overlap: #8's `megamorphic.rs` and #10's `devchecks.rs` don't use the throw/rejection analysis. #10's `project.rs` change (the `transform_with` / dev-check plumbing) is separate from the propagation code. #5's `calls` and #8's `shapes` fixtures pass on top of this analysis. - `cargo nextest run --workspace`: 102 passed, 0 failed. This includes `fixtures_match_annotations` over all fixtures: this PR's `promises`, #18's `catches` and the updated `throws`, plus main's `calls`, `shapes`, `json_imports`, `features` and `lints`. It also includes `docs.rs` (checked doc examples). - `npm run check` (demo): same output as `main`, apart from timings. - `safe-ts check examples/vue/src/main.ts`: no problems. - `npm run test:std`: 130/130 passed. - `npm run test:vite`: passed. - `npm run test:docs`: passed (223 documentation examples compile, wasm build, VitePress build). - `npm run typecheck`: passed. - `npm run bench:check`: not run; no benches and no transform code are touched. Fixtures from before the rebase: `tests/fixtures/promises` covers return / `.then` / arrow body / executor, a function that throws one kind and rejects another (with `.catch` only, and with `try` + `.catch`), `try` with and without `await`, `forEach` vs `map` + `Promise.all`, `Promise.allSettled`, a legacy failure handed back by a plain function, and top-level calls. `tests/fixtures/catches` covers `else throw`, early return then `throw e`, a negated test with `ns.X`, `||`, a subclass-only test, `instanceof PropagateError`, a handled branch that falls through to the rethrow, an unknown test, a catch without rethrow, `finally` only, nested tries, async with `await`, and `JSON.parse` / legacy calls under narrowing catches. Both fixtures failed against the code they replace (checked when they were written). 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Only the `async` keyword marked a function as async, so `function f() { return load() }`
counted as throwing: `try { f() }` without await looked like it caught the rejection,
and calling it unawaited raised no floating-rejection.

Instead of one async flag per function, every propagated error kind (and every failure)
now records whether it is thrown or comes back as a rejection: from an `async` function,
a `new Promise` executor, or another call's promise handed back with `return`, `.then`
or `.finally`. A try catches thrown kinds, and rejections only when awaited inside it;
`.catch()` catches only rejections. That also gets functions right that throw on bad
input before making their promise. Promises flow through `Promise.all`/`race`/`any`
(`allSettled` handles them), and a promise returned from a `forEach`/`filter`/... callback
is dropped, so it floats.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee changed target branch from calls-beyond-named-functions to main 2026-11-03 21:32:57 +01:00
sionzee force-pushed promise-returning-functions from a78a284cdb to 67b79110b1
All checks were successful
Benchmarks / bench (pull_request) Successful in 5m16s
2026-11-03 21:57:08 +01:00
Compare
sionzee deleted branch promise-returning-functions 2026-11-03 21:59:06 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!11
No description provided.