1 /*
2 * Copyright (c) 2021-2024 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 "optionalChain.h"
17
18 #include "compiler/core/pandagen.h"
19
20 namespace ark::es2panda::compiler {
OptionalChain(PandaGen * pg,const ir::AstNode * node)21 OptionalChain::OptionalChain(PandaGen *pg, const ir::AstNode *node) : pg_(pg), node_(node), prev_(pg->optionalChain_)
22 {
23 pg->optionalChain_ = this;
24 }
25
~OptionalChain()26 OptionalChain::~OptionalChain()
27 {
28 if (label_ != nullptr) {
29 pg_->SetLabel(node_, label_);
30 }
31
32 pg_->optionalChain_ = prev_;
33 }
34
Check(compiler::VReg obj)35 void OptionalChain::Check(compiler::VReg obj)
36 {
37 if (label_ == nullptr) {
38 label_ = pg_->AllocLabel();
39 }
40
41 RegScope rs(pg_);
42
43 if (obj.IsInvalid()) {
44 obj = pg_->AllocReg();
45 pg_->StoreAccumulator(node_, obj);
46 }
47
48 auto *coercibleLabel = pg_->AllocLabel();
49
50 pg_->BranchIfCoercible(node_, coercibleLabel);
51
52 pg_->LoadConst(node_, compiler::Constant::JS_UNDEFINED);
53 pg_->Branch(node_, label_);
54
55 pg_->SetLabel(node_, coercibleLabel);
56 pg_->LoadAccumulator(node_, obj);
57 }
58 } // namespace ark::es2panda::compiler
59