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 "templateLiteral.h"
17
18 #include <compiler/core/pandagen.h>
19 #include <typescript/checker.h>
20 #include <ir/astDump.h>
21 #include <ir/base/templateElement.h>
22
23 namespace panda::es2panda::ir {
24
Iterate(const NodeTraverser & cb) const25 void TemplateLiteral::Iterate(const NodeTraverser &cb) const
26 {
27 for (auto *it : expressions_) {
28 cb(it);
29 }
30
31 for (auto *it : quasis_) {
32 cb(it);
33 }
34 }
35
Dump(ir::AstDumper * dumper) const36 void TemplateLiteral::Dump(ir::AstDumper *dumper) const
37 {
38 dumper->Add({{"type", "TemplateLiteral"}, {"expressions", expressions_}, {"quasis", quasis_}});
39 }
40
Compile(compiler::PandaGen * pg) const41 void TemplateLiteral::Compile(compiler::PandaGen *pg) const
42 {
43 auto quasisIt = quasis_.begin();
44 auto expressionIt = expressions_.begin();
45
46 pg->LoadAccumulatorString(this, (*quasisIt)->Cooked());
47
48 quasisIt++;
49
50 bool isQuais = false;
51 size_t total = quasis_.size() + expressions_.size();
52
53 compiler::RegScope rs(pg);
54 compiler::VReg lhs = pg->AllocReg();
55
56 while (total != 1) {
57 const ir::AstNode *node = nullptr;
58
59 if (isQuais) {
60 pg->StoreAccumulator(*quasisIt, lhs);
61 pg->LoadAccumulatorString(this, (*quasisIt)->Cooked());
62
63 node = *quasisIt;
64 quasisIt++;
65 } else {
66 const ir::Expression *element = *expressionIt;
67 pg->StoreAccumulator(element, lhs);
68
69 element->Compile(pg);
70
71 node = element;
72 expressionIt++;
73 }
74
75 pg->Binary(node, lexer::TokenType::PUNCTUATOR_PLUS, lhs);
76
77 isQuais = !isQuais;
78 total--;
79 }
80 }
81
Check(checker::Checker * checker) const82 checker::Type *TemplateLiteral::Check(checker::Checker *checker) const
83 {
84 // TODO(aszilagyi)
85 return checker->GlobalAnyType();
86 }
87
UpdateSelf(const NodeUpdater & cb,binder::Binder * binder)88 void TemplateLiteral::UpdateSelf(const NodeUpdater &cb, [[maybe_unused]] binder::Binder *binder)
89 {
90 for (auto iter = expressions_.begin(); iter != expressions_.end(); iter++) {
91 *iter = std::get<ir::AstNode *>(cb(*iter))->AsExpression();
92 }
93
94 for (auto iter = quasis_.begin(); iter != quasis_.end(); iter++) {
95 *iter = std::get<ir::AstNode *>(cb(*iter))->AsTemplateElement();
96 }
97 }
98
99 } // namespace panda::es2panda::ir
100