1/*
2 * Copyright (c) 2021-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 "literals.h"
17
18#include <compiler/core/pandagen.h>
19#include <ir/base/templateElement.h>
20#include <ir/expressions/taggedTemplateExpression.h>
21#include <ir/expressions/templateLiteral.h>
22
23namespace panda::es2panda::compiler {
24
25// Literals
26
27void Literals::GetTemplateObject(PandaGen *pg, const ir::TaggedTemplateExpression *lit)
28{
29    RegScope rs(pg);
30    VReg templateArg = pg->AllocReg();
31    VReg indexReg = pg->AllocReg();
32    VReg rawArr = pg->AllocReg();
33    VReg cookedArr = pg->AllocReg();
34
35    const ir::TemplateLiteral *templateLit = lit->Quasi();
36
37    pg->CreateEmptyArray(templateLit);
38    pg->StoreAccumulator(templateLit, rawArr);
39
40    pg->CreateEmptyArray(templateLit);
41    pg->StoreAccumulator(templateLit, cookedArr);
42
43    size_t elemIndex = 0;
44
45    for (const auto *element : templateLit->Quasis()) {
46        pg->LoadAccumulatorInt(element, elemIndex);
47        pg->StoreAccumulator(element, indexReg);
48
49        pg->LoadAccumulatorString(element, element->Raw());
50        pg->DefineFieldByValue(element, rawArr, indexReg);
51        // Generate ldundefined when element is escape error
52        if (element->EscapeError()) {
53            pg->LoadConst(element, compiler::Constant::JS_UNDEFINED);
54        } else {
55            pg->LoadAccumulatorString(element, element->Cooked());
56        }
57        pg->DefineFieldByValue(element, cookedArr, indexReg);
58
59        elemIndex++;
60    }
61
62    pg->CreateEmptyArray(lit);
63    pg->StoreAccumulator(lit, templateArg);
64
65    elemIndex = 0;
66    pg->LoadAccumulatorInt(lit, elemIndex);
67    pg->StoreAccumulator(lit, indexReg);
68
69    pg->LoadAccumulator(lit, rawArr);
70    pg->DefineFieldByValue(lit, templateArg, indexReg);
71
72    elemIndex++;
73    pg->LoadAccumulatorInt(lit, elemIndex);
74    pg->StoreAccumulator(lit, indexReg);
75
76    pg->LoadAccumulator(lit, cookedArr);
77    pg->DefineFieldByValue(lit, templateArg, indexReg);
78
79    pg->GetTemplateObject(lit, templateArg);
80}
81
82}  // namespace panda::es2panda::compiler
83