• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2021 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 "switchBuilder.h"
17 
18 #include <ir/statements/switchStatement.h>
19 #include <ir/statements/switchCaseStatement.h>
20 #include <compiler/core/pandagen.h>
21 
22 namespace panda::es2panda::compiler {
23 // SwitchBuilder
24 
SwitchBuilder(PandaGen * pg,const ir::SwitchStatement * stmt)25 SwitchBuilder::SwitchBuilder(PandaGen *pg, const ir::SwitchStatement *stmt)
26     : pg_(pg), end_(pg->AllocLabel()), labelCtx_(pg, LabelTarget(end_, LabelTarget::BREAK_LABEL)), stmt_(stmt)
27 {
28     for (size_t i = 0; i < stmt_->Cases().size(); i++) {
29         caseLabels_.push_back(pg_->AllocLabel());
30     }
31 }
32 
~SwitchBuilder()33 SwitchBuilder::~SwitchBuilder()
34 {
35     pg_->SetLabel(stmt_, end_);
36 }
37 
SetCaseTarget(uint32_t index)38 void SwitchBuilder::SetCaseTarget(uint32_t index)
39 {
40     pg_->SetLabel(stmt_->Cases()[index], caseLabels_[index]);
41 }
42 
CompileTagOfSwitch(VReg tag)43 void SwitchBuilder::CompileTagOfSwitch(VReg tag)
44 {
45     stmt_->Discriminant()->Compile(pg_);
46     pg_->StoreAccumulator(stmt_->Discriminant(), tag);
47 }
48 
CompileCaseStatements(uint32_t index)49 void SwitchBuilder::CompileCaseStatements(uint32_t index)
50 {
51     for (const auto *stmt : stmt_->Cases()[index]->Consequent()) {
52         stmt->Compile(pg_);
53     }
54 }
55 
JumpIfCase(VReg tag,uint32_t index)56 void SwitchBuilder::JumpIfCase(VReg tag, uint32_t index)
57 {
58     const ir::SwitchCaseStatement *caseTarget = stmt_->Cases()[index];
59     caseTarget->Test()->Compile(pg_);
60     pg_->Condition(caseTarget, lexer::TokenType::PUNCTUATOR_NOT_STRICT_EQUAL, tag, caseLabels_[index]);
61 }
62 
JumpToDefault(uint32_t defaultIndex)63 void SwitchBuilder::JumpToDefault(uint32_t defaultIndex)
64 {
65     const ir::SwitchCaseStatement *defaultTarget = stmt_->Cases()[defaultIndex];
66     pg_->Branch(defaultTarget, caseLabels_[defaultIndex]);
67 }
68 
Break()69 void SwitchBuilder::Break()
70 {
71     pg_->Branch(stmt_, end_);
72 }
73 }  // namespace panda::es2panda::compiler
74