Unverified Commit 55366c11 authored by Sam Poder's avatar Sam Poder Committed by GitHub

[turbopack] Collapse nested promises in the analyzer (#96601)

parent d87a203b
...@@ -80,6 +80,11 @@ impl<'a> JsValue<'a> { ...@@ -80,6 +80,11 @@ impl<'a> JsValue<'a> {
} }
} }
} }
JsValue::Promise(_, inner) | JsValue::Awaited(_, inner) => {
if resolve_promises(inner) {
self.update_total_nodes();
}
}
JsValue::Concat(_, v) => { JsValue::Concat(_, v) => {
// TODO(kdy1): Remove duplicate // TODO(kdy1): Remove duplicate
let taken = take(v); let taken = take(v);
...@@ -186,4 +191,44 @@ impl<'a> JsValue<'a> { ...@@ -186,4 +191,44 @@ impl<'a> JsValue<'a> {
} }
} }
/// Replaces `value` with what awaiting it produces, returning whether it changed.
///
/// ```text
/// Promise<Promise<null>> -> null
/// Promise<null | Promise<0>> -> null | 0
/// c ? Promise<null> : Promise<0> -> c ? null : 0
/// null -> null
/// ```
pub(crate) fn resolve_promises<'a>(value: &mut JsValue<'a>) -> bool {
match value {
JsValue::Promise(_, inner) => {
let mut inner = take(&mut **inner);
resolve_promises(&mut inner);
*value = inner;
true
}
// Awaiting a branching value awaits whichever branch is taken, so the promises are inside
// the branches rather than around them.
JsValue::Tenary(_, _, cons, alt) => {
let modified = resolve_promises(cons) | resolve_promises(alt);
if modified {
value.update_total_nodes();
}
modified
}
JsValue::Alternatives { values, .. } => {
let mut modified = false;
for alternative in values.iter_mut() {
modified |= resolve_promises(alternative);
}
if modified {
let values = take(values);
*value = JsValue::alternatives(values);
}
modified
}
_ => false,
}
}
// Similarity // Similarity
awaited (const after eval) = await(findRowWrapped())
awaitedBranch (const after eval) = await((FreeVar(unknownFlag) ? findRow() : findRowWrapped()))
awaitedConditional (const after eval) = await(findRowConditional(true))
awaitedTwice (const after eval) = await(findRowWrappedTwice())
findRow (const after eval) = (...) => Promise<null>
findRowConditional (const after eval) = (...) => Promise<(useFirst ? findRow() : findRowWrapped())>
findRowWrapped (const after eval) = (...) => Promise<findRow()>
findRowWrappedTwice (const after eval) = (...) => Promise<findRowWrapped()>
notAwaited (const after eval) = findRowWrapped()
notAwaitedBranch (const after eval) = (FreeVar(unknownFlag) ? findRow() : findRowWrapped())
useFirst = arguments[0]
[
(
"awaited",
Awaited(
3,
Call(
2,
Variable(
(
"findRowWrapped",
#2,
),
),
[],
),
),
),
(
"awaitedBranch",
Awaited(
7,
Tenary(
6,
FreeVar(
"unknownFlag",
),
Call(
2,
Variable(
(
"findRow",
#2,
),
),
[],
),
Call(
2,
Variable(
(
"findRowWrapped",
#2,
),
),
[],
),
),
),
),
(
"awaitedConditional",
Awaited(
4,
Call(
3,
Variable(
(
"findRowConditional",
#2,
),
),
[
Constant(
True,
),
],
),
),
),
(
"awaitedTwice",
Awaited(
3,
Call(
2,
Variable(
(
"findRowWrappedTwice",
#2,
),
),
[],
),
),
),
(
"findRow",
Function(
3,
268,
Promise(
2,
Constant(
Null,
),
),
),
),
(
"findRowConditional",
Function(
8,
576,
Promise(
7,
Tenary(
6,
Variable(
(
"useFirst",
#6,
),
),
Call(
2,
Variable(
(
"findRow",
#2,
),
),
[],
),
Call(
2,
Variable(
(
"findRowWrapped",
#2,
),
),
[],
),
),
),
),
),
(
"findRowWrapped",
Function(
4,
384,
Promise(
3,
Call(
2,
Variable(
(
"findRow",
#2,
),
),
[],
),
),
),
),
(
"findRowWrappedTwice",
Function(
4,
441,
Promise(
3,
Call(
2,
Variable(
(
"findRowWrapped",
#2,
),
),
[],
),
),
),
),
(
"notAwaited",
Call(
2,
Variable(
(
"findRowWrapped",
#2,
),
),
[],
),
),
(
"notAwaitedBranch",
Tenary(
6,
FreeVar(
"unknownFlag",
),
Call(
2,
Variable(
(
"findRow",
#2,
),
),
[],
),
Call(
2,
Variable(
(
"findRowWrapped",
#2,
),
),
[],
),
),
),
(
"useFirst",
Argument(
576,
0,
),
),
]
// An async function that returns a promise-returning call without awaiting it resolves to the
// inner value, not to a promise. `Promise<Promise<T>>` is not representable, so the modelled
// value must collapse to `Promise<T>` and awaiting it must not look truthy.
async function findRow() {
return null;
}
// The wrapper returns the promise from `findRow` without awaiting it.
async function findRowWrapped() {
return findRow();
}
async function findRowWrappedTwice() {
return findRowWrapped();
}
// Same, but each branch of the returned expression is a promise.
async function findRowConditional(useFirst) {
return useFirst ? findRow() : findRowWrapped();
}
export const awaited = await findRowWrapped();
export const awaitedTwice = await findRowWrappedTwice();
export const awaitedConditional = await findRowConditional(true)
// `unknownFlag` is a free variable, so the branch survives analysis rather than folding to one
// side, and the promises sit inside the branches rather than around them.
export const awaitedBranch = await (unknownFlag ? findRow() : findRowWrapped())
// Un-awaited, the same expression really is a union of promises.
export const notAwaitedBranch = unknownFlag ? findRow() : findRowWrapped();
// Not awaited, so this one really is a promise.
export const notAwaited = findRowWrapped();
0 -> 1 call = (...) => Promise<findRow()>()
0 -> 2 call = (...) => Promise<findRowWrapped()>()
0 -> 3 call = (...) => Promise<(useFirst ? findRow() : findRowWrapped())>(true)
0 -> 4 free var = FreeVar(unknownFlag)
0 -> 5 conditional = ???*0*
- *0* FreeVar(unknownFlag)
⚠️ unknown global
⚠️ This value might have side effects
5 -> 6 call = (...) => Promise<null>()
5 -> 7 call = (...) => Promise<findRow()>()
0 -> 8 free var = FreeVar(unknownFlag)
0 -> 9 conditional = ???*0*
- *0* FreeVar(unknownFlag)
⚠️ unknown global
⚠️ This value might have side effects
9 -> 10 call = (...) => Promise<null>()
9 -> 11 call = (...) => Promise<findRow()>()
0 -> 12 call = (...) => Promise<findRow()>()
0 -> 13 unreachable = ???*0*
- *0* unreachable
⚠️ This value might have side effects
0 -> 14 call = (...) => Promise<null>()
0 -> 15 unreachable = ???*0*
- *0* unreachable
⚠️ This value might have side effects
0 -> 16 call = (...) => Promise<findRow()>()
0 -> 17 unreachable = ???*0*
- *0* unreachable
⚠️ This value might have side effects
0 -> 18 conditional = ???*0*
- *0* arguments[0]
⚠️ function calls are not analyzed yet
18 -> 19 call = (...) => Promise<null>()
18 -> 20 call = (...) => Promise<findRow()>()
0 -> 21 unreachable = ???*0*
- *0* unreachable
⚠️ This value might have side effects
awaited = null
awaitedBranch = (???*0* ? null : null)
- *0* FreeVar(unknownFlag)
⚠️ unknown global
⚠️ This value might have side effects
awaitedConditional = null
awaitedTwice = null
findRow = (...) => Promise<null>
findRowConditional = (...) => Promise<(useFirst ? findRow() : findRowWrapped())>
findRowWrapped = (...) => Promise<findRow()>
findRowWrappedTwice = (...) => Promise<findRowWrapped()>
notAwaited = Promise<null>
notAwaitedBranch = (???*0* ? Promise<null> : Promise<null>)
- *0* FreeVar(unknownFlag)
⚠️ unknown global
⚠️ This value might have side effects
useFirst = ???*0*
- *0* arguments[0]
⚠️ function calls are not analyzed yet
// An async function that returns a promise-returning call without awaiting it resolves to the
// inner value, not to a promise. Modelling that as `Promise<Promise<T>>` made awaiting it strip
// only one layer, so the result still looked like a promise — always truthy — and guards on it
// were folded away along with the code after them.
//
// Each guard below calls a concrete wrapper rather than a parameter, so the analyzer can
// resolve the call and the folding is actually exercised.
async function findRow() {
return null
}
// Returns the promise from `findRow` without awaiting it.
async function findRowWrapped() {
return findRow()
}
async function findRowWrappedTwice() {
return findRowWrapped()
}
async function findRowConditional(useFirst) {
return useFirst ? findRow() : findRowWrapped()
}
async function classifyWrapped() {
const row = await findRowWrapped()
if (row) {
return 'found'
}
return 'missing'
}
async function classifyWrappedTwice() {
const row = await findRowWrappedTwice()
if (row) {
return 'found'
}
return 'missing'
}
// `useFirst` stays an unresolved argument, so the ternary survives analysis instead of
// folding to one branch.
async function classifyConditional(useFirst) {
const row = await findRowConditional(useFirst)
if (row) {
return 'found'
}
return 'missing'
}
it('should not take a guard on an awaited nested promise', async () => {
const row = await findRowWrapped()
expect(row).toBe(null)
if (row) {
throw new Error('guard on an awaited nested promise should not be taken')
}
})
it('should keep the code after a guard that always returns', async () => {
expect(await classifyWrapped()).toBe('missing')
})
it('should collapse more than one level of nesting', async () => {
expect(await findRowWrappedTwice()).toBe(null)
expect(await classifyWrappedTwice()).toBe('missing')
})
it('should collapse promises nested inside branches', async () => {
expect(await findRowConditional(true)).toBe(null)
expect(await findRowConditional(false)).toBe(null)
expect(await classifyConditional(true)).toBe('missing')
expect(await classifyConditional(false)).toBe('missing')
})
it('should still treat an un-awaited promise as truthy', async () => {
const promise = findRowWrapped()
let taken = false
if (promise) {
taken = true
}
expect(taken).toBe(true)
expect(await promise).toBe(null)
})
// A union of promises with no enclosing async function: `await` has to unwrap each branch.
async function classifyBareAlternatives(useFirst) {
const pending = useFirst ? findRow() : findRowWrapped()
const row = await pending
if (row) {
return 'found'
}
return 'missing'
}
it('should distribute await over a union of promises', async () => {
expect(await classifyBareAlternatives(true)).toBe('missing')
expect(await classifyBareAlternatives(false)).toBe('missing')
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment