1 /*
2 * Copyright (c) 2021-2025 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 "functionBuilder.h"
17
18 #include "varbinder/varbinder.h"
19 #include "util/helpers.h"
20 #include "ir/statement.h"
21 #include "ir/base/scriptFunction.h"
22 #include "compiler/base/iterators.h"
23 #include "compiler/core/pandagen.h"
24
25 namespace ark::es2panda::compiler {
FunctionBuilder(PandaGen * pg,CatchTable * catchTable)26 FunctionBuilder::FunctionBuilder(PandaGen *pg, CatchTable *catchTable)
27 : pg_(pg), catchTable_(catchTable), funcObj_(catchTable != nullptr ? pg_->AllocReg() : VReg(VReg::REG_START))
28 {
29 }
30
GeneratorKind() const31 IteratorType FunctionBuilder::GeneratorKind() const
32 {
33 return IteratorType::SYNC;
34 }
35
DirectReturn(const ir::AstNode * node) const36 void FunctionBuilder::DirectReturn(const ir::AstNode *node) const
37 {
38 pg_->EmitReturn(node);
39 }
40
ImplicitReturn(const ir::AstNode * node) const41 void FunctionBuilder::ImplicitReturn(const ir::AstNode *node) const
42 {
43 const auto *rootNode = pg_->RootNode();
44
45 if (!rootNode->IsScriptFunction() || !rootNode->AsScriptFunction()->IsConstructor()) {
46 pg_->EmitReturnUndefined(node);
47 return;
48 }
49
50 pg_->GetThis(rootNode);
51 pg_->ThrowIfSuperNotCorrectCall(rootNode, 0);
52 pg_->EmitReturn(node);
53 }
54
AsyncYield(const ir::AstNode * node,VReg completionType,VReg completionValue) const55 void FunctionBuilder::AsyncYield(const ir::AstNode *node, VReg completionType, VReg completionValue) const
56 {
57 ES2PANDA_ASSERT(BuilderKind() == BuilderType::ASYNC_GENERATOR);
58
59 pg_->GeneratorYield(node, funcObj_);
60 pg_->SuspendAsyncGenerator(node, funcObj_);
61
62 ResumeGenerator(node, completionType, completionValue);
63 }
64
SuspendResumeExecution(const ir::AstNode * node,VReg completionType,VReg completionValue) const65 void FunctionBuilder::SuspendResumeExecution(const ir::AstNode *node, VReg completionType, VReg completionValue) const
66 {
67 ES2PANDA_ASSERT(BuilderKind() == BuilderType::ASYNC || BuilderKind() == BuilderType::ASYNC_GENERATOR ||
68 BuilderKind() == BuilderType::GENERATOR);
69
70 pg_->SuspendGenerator(node, funcObj_);
71 ResumeGenerator(node, completionType, completionValue);
72 }
73
ResumeGenerator(const ir::AstNode * node,VReg completionType,VReg completionValue) const74 void FunctionBuilder::ResumeGenerator(const ir::AstNode *node, VReg completionType, VReg completionValue) const
75 {
76 ES2PANDA_ASSERT(BuilderKind() == BuilderType::ASYNC || BuilderKind() == BuilderType::ASYNC_GENERATOR ||
77 BuilderKind() == BuilderType::GENERATOR);
78
79 pg_->ResumeGenerator(node, funcObj_);
80 pg_->StoreAccumulator(node, completionValue);
81 pg_->GetResumeMode(node, funcObj_);
82 pg_->StoreAccumulator(node, completionType);
83 }
84
FunctionReg(const ir::ScriptFunction * node) const85 VReg FunctionBuilder::FunctionReg(const ir::ScriptFunction *node) const
86 {
87 varbinder::FunctionScope *scope = node->Scope();
88 auto res = scope->Find(varbinder::VarBinder::MANDATORY_PARAM_FUNC);
89 ES2PANDA_ASSERT(res.level == 0 && res.variable->IsLocalVariable());
90 return res.variable->AsLocalVariable()->Vreg();
91 }
92
Await(const ir::AstNode * node)93 void FunctionBuilder::Await(const ir::AstNode *node)
94 {
95 if (BuilderKind() == BuilderType::NORMAL) {
96 // NOTE: frobert. Implement top-level await
97 PandaGen::Unimplemented();
98 }
99
100 ES2PANDA_ASSERT(BuilderKind() == BuilderType::ASYNC || BuilderKind() == BuilderType::ASYNC_GENERATOR);
101
102 RegScope rs(pg_);
103 VReg completionType = pg_->AllocReg();
104 VReg completionValue = pg_->AllocReg();
105
106 pg_->AsyncFunctionAwait(node, funcObj_);
107 SuspendResumeExecution(node, completionType, completionValue);
108
109 HandleCompletion(node, completionType, completionValue);
110 }
111
HandleCompletion(const ir::AstNode * node,VReg completionType,VReg completionValue)112 void FunctionBuilder::HandleCompletion(const ir::AstNode *node, VReg completionType, VReg completionValue)
113 {
114 // .return(value)
115 pg_->LoadAccumulatorInt(node, static_cast<int32_t>(ResumeMode::RETURN));
116
117 auto *notRetLabel = pg_->AllocLabel();
118 pg_->Condition(node, lexer::TokenType::PUNCTUATOR_EQUAL, completionType, notRetLabel);
119 if (!handleReturn_) {
120 handleReturn_ = true;
121 pg_->ControlFlowChangeBreak();
122 handleReturn_ = false;
123 }
124
125 pg_->LoadAccumulator(node, completionValue);
126 pg_->DirectReturn(node);
127
128 // .throw(value)
129 pg_->SetLabel(node, notRetLabel);
130 pg_->LoadAccumulatorInt(node, static_cast<int32_t>(ResumeMode::THROW));
131
132 auto *notThrowLabel = pg_->AllocLabel();
133 pg_->Condition(node, lexer::TokenType::PUNCTUATOR_EQUAL, completionType, notThrowLabel);
134 pg_->LoadAccumulator(node, completionValue);
135 pg_->EmitThrow(node);
136
137 // .next(value)
138 pg_->SetLabel(node, notThrowLabel);
139 pg_->LoadAccumulator(node, completionValue);
140 }
141
142 // CC-OFFNXT(huge_method, G.FUN.01-CPP) solid logic
YieldStar(const ir::AstNode * node)143 void FunctionBuilder::YieldStar(const ir::AstNode *node)
144 {
145 ES2PANDA_ASSERT(BuilderKind() == BuilderType::GENERATOR || BuilderKind() == BuilderType::ASYNC_GENERATOR);
146
147 RegScope rs(pg_);
148
149 auto *loopStart = pg_->AllocLabel();
150 auto *returnCompletion = pg_->AllocLabel();
151 auto *throwCompletion = pg_->AllocLabel();
152 auto *callMethod = pg_->AllocLabel();
153 auto *normalOrThrowCompletion = pg_->AllocLabel();
154 auto *iteratorComplete = pg_->AllocLabel();
155
156 // 4. Let iteratorRecord be ? GetIterator(value, generatorKind).
157 Iterator iterator(pg_, node, GeneratorKind());
158
159 // 6. Let received be NormalCompletion(undefined).
160 VReg receivedValue = iterator.NextResult();
161 VReg receivedType = pg_->AllocReg();
162 VReg nextMethod = pg_->AllocReg();
163 VReg exitReturn = pg_->AllocReg();
164
165 pg_->StoreConst(node, receivedValue, Constant::JS_UNDEFINED);
166 pg_->LoadAccumulatorInt(node, static_cast<int32_t>(ResumeMode::NEXT));
167 pg_->StoreAccumulator(node, receivedType);
168 pg_->MoveVreg(node, nextMethod, iterator.Method());
169
170 // 7. Repeat
171 pg_->SetLabel(node, loopStart);
172 pg_->StoreConst(node, exitReturn, Constant::JS_FALSE);
173
174 // a. If received.[[Type]] is normal, then
175 pg_->LoadAccumulatorInt(node, static_cast<int32_t>(ResumeMode::NEXT));
176 pg_->Condition(node, lexer::TokenType::PUNCTUATOR_STRICT_EQUAL, receivedType, throwCompletion);
177 pg_->MoveVreg(node, iterator.Method(), nextMethod);
178 pg_->Branch(node, callMethod);
179
180 // b. Else if received.[[Type]] is throw, then
181 pg_->SetLabel(node, throwCompletion);
182 pg_->LoadAccumulatorInt(node, static_cast<int32_t>(ResumeMode::THROW));
183 pg_->Condition(node, lexer::TokenType::PUNCTUATOR_STRICT_EQUAL, receivedType, returnCompletion);
184
185 // i. Let throw be ? GetMethod(iterator, "throw").
186 iterator.GetMethod("throw");
187
188 // ii. If throw is not undefined, then
189 pg_->BranchIfNotUndefined(node, callMethod);
190
191 // iii. Else,
192 // 1. NOTE: If iterator does not have a throw method, this throw is going to terminate the yield* loop. But first we
193 // need to give iterator a chance to clean up.
194 // 2. Let closeCompletion be Completion { [[Type]]: normal, [[Value]]: empty, [[Target]]: empty }.
195 // 3. If generatorKind is async, perform ? AsyncIteratorClose(iteratorRecord, closeCompletion).
196 // 4. Else, perform ? IteratorClose(iteratorRecord, closeCompletion).
197 iterator.Close(false);
198 // 5. NOTE: The next step throws a TypeError to indicate that there was a yield* protocol violation: iterator does
199 // not have a throw method.
200 // 6. Throw a TypeError exception.
201 pg_->ThrowThrowNotExist(node);
202
203 // c. Else,
204 // i. Assert: received.[[Type]] is return.
205 pg_->SetLabel(node, returnCompletion);
206 pg_->StoreConst(node, exitReturn, Constant::JS_TRUE);
207 // ii. Let return be ? GetMethod(iterator, "return").
208 iterator.GetMethod("return");
209
210 // iii. If return is undefined, then
211 pg_->BranchIfNotUndefined(node, callMethod);
212
213 // 1. If generatorKind is async, set received.[[Value]] to ? Await(received.[[Value]]).
214 pg_->ControlFlowChangeBreak();
215 pg_->LoadAccumulator(node, receivedValue);
216
217 if (GeneratorKind() == IteratorType::ASYNC) {
218 Await(node);
219 }
220
221 // 2. Return Completion(received).
222 pg_->DirectReturn(node);
223
224 pg_->SetLabel(node, callMethod);
225 // i. Let innerResult be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « received.[[Value]] »).
226 // 1. Let innerResult be ? Call(throw, iterator, « received.[[Value]] »).
227 // iv. Let innerReturnResult be ? Call(return, iterator, « received.[[Value]] »).
228 iterator.CallMethodWithValue();
229
230 // ii. ii. If generatorKind is async, set innerResult to ? Await(innerResult).
231 // 2. If generatorKind is async, set innerResult to ? Await(innerResult).
232 // v. If generatorKind is async, set innerReturnResult to ? Await(innerReturnResult).
233 if (GeneratorKind() == IteratorType::ASYNC) {
234 Await(node);
235 }
236
237 pg_->StoreAccumulator(node, receivedValue);
238
239 // ii. If Type(innerResult) is not Object, throw a TypeError exception.
240 // 4. If Type(innerResult) is not Object, throw a TypeError exception.
241 // vi. If Type(innerReturnResult) is not Object, throw a TypeError exception.
242 pg_->ThrowIfNotObject(node);
243
244 // iv. Let done be ? IteratorComplete(innerResult).
245 // v. Let done be ? IteratorComplete(innerResult).
246 // vii. Let done be ? IteratorComplete(innerReturnResult).
247 iterator.Complete();
248 pg_->BranchIfTrue(node, iteratorComplete);
249
250 // vi. If generatorKind is async, set received to AsyncGeneratorYield(? IteratorValue(innerResult)).
251 // 7. If generatorKind is async, set received to AsyncGeneratorYield(? IteratorValue(innerResult)).
252 // ix. If generatorKind is async, set received to AsyncGeneratorYield(? IteratorValue(innerReturnResult)).
253 if (GeneratorKind() == IteratorType::ASYNC) {
254 iterator.Value();
255 // 27.6.3.8 AsyncGeneratorYield
256 // 5. Set value to ? Await(value).
257 Await(node);
258 // 6. Set generator.[[AsyncGeneratorState]] to suspendedYield.
259 AsyncYield(node, receivedType, receivedValue);
260
261 // a. If resumptionValue.[[Type]] is not return
262 pg_->LoadAccumulatorInt(node, static_cast<int32_t>(ResumeMode::RETURN));
263 pg_->Condition(node, lexer::TokenType::PUNCTUATOR_EQUAL, receivedType, loopStart);
264
265 // b. Let awaited be Await(resumptionValue.[[Value]]).
266 pg_->LoadAccumulator(node, receivedValue);
267 pg_->AsyncFunctionAwait(node, funcObj_);
268 SuspendResumeExecution(node, receivedType, receivedValue);
269
270 // c. If awaited.[[Type]] is throw, return Completion(awaited).
271 pg_->LoadAccumulatorInt(node, static_cast<int32_t>(ResumeMode::THROW));
272 // d. Assert: awaited.[[Type]] is normal.
273 // e. Return Completion { [[Type]]: return, [[Value]]: awaited.[[Value]], [[Target]]: empty }.
274 pg_->Condition(node, lexer::TokenType::PUNCTUATOR_EQUAL, receivedType, returnCompletion);
275 } else {
276 // vii. Else, set received to GeneratorYield(innerResult).
277 // 8. Else, set received to GeneratorYield(innerResult).
278 // x. Else, set received to GeneratorYield(innerReturnResult).
279 pg_->LoadAccumulator(node, receivedValue);
280 pg_->GeneratorYield(node, funcObj_);
281 SuspendResumeExecution(node, receivedType, receivedValue);
282 }
283
284 pg_->Branch(node, loopStart);
285
286 // v. If done is true, then
287 // 6. If done is true, then
288 // viii. If done is true, then
289 pg_->SetLabel(node, iteratorComplete);
290
291 pg_->LoadAccumulator(node, exitReturn);
292 pg_->BranchIfFalse(node, normalOrThrowCompletion);
293
294 // 1. Let value be ? IteratorValue(innerReturnResult).
295 iterator.Value();
296
297 if (pg_->CheckControlFlowChange()) {
298 pg_->StoreAccumulator(node, receivedValue);
299 pg_->ControlFlowChangeBreak();
300 pg_->LoadAccumulator(node, receivedValue);
301 }
302
303 // 2. Return Completion { [[Type]]: return, [[Value]]: value, [[Target]]: empty }.
304 pg_->DirectReturn(node);
305
306 pg_->SetLabel(node, normalOrThrowCompletion);
307 // 1. Return ? IteratorValue(innerResult).
308 // a. Return ? IteratorValue(innerResult).
309 iterator.Value();
310 }
311 } // namespace ark::es2panda::compiler
312