• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 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 "stringConstantsLowering.h"
17 
18 namespace ark::es2panda::compiler {
19 
Name() const20 std::string_view StringConstantsLowering::Name() const
21 {
22     return "StringConstantsLowering";
23 }
24 
FoldConcat(public_lib::Context * ctx,ir::BinaryExpression * const concat)25 static ir::AstNode *FoldConcat(public_lib::Context *ctx, ir::BinaryExpression *const concat)
26 {
27     auto const lhs = concat->Left()->AsStringLiteral();
28     auto const rhs = concat->Right()->AsStringLiteral();
29     auto const resStr = util::UString(lhs->Str().Mutf8() + rhs->Str().Mutf8(), ctx->allocator).View();
30 
31     auto resNode = util::NodeAllocator::Alloc<ir::StringLiteral>(ctx->allocator, resStr);
32     resNode->SetParent(concat->Parent());
33     resNode->SetRange({lhs->Range().start, rhs->Range().end});
34     return resNode;
35 }
36 
Perform(public_lib::Context * ctx,parser::Program * program)37 bool StringConstantsLowering::Perform(public_lib::Context *ctx, parser::Program *program)
38 {
39     for (auto &[_, ext_programs] : program->ExternalSources()) {
40         (void)_;
41         for (auto *extProg : ext_programs) {
42             Perform(ctx, extProg);
43         }
44     }
45 
46     program->Ast()->TransformChildrenRecursivelyPostorder(
47         // CC-OFFNXT(G.FMT.14-CPP) project code style
48         [ctx](ir::AstNode *const node) -> ir::AstNode * {
49             if (node->IsBinaryExpression()) {
50                 auto const binOp = node->AsBinaryExpression();
51                 if (binOp->OperatorType() == lexer::TokenType::PUNCTUATOR_PLUS && binOp->Left()->IsStringLiteral() &&
52                     binOp->Right()->IsStringLiteral()) {
53                     return FoldConcat(ctx, binOp);
54                 }
55             }
56             return node;
57         },
58         Name());
59 
60     return true;
61 }
62 
63 }  // namespace ark::es2panda::compiler
64