promise-all.tq 15.8 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include 'src/builtins/builtins-promise.h'
#include 'src/builtins/builtins-promise-gen.h'

namespace promise {
9 10 11 12 13 14 15 16 17 18 19
const kPromiseBuiltinsPromiseContextLength: constexpr int31
    generates 'PromiseBuiltins::kPromiseContextLength';

// Creates the context used by all Promise.all resolve element closures,
// together with the values array. Since all closures for a single Promise.all
// call use the same context, we need to store the indices for the individual
// closures somewhere else (we put them into the identity hash field of the
// closures), and we also need to have a separate marker for when the closure
// was called already (we slap the native context onto the closure in that
// case to mark it's done).
macro CreatePromiseAllResolveElementContext(implicit context: Context)(
20 21 22 23
    capability: PromiseCapability,
    nativeContext: NativeContext): PromiseAllResolveElementContext {
  const resolveContext = %RawDownCast<
      PromiseAllResolveElementContext>(AllocateSyntheticFunctionContext(
24
      nativeContext,
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
      PromiseAllResolveElementContextSlots::kPromiseAllResolveElementLength));
  InitContextSlot(
      resolveContext,
      PromiseAllResolveElementContextSlots::
          kPromiseAllResolveElementRemainingSlot,
      1);
  InitContextSlot(
      resolveContext,
      PromiseAllResolveElementContextSlots::
          kPromiseAllResolveElementCapabilitySlot,
      capability);
  InitContextSlot(
      resolveContext,
      PromiseAllResolveElementContextSlots::kPromiseAllResolveElementValuesSlot,
      kEmptyFixedArray);
40 41
  return resolveContext;
}
42

43
macro CreatePromiseAllResolveElementFunction(implicit context: Context)(
44 45
    resolveElementContext: PromiseAllResolveElementContext, index: Smi,
    nativeContext: NativeContext,
46 47 48 49
    resolveFunction: SharedFunctionInfo): JSFunction {
  assert(index > 0);
  assert(index < kPropertyArrayHashFieldMax);

50 51
  const map = *ContextSlot(
      nativeContext, ContextSlot::STRICT_FUNCTION_WITHOUT_PROTOTYPE_MAP_INDEX);
52 53 54 55 56 57 58
  const resolve = AllocateFunctionWithMapAndContext(
      map, resolveFunction, resolveElementContext);

  assert(kPropertyArrayNoHashSentinel == 0);
  resolve.properties_or_hash = index;
  return resolve;
}
59

60 61
@export
macro CreatePromiseResolvingFunctionsContext(implicit context: Context)(
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    promise: JSPromise, debugEvent: Boolean, nativeContext: NativeContext):
    PromiseResolvingFunctionContext {
  const resolveContext = %RawDownCast<PromiseResolvingFunctionContext>(
      AllocateSyntheticFunctionContext(
          nativeContext,
          PromiseResolvingFunctionContextSlot::kPromiseContextLength));
  InitContextSlot(
      resolveContext, PromiseResolvingFunctionContextSlot::kPromiseSlot,
      promise);
  InitContextSlot(
      resolveContext, PromiseResolvingFunctionContextSlot::kAlreadyResolvedSlot,
      False);
  InitContextSlot(
      resolveContext, PromiseResolvingFunctionContextSlot::kDebugEventSlot,
      debugEvent);
  static_assert(
      PromiseResolvingFunctionContextSlot::kPromiseContextLength ==
      ContextSlot::MIN_CONTEXT_SLOTS + 3);
80 81
  return resolveContext;
}
82

83 84 85 86
macro IsPromiseThenLookupChainIntact(implicit context: Context)(
    nativeContext: NativeContext, receiverMap: Map): bool {
  if (IsForceSlowPath()) return false;
  if (!IsJSPromiseMap(receiverMap)) return false;
87 88
  if (receiverMap.prototype != *NativeContextSlot(
          nativeContext, ContextSlot::PROMISE_PROTOTYPE_INDEX)) {
89
    return false;
90
  }
91 92
  return !IsPromiseThenProtectorCellInvalid();
}
93

94 95
struct PromiseAllResolveElementFunctor {
  macro Call(implicit context: Context)(
96 97
      resolveElementContext: PromiseAllResolveElementContext,
      nativeContext: NativeContext, index: Smi,
98 99 100 101
      _capability: PromiseCapability): Callable {
    return CreatePromiseAllResolveElementFunction(
        resolveElementContext, index, nativeContext,
        PromiseAllResolveElementSharedFunConstant());
102
  }
103
}
104

105 106
struct PromiseAllRejectElementFunctor {
  macro Call(implicit context: Context)(
107 108 109
      _resolveElementContext: PromiseAllResolveElementContext,
      _nativeContext: NativeContext, _index: Smi,
      capability: PromiseCapability): Callable {
110
    return UnsafeCast<Callable>(capability.reject);
111
  }
112
}
113

114 115
struct PromiseAllSettledResolveElementFunctor {
  macro Call(implicit context: Context)(
116 117
      resolveElementContext: PromiseAllResolveElementContext,
      nativeContext: NativeContext, index: Smi,
118 119 120 121
      _capability: PromiseCapability): Callable {
    return CreatePromiseAllResolveElementFunction(
        resolveElementContext, index, nativeContext,
        PromiseAllSettledResolveElementSharedFunConstant());
122
  }
123
}
124

125 126
struct PromiseAllSettledRejectElementFunctor {
  macro Call(implicit context: Context)(
127 128
      resolveElementContext: PromiseAllResolveElementContext,
      nativeContext: NativeContext, index: Smi,
129 130 131 132
      _capability: PromiseCapability): Callable {
    return CreatePromiseAllResolveElementFunction(
        resolveElementContext, index, nativeContext,
        PromiseAllSettledRejectElementSharedFunConstant());
133
  }
134
}
135

136 137
transitioning macro PerformPromiseAll<F1: type, F2: type>(
    implicit context: Context)(
138 139 140
    nativeContext: NativeContext, iter: iterator::IteratorRecord,
    constructor: Constructor, capability: PromiseCapability,
    promiseResolveFunction: JSAny, createResolveElementFunctor: F1,
141 142 143 144 145 146 147 148 149 150 151
    createRejectElementFunctor: F2): JSAny labels
Reject(Object) {
  const promise = capability.promise;
  const resolve = capability.resolve;
  const reject = capability.reject;

  // For catch prediction, don't treat the .then calls as handling it;
  // instead, recurse outwards.
  if (IsDebugActive()) deferred {
      SetPropertyStrict(context, reject, kPromiseForwardingHandlerSymbol, True);
    }
152

153 154
  const resolveElementContext =
      CreatePromiseAllResolveElementContext(capability, nativeContext);
155

156
  let index: Smi = 1;
157

158
  try {
159 160
    const fastIteratorResultMap = *NativeContextSlot(
        nativeContext, ContextSlot::ITERATOR_RESULT_MAP_INDEX);
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    while (true) {
      let nextValue: JSAny;
      try {
        // Let next be IteratorStep(iteratorRecord.[[Iterator]]).
        // If next is an abrupt completion, set iteratorRecord.[[Done]] to
        // true. ReturnIfAbrupt(next).
        const next: JSReceiver = iterator::IteratorStep(
            iter, fastIteratorResultMap) otherwise goto Done;

        // Let nextValue be IteratorValue(next).
        // If nextValue is an abrupt completion, set iteratorRecord.[[Done]]
        // to true.
        // ReturnIfAbrupt(nextValue).
        nextValue = iterator::IteratorValue(next, fastIteratorResultMap);
      } catch (e) {
        goto Reject(e);
177 178
      }

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
      // Check if we reached the limit.
      if (index == kPropertyArrayHashFieldMax) {
        // If there are too many elements (currently more than 2**21-1),
        // raise a RangeError here (which is caught below and turned into
        // a rejection of the resulting promise). We could gracefully handle
        // this case as well and support more than this number of elements
        // by going to a separate function and pass the larger indices via a
        // separate context, but it doesn't seem likely that we need this,
        // and it's unclear how the rest of the system deals with 2**21 live
        // Promises anyway.
        ThrowRangeError(
            MessageTemplate::kTooManyElementsInPromiseCombinator, 'all');
      }

      // Set remainingElementsCount.[[Value]] to
      //     remainingElementsCount.[[Value]] + 1.
195 196 197 198
      *ContextSlot(
          resolveElementContext,
          PromiseAllResolveElementContextSlots::
              kPromiseAllResolveElementRemainingSlot) += 1;
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

      // Let resolveElement be CreateBuiltinFunction(steps,
      //                                             « [[AlreadyCalled]],
      //                                               [[Index]],
      //                                               [[Values]],
      //                                               [[Capability]],
      //                                               [[RemainingElements]]
      //                                               »).
      // Set resolveElement.[[AlreadyCalled]] to a Record { [[Value]]: false
      // }. Set resolveElement.[[Index]] to index. Set
      // resolveElement.[[Values]] to values. Set
      // resolveElement.[[Capability]] to resultCapability. Set
      // resolveElement.[[RemainingElements]] to remainingElementsCount.
      const resolveElementFun = createResolveElementFunctor.Call(
          resolveElementContext, nativeContext, index, capability);
      const rejectElementFun = createRejectElementFunctor.Call(
          resolveElementContext, nativeContext, index, capability);

      // We can skip the "then" lookup on the result of the "resolve" call and
      // immediately chain the continuation onto the {next_value} if:
      //
      //   (a) The {constructor} is the intrinsic %Promise% function, and
      //       looking up "resolve" on {constructor} yields the initial
      //       Promise.resolve() builtin, and
      //   (b) the promise @@species protector cell is valid, meaning that
      //       no one messed with the Symbol.species property on any
      //       intrinsic promise or on the Promise.prototype, and
      //   (c) the {next_value} is a JSPromise whose [[Prototype]] field
      //       contains the intrinsic %PromisePrototype%, and
      //   (d) we're not running with async_hooks or DevTools enabled.
      //
      // In that case we also don't need to allocate a chained promise for
      // the PromiseReaction (aka we can pass undefined to
      // PerformPromiseThen), since this is only necessary for DevTools and
      // PromiseHooks.
      if (promiseResolveFunction != Undefined ||
          IsPromiseHookEnabledOrDebugIsActiveOrHasAsyncEventDelegate() ||
          IsPromiseSpeciesProtectorCellInvalid() || Is<Smi>(nextValue) ||
          !IsPromiseThenLookupChainIntact(
              nativeContext, UnsafeCast<HeapObject>(nextValue).map)) {
        // Let nextPromise be ? Call(constructor, _promiseResolve_, «
        // nextValue »).
        const nextPromise =
            CallResolve(constructor, promiseResolveFunction, nextValue);

        // Perform ? Invoke(nextPromise, "then", « resolveElement,
        //                  resultCapability.[[Reject]] »).
        const then = GetProperty(nextPromise, kThenString);
        const thenResult = Call(
            nativeContext, then, nextPromise, resolveElementFun,
            rejectElementFun);

        // For catch prediction, mark that rejections here are
        // semantically handled by the combined Promise.
        if (IsDebugActive() && Is<JSPromise>(thenResult)) deferred {
            SetPropertyStrict(
                context, thenResult, kPromiseHandledBySymbol, promise);
          }
      } else {
        PerformPromiseThenImpl(
            UnsafeCast<JSPromise>(nextValue), resolveElementFun,
            rejectElementFun, Undefined);
261
      }
262 263 264

      // Set index to index + 1.
      index += 1;
265
    }
266 267 268
  } catch (e) deferred {
    iterator::IteratorCloseOnException(iter);
    goto Reject(e);
269 270 271 272 273
  } label Done {}

  // Set iteratorRecord.[[Done]] to true.
  // Set remainingElementsCount.[[Value]] to
  //    remainingElementsCount.[[Value]] - 1.
274 275 276 277 278
  const remainingElementsCount = -- *ContextSlot(
      resolveElementContext,
      PromiseAllResolveElementContextSlots::
          kPromiseAllResolveElementRemainingSlot);

279 280
  check(remainingElementsCount >= 0);

281
  if (remainingElementsCount > 0) {
282 283 284
    // Pre-allocate the backing store for the {values} to the desired
    // capacity. We may already have elements in "values" - this happens
    // when the Thenable calls the resolve callback immediately.
285 286 287 288 289
    const valuesRef:&FixedArray = ContextSlot(
        resolveElementContext,
        PromiseAllResolveElementContextSlots::
            kPromiseAllResolveElementValuesSlot);
    const values = *valuesRef;
290 291 292 293 294
    // 'index' is a 1-based index and incremented after every Promise. Later we
    // use 'values' as a 0-based array, so capacity 'index - 1' is enough.
    const newCapacity = SmiUntag(index) - 1;

    const oldCapacity = values.length_intptr;
295
    if (oldCapacity < newCapacity) {
296
      *valuesRef = ExtractFixedArray(values, 0, oldCapacity, newCapacity);
297 298 299 300 301 302 303
    }
  } else
    deferred {
      // If remainingElementsCount.[[Value]] is 0, then
      //     Let valuesArray be CreateArrayFromList(values).
      //     Perform ? Call(resultCapability.[[Resolve]], undefined,
      //                    « valuesArray »).
304

305 306 307 308 309 310 311
      const values: FixedArray = *ContextSlot(
          resolveElementContext,
          PromiseAllResolveElementContextSlots::
              kPromiseAllResolveElementValuesSlot);
      const arrayMap =
          *NativeContextSlot(
          nativeContext, ContextSlot::JS_ARRAY_PACKED_ELEMENTS_MAP_INDEX);
312
      const valuesArray = NewJSArray(arrayMap, values);
313 314
      Call(nativeContext, UnsafeCast<JSAny>(resolve), Undefined, valuesArray);
    }
315

316 317 318
  // Return resultCapability.[[Promise]].
  return promise;
}
319

320 321 322 323
transitioning macro GeneratePromiseAll<F1: type, F2: type>(
    implicit context: Context)(
    receiver: JSAny, iterable: JSAny, createResolveElementFunctor: F1,
    createRejectElementFunctor: F2): JSAny {
324
  const nativeContext = LoadNativeContext(context);
325 326 327 328 329 330 331 332 333 334
  // Let C be the this value.
  // If Type(C) is not Object, throw a TypeError exception.
  const receiver = Cast<JSReceiver>(receiver)
      otherwise ThrowTypeError(MessageTemplate::kCalledOnNonObject, 'Promise.all');

  // Let promiseCapability be ? NewPromiseCapability(C).
  // Don't fire debugEvent so that forwarding the rejection through all does
  // not trigger redundant ExceptionEvents
  const capability = NewPromiseCapability(receiver, False);

335 336 337 338
  // NewPromiseCapability guarantees that receiver is Constructor.
  assert(Is<Constructor>(receiver));
  const constructor = UnsafeCast<Constructor>(receiver);

339
  try {
340 341 342 343 344
    // Let promiseResolve be GetPromiseResolve(C).
    // IfAbruptRejectPromise(promiseResolve, promiseCapability).
    const promiseResolveFunction =
        GetPromiseResolve(nativeContext, constructor);

345 346 347 348 349 350 351 352 353 354
    // Let iterator be GetIterator(iterable).
    // IfAbruptRejectPromise(iterator, promiseCapability).
    let i = iterator::GetIterator(iterable);

    // Let result be PerformPromiseAll(iteratorRecord, C,
    // promiseCapability). If result is an abrupt completion, then
    //   If iteratorRecord.[[Done]] is false, let result be
    //       IteratorClose(iterator, result).
    //    IfAbruptRejectPromise(result, promiseCapability).
    return PerformPromiseAll(
355 356 357
        nativeContext, i, constructor, capability, promiseResolveFunction,
        createResolveElementFunctor, createRejectElementFunctor)
        otherwise Reject;
358 359 360 361 362 363 364 365
  } catch (e) deferred {
    goto Reject(e);
  } label Reject(e: Object) deferred {
    // Exception must be bound to a JS value.
    const e = UnsafeCast<JSAny>(e);
    const reject = UnsafeCast<JSAny>(capability.reject);
    Call(context, reject, Undefined, e);
    return capability.promise;
366
  }
367
}
368

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
// ES#sec-promise.all
transitioning javascript builtin PromiseAll(
    js-implicit context: Context, receiver: JSAny)(iterable: JSAny): JSAny {
  return GeneratePromiseAll(
      receiver, iterable, PromiseAllResolveElementFunctor{},
      PromiseAllRejectElementFunctor{});
}

// ES#sec-promise.allsettled
// Promise.allSettled ( iterable )
transitioning javascript builtin PromiseAllSettled(
    js-implicit context: Context, receiver: JSAny)(iterable: JSAny): JSAny {
  return GeneratePromiseAll(
      receiver, iterable, PromiseAllSettledResolveElementFunctor{},
      PromiseAllSettledRejectElementFunctor{});
}
385

386 387 388 389 390
extern macro PromiseAllResolveElementSharedFunConstant(): SharedFunctionInfo;
extern macro PromiseAllSettledRejectElementSharedFunConstant():
    SharedFunctionInfo;
extern macro PromiseAllSettledResolveElementSharedFunConstant():
    SharedFunctionInfo;
391
}