• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 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 panda::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_) {
29         pg_->SetLabel(node_, label_);
30     }
31     pg_->optionalChain_ = prev_;
32 }
33 
CheckNullish(bool optional,compiler::VReg obj)34 void OptionalChain::CheckNullish(bool optional, compiler::VReg obj)
35 {
36     if (!optional) {
37         return;
38     }
39 
40     if (!label_) {
41         label_ = pg_->AllocLabel();
42     }
43 
44     RegScope rs(pg_);
45 
46     auto *notNullish = pg_->AllocLabel();
47     auto *nullish = pg_->AllocLabel();
48 
49     pg_->LoadConst(node_, Constant::JS_NULL);
50     pg_->Condition(node_, lexer::TokenType::PUNCTUATOR_NOT_STRICT_EQUAL, obj, nullish);
51     pg_->LoadConst(node_, Constant::JS_UNDEFINED);
52     pg_->Condition(node_, lexer::TokenType::PUNCTUATOR_NOT_STRICT_EQUAL, obj, nullish);
53     pg_->Branch(node_, notNullish);
54     pg_->SetLabel(node_, nullish);
55 
56     pg_->LoadConst(node_, compiler::Constant::JS_UNDEFINED);
57     pg_->Branch(node_, label_);
58     pg_->SetLabel(node_, notNullish);
59     pg_->LoadAccumulator(node_, obj);
60 }
61 
62 }   // namespace panda::es2panda::compiler
63