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