builtins-async-iterator-gen.cc 13.4 KB
Newer Older
1 2 3 4
// Copyright 2017 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.

5
#include "src/base/optional.h"
6
#include "src/builtins/builtins-async-gen.h"
7
#include "src/builtins/builtins-utils-gen.h"
8
#include "src/builtins/builtins.h"
9 10
#include "src/codegen/code-factory.h"
#include "src/codegen/code-stub-assembler.h"
11
#include "src/execution/frames-inl.h"
12 13 14 15 16 17 18

namespace v8 {
namespace internal {

namespace {
class AsyncFromSyncBuiltinsAssembler : public AsyncBuiltinsAssembler {
 public:
19 20 21 22
  // The 'next' and 'return' take an optional value parameter, and the 'throw'
  // method take an optional reason parameter.
  static const int kValueOrReasonArg = 0;

23
  explicit AsyncFromSyncBuiltinsAssembler(compiler::CodeAssemblerState* state)
24 25
      : AsyncBuiltinsAssembler(state) {}

26 27
  void ThrowIfNotAsyncFromSyncIterator(const TNode<Context> context,
                                       const TNode<Object> object,
28
                                       Label* if_exception,
29
                                       TVariable<Object>* var_exception,
30 31
                                       const char* method_name);

32 33 34 35 36
  using UndefinedMethodHandler =
      std::function<void(const TNode<NativeContext> native_context,
                         const TNode<JSPromise> promise, Label* if_exception)>;
  using SyncIteratorNodeGenerator =
      std::function<TNode<Object>(TNode<JSReceiver>)>;
37
  void Generate_AsyncFromSyncIteratorMethod(
38 39
      CodeStubArguments* args, const TNode<Context> context,
      const TNode<Object> iterator, const TNode<Object> sent_value,
40 41
      const SyncIteratorNodeGenerator& get_method,
      const UndefinedMethodHandler& if_method_undefined,
42 43
      const char* operation_name,
      Label::Type reject_label_type = Label::kDeferred,
44
      base::Optional<TNode<Object>> initial_exception_value = base::nullopt);
45

46
  void Generate_AsyncFromSyncIteratorMethod(
47 48 49
      CodeStubArguments* args, const TNode<Context> context,
      const TNode<Object> iterator, const TNode<Object> sent_value,
      Handle<String> name, const UndefinedMethodHandler& if_method_undefined,
50 51
      const char* operation_name,
      Label::Type reject_label_type = Label::kDeferred,
52 53
      base::Optional<TNode<Object>> initial_exception_value = base::nullopt) {
    auto get_method = [=](const TNode<JSReceiver> sync_iterator) {
54 55 56
      return GetProperty(context, sync_iterator, name);
    };
    return Generate_AsyncFromSyncIteratorMethod(
57
        args, context, iterator, sent_value, get_method, if_method_undefined,
58 59 60
        operation_name, reject_label_type, initial_exception_value);
  }

61
  // Load "value" and "done" from an iterator result object. If an exception
62
  // is thrown at any point, jumps to the `if_exception` label with exception
63 64 65 66 67
  // stored in `var_exception`.
  //
  // Returns a Pair of Nodes, whose first element is the value of the "value"
  // property, and whose second element is the value of the "done" property,
  // converted to a Boolean if needed.
68 69 70 71
  std::pair<TNode<Object>, TNode<Oddball>> LoadIteratorResult(
      const TNode<Context> context, const TNode<NativeContext> native_context,
      const TNode<Object> iter_result, Label* if_exception,
      TVariable<Object>* var_exception);
72 73 74
};

void AsyncFromSyncBuiltinsAssembler::ThrowIfNotAsyncFromSyncIterator(
75 76 77
    const TNode<Context> context, const TNode<Object> object,
    Label* if_exception, TVariable<Object>* var_exception,
    const char* method_name) {
78 79 80
  Label if_receiverisincompatible(this, Label::kDeferred), done(this);

  GotoIf(TaggedIsSmi(object), &if_receiverisincompatible);
81
  Branch(HasInstanceType(CAST(object), JS_ASYNC_FROM_SYNC_ITERATOR_TYPE), &done,
82 83
         &if_receiverisincompatible);

84
  BIND(&if_receiverisincompatible);
85 86 87 88 89
  {
    // If Type(O) is not Object, or if O does not have a [[SyncIterator]]
    // internal slot, then

    // Let badIteratorError be a new TypeError exception.
90
    TNode<HeapObject> error =
91 92
        MakeTypeError(MessageTemplate::kIncompatibleMethodReceiver, context,
                      StringConstant(method_name), object);
93 94 95

    // Perform ! Call(promiseCapability.[[Reject]], undefined,
    //                « badIteratorError »).
96
    *var_exception = error;
97 98 99
    Goto(if_exception);
  }

100
  BIND(&done);
101 102 103
}

void AsyncFromSyncBuiltinsAssembler::Generate_AsyncFromSyncIteratorMethod(
104 105 106
    CodeStubArguments* args, const TNode<Context> context,
    const TNode<Object> iterator, const TNode<Object> sent_value,
    const SyncIteratorNodeGenerator& get_method,
107
    const UndefinedMethodHandler& if_method_undefined,
108
    const char* operation_name, Label::Type reject_label_type,
109 110
    base::Optional<TNode<Object>> initial_exception_value) {
  const TNode<NativeContext> native_context = LoadNativeContext(context);
111
  const TNode<JSPromise> promise = NewJSPromise(context);
112

113 114 115
  TVARIABLE(
      Object, var_exception,
      initial_exception_value ? *initial_exception_value : UndefinedConstant());
116 117 118 119 120
  Label reject_promise(this, reject_label_type);

  ThrowIfNotAsyncFromSyncIterator(context, iterator, &reject_promise,
                                  &var_exception, operation_name);

121 122 123
  TNode<JSAsyncFromSyncIterator> async_iterator = CAST(iterator);
  const TNode<JSReceiver> sync_iterator = LoadObjectField<JSReceiver>(
      async_iterator, JSAsyncFromSyncIterator::kSyncIteratorOffset);
124

125
  TNode<Object> method = get_method(sync_iterator);
126 127 128 129

  if (if_method_undefined) {
    Label if_isnotundefined(this);

130
    GotoIfNot(IsNullOrUndefined(method), &if_isnotundefined);
131 132
    if_method_undefined(native_context, promise, &reject_promise);

133
    BIND(&if_isnotundefined);
134 135
  }

136
  TVARIABLE(Object, iter_result);
137
  {
138
    Label has_sent_value(this), no_sent_value(this), merge(this);
139
    ScopedExceptionHandler handler(this, &reject_promise, &var_exception);
140 141 142 143 144 145 146 147 148 149 150 151 152 153
    Branch(
        IntPtrGreaterThan(args->GetLength(), IntPtrConstant(kValueOrReasonArg)),
        &has_sent_value, &no_sent_value);
    BIND(&has_sent_value);
    {
      iter_result = Call(context, method, sync_iterator, sent_value);
      Goto(&merge);
    }
    BIND(&no_sent_value);
    {
      iter_result = Call(context, method, sync_iterator);
      Goto(&merge);
    }
    BIND(&merge);
154
  }
155

156 157
  TNode<Object> value;
  TNode<Oddball> done;
158 159 160
  std::tie(value, done) =
      LoadIteratorResult(context, native_context, iter_result.value(),
                         &reject_promise, &var_exception);
161

162
  const TNode<JSFunction> promise_fun =
163
      CAST(LoadContextElement(native_context, Context::PROMISE_FUNCTION_INDEX));
164 165
  CSA_ASSERT(this, IsConstructor(promise_fun));

166 167
  // Let valueWrapper be PromiseResolve(%Promise%, « value »).
  // IfAbruptRejectPromise(valueWrapper, promiseCapability).
168 169 170 171 172 173
  TNode<Object> value_wrapper;
  {
    ScopedExceptionHandler handler(this, &reject_promise, &var_exception);
    value_wrapper = CallBuiltin(Builtins::kPromiseResolve, native_context,
                                promise_fun, value);
  }
174 175 176 177

  // Let onFulfilled be a new built-in function object as defined in
  // Async Iterator Value Unwrap Functions.
  // Set onFulfilled.[[Done]] to throwDone.
178 179
  const TNode<JSFunction> on_fulfilled =
      CreateUnwrapClosure(native_context, done);
180 181 182

  // Perform ! PerformPromiseThen(valueWrapper,
  //     onFulfilled, undefined, promiseCapability).
183 184 185
  args->PopAndReturn(CallBuiltin(Builtins::kPerformPromiseThen, context,
                                 value_wrapper, on_fulfilled,
                                 UndefinedConstant(), promise));
186 187 188

  BIND(&reject_promise);
  {
189
    const TNode<Object> exception = var_exception.value();
190 191
    CallBuiltin(Builtins::kRejectPromise, context, promise, exception,
                TrueConstant());
192
    args->PopAndReturn(promise);
193 194
  }
}
195 196 197 198 199 200

std::pair<TNode<Object>, TNode<Oddball>>
AsyncFromSyncBuiltinsAssembler::LoadIteratorResult(
    const TNode<Context> context, const TNode<NativeContext> native_context,
    const TNode<Object> iter_result, Label* if_exception,
    TVariable<Object>* var_exception) {
201 202 203 204
  Label if_fastpath(this), if_slowpath(this), merge(this), to_boolean(this),
      done(this), if_notanobject(this, Label::kDeferred);
  GotoIf(TaggedIsSmi(iter_result), &if_notanobject);

205
  const TNode<Map> iter_result_map = LoadMap(CAST(iter_result));
206 207
  GotoIfNot(IsJSReceiverMap(iter_result_map), &if_notanobject);

208
  const TNode<Object> fast_iter_result_map =
209 210
      LoadContextElement(native_context, Context::ITERATOR_RESULT_MAP_INDEX);

211 212
  TVARIABLE(Object, var_value);
  TVARIABLE(Object, var_done);
213
  Branch(TaggedEqual(iter_result_map, fast_iter_result_map), &if_fastpath,
214 215
         &if_slowpath);

216
  BIND(&if_fastpath);
217
  {
218 219 220 221
    TNode<JSObject> fast_iter_result = CAST(iter_result);
    var_done = LoadObjectField(fast_iter_result, JSIteratorResult::kDoneOffset);
    var_value =
        LoadObjectField(fast_iter_result, JSIteratorResult::kValueOffset);
222 223 224
    Goto(&merge);
  }

225
  BIND(&if_slowpath);
226
  {
227 228
    ScopedExceptionHandler handler(this, if_exception, var_exception);

229 230
    // Let nextDone be IteratorComplete(nextResult).
    // IfAbruptRejectPromise(nextDone, promiseCapability).
231
    const TNode<Object> done =
232 233
        GetProperty(context, iter_result, factory()->done_string());

234 235
    // Let nextValue be IteratorValue(nextResult).
    // IfAbruptRejectPromise(nextValue, promiseCapability).
236
    const TNode<Object> value =
237 238
        GetProperty(context, iter_result, factory()->value_string());

239 240
    var_value = value;
    var_done = done;
241 242 243
    Goto(&merge);
  }

244
  BIND(&if_notanobject);
245 246 247
  {
    // Sync iterator result is not an object --- Produce a TypeError and jump
    // to the `if_exception` path.
248 249
    const TNode<Object> error = MakeTypeError(
        MessageTemplate::kIteratorResultNotAnObject, context, iter_result);
250
    *var_exception = error;
251 252 253
    Goto(if_exception);
  }

254
  BIND(&merge);
255 256
  // Ensure `iterResult.done` is a Boolean.
  GotoIf(TaggedIsSmi(var_done.value()), &to_boolean);
257
  Branch(IsBoolean(CAST(var_done.value())), &done, &to_boolean);
258

259
  BIND(&to_boolean);
260
  {
261
    const TNode<Object> result =
262
        CallBuiltin(Builtins::kToBoolean, context, var_done.value());
263
    var_done = result;
264 265 266
    Goto(&done);
  }

267
  BIND(&done);
268
  return std::make_pair(var_value.value(), CAST(var_done.value()));
269
}
270

271 272 273 274 275
}  // namespace

// https://tc39.github.io/proposal-async-iteration/
// Section #sec-%asyncfromsynciteratorprototype%.next
TF_BUILTIN(AsyncFromSyncIteratorPrototypeNext, AsyncFromSyncBuiltinsAssembler) {
276
  TNode<IntPtrT> argc = ChangeInt32ToIntPtr(
277
      UncheckedParameter<Int32T>(Descriptor::kJSActualArgumentsCount));
278 279 280 281
  CodeStubArguments args(this, argc);

  const TNode<Object> iterator = args.GetReceiver();
  const TNode<Object> value = args.GetOptionalArgumentValue(kValueOrReasonArg);
282
  const auto context = Parameter<Context>(Descriptor::kContext);
283

284 285 286
  auto get_method = [=](const TNode<JSReceiver> unused) {
    return LoadObjectField(CAST(iterator),
                           JSAsyncFromSyncIterator::kNextOffset);
287
  };
288
  Generate_AsyncFromSyncIteratorMethod(
289
      &args, context, iterator, value, get_method, UndefinedMethodHandler(),
290
      "[Async-from-Sync Iterator].prototype.next");
291 292 293 294 295 296
}

// https://tc39.github.io/proposal-async-iteration/
// Section #sec-%asyncfromsynciteratorprototype%.return
TF_BUILTIN(AsyncFromSyncIteratorPrototypeReturn,
           AsyncFromSyncBuiltinsAssembler) {
297
  TNode<IntPtrT> argc = ChangeInt32ToIntPtr(
298
      UncheckedParameter<Int32T>(Descriptor::kJSActualArgumentsCount));
299 300 301 302
  CodeStubArguments args(this, argc);

  const TNode<Object> iterator = args.GetReceiver();
  const TNode<Object> value = args.GetOptionalArgumentValue(kValueOrReasonArg);
303
  const auto context = Parameter<Context>(Descriptor::kContext);
304

305 306
  auto if_return_undefined = [=, &args](
                                 const TNode<NativeContext> native_context,
307 308
                                 const TNode<JSPromise> promise,
                                 Label* if_exception) {
309 310
    // If return is undefined, then
    // Let iterResult be ! CreateIterResultObject(value, true)
311
    const TNode<Object> iter_result = CallBuiltin(
312
        Builtins::kCreateIterResultObject, context, value, TrueConstant());
313 314 315 316

    // Perform ! Call(promiseCapability.[[Resolve]], undefined, « iterResult »).
    // IfAbruptRejectPromise(nextDone, promiseCapability).
    // Return promiseCapability.[[Promise]].
317
    CallBuiltin(Builtins::kResolvePromise, context, promise, iter_result);
318
    args.PopAndReturn(promise);
319 320 321
  };

  Generate_AsyncFromSyncIteratorMethod(
322 323
      &args, context, iterator, value, factory()->return_string(),
      if_return_undefined, "[Async-from-Sync Iterator].prototype.return");
324 325 326 327 328 329
}

// https://tc39.github.io/proposal-async-iteration/
// Section #sec-%asyncfromsynciteratorprototype%.throw
TF_BUILTIN(AsyncFromSyncIteratorPrototypeThrow,
           AsyncFromSyncBuiltinsAssembler) {
330
  TNode<IntPtrT> argc = ChangeInt32ToIntPtr(
331
      UncheckedParameter<Int32T>(Descriptor::kJSActualArgumentsCount));
332 333 334 335
  CodeStubArguments args(this, argc);

  const TNode<Object> iterator = args.GetReceiver();
  const TNode<Object> reason = args.GetOptionalArgumentValue(kValueOrReasonArg);
336
  const auto context = Parameter<Context>(Descriptor::kContext);
337

338 339
  auto if_throw_undefined = [=](const TNode<NativeContext> native_context,
                                const TNode<JSPromise> promise,
340 341 342
                                Label* if_exception) { Goto(if_exception); };

  Generate_AsyncFromSyncIteratorMethod(
343 344 345
      &args, context, iterator, reason, factory()->throw_string(),
      if_throw_undefined, "[Async-from-Sync Iterator].prototype.throw",
      Label::kNonDeferred, reason);
346 347 348 349
}

}  // namespace internal
}  // namespace v8