1 /*
2 * Copyright (c) 2021 - 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "generatorFunctionBuilder.h"
17
18 #include "compiler/core/pandagen.h"
19 #include "compiler/base/catchTable.h"
20 #include "ir/base/scriptFunction.h"
21
22 namespace ark::es2panda::compiler {
Prepare(const ir::ScriptFunction *node) const23 void GeneratorFunctionBuilder::Prepare(const ir::ScriptFunction *node) const
24 {
25 VReg callee = FunctionReg(node);
26
27 pg_->CreateGeneratorObj(node, callee);
28 pg_->StoreAccumulator(node, funcObj_);
29 pg_->SuspendGenerator(node, funcObj_);
30 pg_->SetLabel(node, catchTable_->LabelSet().TryBegin());
31 }
32
CleanUp(const ir::ScriptFunction *node) const33 void GeneratorFunctionBuilder::CleanUp(const ir::ScriptFunction *node) const
34 {
35 const auto &labelSet = catchTable_->LabelSet();
36
37 pg_->SetLabel(node, labelSet.TryEnd());
38 pg_->SetLabel(node, labelSet.CatchBegin());
39 pg_->GeneratorComplete(node, funcObj_);
40 pg_->EmitThrow(node);
41 pg_->SetLabel(node, labelSet.CatchEnd());
42 }
43
DirectReturn(const ir::AstNode *node) const44 void GeneratorFunctionBuilder::DirectReturn(const ir::AstNode *node) const
45 {
46 pg_->GeneratorComplete(node, funcObj_);
47 pg_->CreateIterResultObject(node, true);
48 pg_->EmitReturn(node);
49 }
50
ImplicitReturn(const ir::AstNode *node) const51 void GeneratorFunctionBuilder::ImplicitReturn(const ir::AstNode *node) const
52 {
53 pg_->LoadConst(node, Constant::JS_UNDEFINED);
54 DirectReturn(node);
55 }
56
Yield(const ir::AstNode *node)57 void GeneratorFunctionBuilder::Yield(const ir::AstNode *node)
58 {
59 RegScope rs(pg_);
60 VReg completionType = pg_->AllocReg();
61 VReg completionValue = pg_->AllocReg();
62
63 pg_->CreateIterResultObject(node, false);
64 pg_->GeneratorYield(node, funcObj_);
65 SuspendResumeExecution(node, completionType, completionValue);
66
67 HandleCompletion(node, completionType, completionValue);
68 }
69 } // namespace ark::es2panda::compiler
70