promise-any.tq 14.3 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2020 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-gen.h'

namespace promise {
8 9 10 11
extern enum PromiseAnyRejectElementContextSlots extends int31
constexpr 'PromiseBuiltins::PromiseAnyRejectElementContextSlots' {
  kPromiseAnyRejectElementRemainingSlot,
  kPromiseAnyRejectElementCapabilitySlot,
12
  kPromiseAnyRejectElementErrorsSlot,
13 14
  kPromiseAnyRejectElementLength
}
15

16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
extern operator '[]=' macro StoreContextElement(
    Context, constexpr PromiseAnyRejectElementContextSlots, Object): void;
extern operator '[]' macro LoadContextElement(
    Context, constexpr PromiseAnyRejectElementContextSlots): Object;

// Creates the context used by all Promise.any reject element closures,
// together with the errors array. Since all closures for a single Promise.any
// 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). See Promise.all which uses the same approach.
transitioning macro CreatePromiseAnyRejectElementContext(
    implicit context: Context)(
    capability: PromiseCapability, nativeContext: NativeContext): Context {
  const rejectContext = AllocateSyntheticFunctionContext(
      nativeContext,
      PromiseAnyRejectElementContextSlots::kPromiseAnyRejectElementLength);
  rejectContext[PromiseAnyRejectElementContextSlots::
                    kPromiseAnyRejectElementRemainingSlot] = SmiConstant(1);
  rejectContext[PromiseAnyRejectElementContextSlots::
                    kPromiseAnyRejectElementCapabilitySlot] = capability;
  rejectContext[PromiseAnyRejectElementContextSlots::
39
                    kPromiseAnyRejectElementErrorsSlot] = kEmptyFixedArray;
40 41
  return rejectContext;
}
42

43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
macro CreatePromiseAnyRejectElementFunction(implicit context: Context)(
    rejectElementContext: Context, index: Smi,
    nativeContext: NativeContext): JSFunction {
  assert(index > 0);
  assert(index < kPropertyArrayHashFieldMax);
  const map = UnsafeCast<Map>(
      nativeContext
          [NativeContextSlot::STRICT_FUNCTION_WITHOUT_PROTOTYPE_MAP_INDEX]);
  const rejectInfo = PromiseAnyRejectElementSharedFunConstant();
  const reject =
      AllocateFunctionWithMapAndContext(map, rejectInfo, rejectElementContext);
  assert(kPropertyArrayNoHashSentinel == 0);
  reject.properties_or_hash = index;
  return reject;
}
58

59 60 61 62 63 64
// https://tc39.es/proposal-promise-any/#sec-promise.any-reject-element-functions
transitioning javascript builtin
PromiseAnyRejectElementClosure(
    js-implicit context: Context, receiver: JSAny,
    target: JSFunction)(value: JSAny): JSAny {
  // 1. Let F be the active function object.
65

66
  // 2. Let alreadyCalled be F.[[AlreadyCalled]].
67

68
  // 3. If alreadyCalled.[[Value]] is true, return undefined.
69

70 71 72 73 74 75
  // We use the function's context as the marker to remember whether this
  // reject element closure was already called. It points to the reject
  // element context (which is a FunctionContext) until it was called the
  // first time, in which case we make it point to the native context here
  // to mark this reject element closure as done.
  if (IsNativeContext(context)) deferred {
76 77 78
      return Undefined;
    }

79 80 81 82 83 84 85 86 87 88 89 90 91 92
  assert(
      context.length ==
      PromiseAnyRejectElementContextSlots::kPromiseAnyRejectElementLength);

  // 4. Set alreadyCalled.[[Value]] to true.
  const nativeContext = LoadNativeContext(context);
  target.context = nativeContext;

  // 5. Let index be F.[[Index]].
  assert(kPropertyArrayNoHashSentinel == 0);
  const identityHash = LoadJSReceiverIdentityHash(target) otherwise unreachable;
  assert(identityHash > 0);
  const index = identityHash - 1;

93 94 95 96 97
  // 6. Let errors be F.[[Errors]].
  let errors =
      UnsafeCast<FixedArray>(context[PromiseAnyRejectElementContextSlots::
                                         kPromiseAnyRejectElementErrorsSlot]);

98 99 100 101 102 103
  // 7. Let promiseCapability be F.[[Capability]].

  // 8. Let remainingElementsCount be F.[[RemainingElements]].
  let remainingElementsCount =
      UnsafeCast<Smi>(context[PromiseAnyRejectElementContextSlots::
                                  kPromiseAnyRejectElementRemainingSlot]);
104

105
  // 9. Set errors[index] to x.
106 107 108 109 110 111 112
  const newCapacity = IntPtrMax(SmiUntag(remainingElementsCount), index + 1);
  if (newCapacity > errors.length_intptr) deferred {
      errors = ExtractFixedArray(errors, 0, errors.length_intptr, newCapacity);
      context[PromiseAnyRejectElementContextSlots::
                  kPromiseAnyRejectElementErrorsSlot] = errors;
    }
  errors.objects[index] = value;
113 114 115 116 117 118 119 120 121 122 123 124

  // 10. Set remainingElementsCount.[[Value]] to
  // remainingElementsCount.[[Value]] - 1.
  remainingElementsCount = remainingElementsCount - 1;
  context[PromiseAnyRejectElementContextSlots::
              kPromiseAnyRejectElementRemainingSlot] = remainingElementsCount;

  // 11. If remainingElementsCount.[[Value]] is 0, then
  if (remainingElementsCount == 0) {
    //   a. Let error be a newly created AggregateError object.

    //   b. Set error.[[AggregateErrors]] to errors.
125
    const error = ConstructAggregateError(errors);
126 127 128 129 130 131
    //   c. Return ? Call(promiseCapability.[[Reject]], undefined, « error »).
    const capability = UnsafeCast<PromiseCapability>(
        context[PromiseAnyRejectElementContextSlots::
                    kPromiseAnyRejectElementCapabilitySlot]);
    Call(context, UnsafeCast<Callable>(capability.reject), Undefined, error);
  }
132

133 134 135
  // 12. Return undefined.
  return Undefined;
}
136

137
transitioning macro PerformPromiseAny(implicit context: Context)(
138 139 140
    nativeContext: NativeContext, iteratorRecord: iterator::IteratorRecord,
    constructor: Constructor, resultCapability: PromiseCapability,
    promiseResolveFunction: JSAny): JSAny labels
141 142 143 144
Reject(Object) {
  // 1. Assert: ! IsConstructor(constructor) is true.
  // 2. Assert: resultCapability is a PromiseCapability Record.

145 146
  // 3. Let errors be a new empty List. (Do nothing: errors is
  // initialized lazily when the first Promise rejects.)
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163

  // 4. Let remainingElementsCount be a new Record { [[Value]]: 1 }.
  const rejectElementContext =
      CreatePromiseAnyRejectElementContext(resultCapability, nativeContext);

  // 5. Let index be 0.
  //    (We subtract 1 in the PromiseAnyRejectElementClosure).
  let index: Smi = 1;

  try {
    const fastIteratorResultMap = UnsafeCast<Map>(
        nativeContext[NativeContextSlot::ITERATOR_RESULT_MAP_INDEX]);
    // 8. Repeat,
    while (true) {
      let nextValue: JSAny;
      try {
        // a. Let next be IteratorStep(iteratorRecord).
164

165 166
        // b. If next is an abrupt completion, set
        // iteratorRecord.[[Done]] to true.
167

168
        // c. ReturnIfAbrupt(next).
169

170 171 172 173
        // d. if next is false, then [continues below in "Done"]
        const next: JSReceiver = iterator::IteratorStep(
            iteratorRecord, fastIteratorResultMap) otherwise goto Done;
        // e. Let nextValue be IteratorValue(next).
174

175 176
        // f. If nextValue is an abrupt completion, set
        // iteratorRecord.[[Done]] to true.
177

178 179 180 181
        // g. ReturnIfAbrupt(nextValue).
        nextValue = iterator::IteratorValue(next, fastIteratorResultMap);
      } catch (e) {
        goto Reject(e);
182
      }
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

      // We store the indices as identity hash on the reject element
      // closures. Thus, we need this limit.
      if (index == kPropertyArrayHashFieldMax) {
        // If there are too many elements (currently more than
        // 2**21-1), raise a RangeError here (which is caught later 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, 'any');
198 199
      }

200 201
      // h. Append undefined to errors. (Do nothing: errors is initialized
      // lazily when the first Promise rejects.)
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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

      let nextPromise: JSAny;
      // i. Let nextPromise be ? Call(constructor, promiseResolve,
      // «nextValue »).
      nextPromise = CallResolve(constructor, promiseResolveFunction, nextValue);

      // j. Let steps be the algorithm steps defined in Promise.any
      // Reject Element Functions.

      // k. Let rejectElement be ! CreateBuiltinFunction(steps, «
      // [[AlreadyCalled]], [[Index]],
      // [[Errors]], [[Capability]], [[RemainingElements]] »).

      // l. Set rejectElement.[[AlreadyCalled]] to a new Record {
      // [[Value]]: false }.

      // m. Set rejectElement.[[Index]] to index.

      // n. Set rejectElement.[[Errors]] to errors.

      // o. Set rejectElement.[[Capability]] to resultCapability.

      // p. Set rejectElement.[[RemainingElements]] to
      // remainingElementsCount.
      const rejectElement = CreatePromiseAnyRejectElementFunction(
          rejectElementContext, index, nativeContext);
      // q. Set remainingElementsCount.[[Value]] to
      // remainingElementsCount.[[Value]] + 1.
      const remainingElementsCount = UnsafeCast<Smi>(
          rejectElementContext[PromiseAnyRejectElementContextSlots::
                                   kPromiseAnyRejectElementRemainingSlot]);
      rejectElementContext[PromiseAnyRejectElementContextSlots::
                               kPromiseAnyRejectElementRemainingSlot] =
          remainingElementsCount + 1;

      // r. Perform ? Invoke(nextPromise, "then", «
      // resultCapability.[[Resolve]], rejectElement »).
      let thenResult: JSAny;

      const then = GetProperty(nextPromise, kThenString);
      thenResult = Call(
          context, then, nextPromise,
          UnsafeCast<JSAny>(resultCapability.resolve), rejectElement);

      // s. Increase index by 1.
      index += 1;

      // For catch prediction, mark that rejections here are
      // semantically handled by the combined Promise.
      if (IsDebugActive() && Is<JSPromise>(thenResult)) deferred {
          SetPropertyStrict(
              context, thenResult, kPromiseHandledBySymbol,
              resultCapability.promise);
          SetPropertyStrict(
              context, rejectElement, kPromiseForwardingHandlerSymbol, True);
        }
    }
  } catch (e) deferred {
    iterator::IteratorCloseOnException(iteratorRecord);
    goto Reject(e);
  } label Done {}

  // (8.d)
  //   i. Set iteratorRecord.[[Done]] to true.
  //  ii. Set remainingElementsCount.[[Value]] to
  //  remainingElementsCount.[[Value]] - 1.
  let remainingElementsCount = UnsafeCast<Smi>(
      rejectElementContext[PromiseAnyRejectElementContextSlots::
                               kPromiseAnyRejectElementRemainingSlot]);
  remainingElementsCount -= 1;
  rejectElementContext[PromiseAnyRejectElementContextSlots::
                           kPromiseAnyRejectElementRemainingSlot] =
      remainingElementsCount;

  // iii. If remainingElementsCount.[[Value]] is 0, then
  if (remainingElementsCount == 0) deferred {
      // 1. Let error be a newly created AggregateError object.
      // 2. Set error.[[AggregateErrors]] to errors.
280 281 282 283 284 285 286 287

      // We may already have elements in "errors" - this happens when the
      // Thenable calls the reject callback immediately.
      const errors = UnsafeCast<FixedArray>(
          rejectElementContext[PromiseAnyRejectElementContextSlots::
                                   kPromiseAnyRejectElementErrorsSlot]);

      const error = ConstructAggregateError(errors);
288 289 290 291 292 293 294 295 296 297 298
      // 3. Return ThrowCompletion(error).
      goto Reject(error);
    }
  // iv. Return resultCapability.[[Promise]].
  return resultCapability.promise;
}

// https://tc39.es/proposal-promise-any/#sec-promise.any
transitioning javascript builtin
PromiseAny(
    js-implicit context: Context, receiver: JSAny)(iterable: JSAny): JSAny {
299 300
  const nativeContext = LoadNativeContext(context);

301 302 303
  // 1. Let C be the this value.
  const receiver = Cast<JSReceiver>(receiver)
      otherwise ThrowTypeError(MessageTemplate::kCalledOnNonObject, 'Promise.any');
304

305 306
  // 2. Let promiseCapability be ? NewPromiseCapability(C).
  const capability = NewPromiseCapability(receiver, False);
307

308
  // NewPromiseCapability guarantees that receiver is Constructor.
309 310
  assert(Is<Constructor>(receiver));
  const constructor = UnsafeCast<Constructor>(receiver);
311

312
  try {
313 314 315 316 317
    // 3. Let promiseResolve be GetPromiseResolve(C).
    // 4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
    // (catch below)
    const promiseResolveFunction =
        GetPromiseResolve(nativeContext, constructor);
318

319
    // 5. Let iteratorRecord be GetIterator(iterable).
320

321 322 323
    // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
    // (catch below)
    const iteratorRecord = iterator::GetIterator(iterable);
324

325 326
    // 7. Let result be PerformPromiseAny(iteratorRecord, C,
    // promiseCapability).
327

328
    // 8. If result is an abrupt completion, then
329

330 331
    //   a. If iteratorRecord.[[Done]] is false, set result to
    //   IteratorClose(iteratorRecord, result).
332

333
    //   b. IfAbruptRejectPromise(result, promiseCapability).
334

335 336 337 338 339 340 341 342 343
    // [Iterator closing handled by PerformPromiseAny]

    // 9. Return Completion(result).
    return PerformPromiseAny(
        nativeContext, iteratorRecord, constructor, capability,
        promiseResolveFunction)
        otherwise Reject;
  } catch (e) deferred {
    goto Reject(e);
344 345 346 347 348 349 350
  } label Reject(e: Object) deferred {
    // Exception must be bound to a JS value.
    assert(e != TheHole);
    Call(
        context, UnsafeCast<Callable>(capability.reject), Undefined,
        UnsafeCast<JSAny>(e));
    return capability.promise;
351
  }
352
}
353

354
transitioning macro ConstructAggregateError(implicit context: Context)(
355
    errors: FixedArray): JSObject {
356
  const obj: JSObject = error::ConstructInternalAggregateErrorHelper(
357
      context, SmiConstant(MessageTemplate::kAllPromisesRejected));
358
  const errorsJSArray = array::CreateJSArrayWithElements(errors);
359 360 361
  SetOwnPropertyIgnoreAttributes(
      obj, ErrorsStringConstant(), errorsJSArray,
      SmiConstant(PropertyAttributes::DONT_ENUM));
362 363
  return obj;
}
364

365
extern macro PromiseAnyRejectElementSharedFunConstant(): SharedFunctionInfo;
366
}