Promise-returning functions without async: rejections, not throws #11
Loading…
Reference in a new issue
No description provided.
Delete branch "promise-returning-functions"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Closes the second and third items of README "Known gaps":
asynckeyword marked a function as async, so a plain function returning a promise counted as throwing.try { f() }withoutawaitlooked like it caught the rejection, and an unawaitedf()raised nofloating-rejection.catchcounted as handling every error kind.if (e instanceof NotFound) return x; throw e;hidForbiddenfrom the analysis,catch (e) { throw e }looked like a handler, and so didtry { ... } finally { ... }with nocatch.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:asyncfunction, anew Promise(executor)executor, or a callback run right away inside one of those, rejects;return, an arrow expression body,.then(ok)or.finally(...)stays a rejection of the caller,asyncor not;Promise.all/race/anypass their elements' rejections on (awaited or returned when the outer call is);Promise.allSettledhandles them;forEach/filter/some/find/sort... callback is dropped (onlymap,flatMap,reducekeep it), so it floats.At a call site, a
try(orunsafe) catches thrown kinds, and catches rejections only when they are awaited inside it..catch(...)/.then(ok, fail)catch only rejections, andunsafeAsynccatches both. So a function that checks its input and throws before making its promise is handled correctly:trycatches that part,.catchthe rest. It also means a plain function declaredPromise<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-rejectionfor unawaited rejections,uncaught-propagationfor the rest at top level or in detached callbacks.unhandled-failureacross 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)
analyze.rs,catch_rethrows): for eachcatch (e), when does it rethrowe? This is followed through blocks,if/else,returnandthrow e(athrowof anything else handlese). Conditions are built frome instanceof X(Xorns.X),!,&&and||. Any other test, and loops /switch/ labels / nestedtrythat contain athrow e, count as maybe rethrowing (three-valued logic). A catch that never rethrows handles everything, as before. One that always rethrows, andfinallywithoutcatch, handle nothing. The rest are recorded per site.project.rs):e instanceof Xis evaluated for eachPropagateErrorkind along the thrown class'sextendschain, across files and re-exports.Gone extends NotFoundis caught byinstanceof NotFound, not the other way round, andinstanceof PropagateError/Errorcatch 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 atrythat awaits it.trycount as handled only if the catch keeps them whatever they are, or keepsinstanceof Error. A test against a projectPropagateErrorclass is known not to match them.Rule change to review:
throw eof the unchangedcatch (e)binding is no longer ano-throw. Without that, theelse throw epattern can't be written in checked code at all. It stays sound: the analysis now knows thetrydoesn't handle what is rethrown, so the rethrown kinds are reported where they end up. Theno-throwpage's rethrow example now shows theunhandled-failureonJSON.parseinstead. Reassigned bindings (e = ...) andthrowof anything else are stillno-throw.Not covered (documented in README "Known gaps",
floating-rejectionanduncaught-propagation)await/return/.then/.catch/.finally/Promise.alland siblings, is reported as floating (unchanged). A.then(...)callback still counts as detached.instanceof(e.name === ...,isRetryable(e)), aliases ofe, and loops/switchin acatcharen't read in detail. If they can reachthrow e, every kind counts as rethrown.if (e instanceof SyntaxError) return; throw e;aroundJSON.parseis still reported. This is a false positive, in the safe direction.Tests
Rebased onto
mainat04a5576(git rebase --onto origin/main 3553552, dropping #5's commit, which is identical to main's6d2ba9d). There were no conflicts, and no changes were needed for what main gained. I checked the overlap: #8'smegamorphic.rsand #10'sdevchecks.rsdon't use the throw/rejection analysis. #10'sproject.rschange (thetransform_with/ dev-check plumbing) is separate from the propagation code. #5'scallsand #8'sshapesfixtures pass on top of this analysis.cargo nextest run --workspace: 102 passed, 0 failed. This includesfixtures_match_annotationsover all fixtures: this PR'spromises, #18'scatchesand the updatedthrows, plus main'scalls,shapes,json_imports,featuresandlints. It also includesdocs.rs(checked doc examples).npm run check(demo): same output asmain, 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/promisescovers return /.then/ arrow body / executor, a function that throws one kind and rejects another (with.catchonly, and withtry+.catch),trywith and withoutawait,forEachvsmap+Promise.all,Promise.allSettled, a legacy failure handed back by a plain function, and top-level calls.tests/fixtures/catchescoverselse throw, early return thenthrow e, a negated test withns.X,||, a subclass-only test,instanceof PropagateError, a handled branch that falls through to the rethrow, an unknown test, a catch without rethrow,finallyonly, nested tries, async withawait, andJSON.parse/ legacy calls under narrowing catches. Both fixtures failed against the code they replace (checked when they were written).🤖 Generated with 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]>a78a284cdbto67b79110b1