1 /*
2 * Copyright (c) 2021-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 "optionalLowering.h"
17 #include "checker/ETSchecker.h"
18 #include "compiler/lowering/util.h"
19 #include "compiler/lowering/scopesInit/scopesInitPhase.h"
20 #include "ir/statements/blockStatement.h"
21 #include "ir/expressions/memberExpression.h"
22 #include "parser/ETSparser.h"
23 #include "varbinder/ETSBinder.h"
24
25 namespace ark::es2panda::compiler {
26
Name() const27 std::string_view OptionalLowering::Name() const
28 {
29 return "OptionalLowering";
30 }
31
RefineSourceRanges(ir::AstNode * node)32 static ir::AstNode *RefineSourceRanges(ir::AstNode *node)
33 {
34 auto const isDummyLoc = [](lexer::SourceRange const &range) {
35 return range.start.index == 0 && range.start.line == 0;
36 };
37
38 auto const refine = [isDummyLoc](ir::AstNode *n) {
39 if (isDummyLoc(n->Range())) {
40 n->SetRange(n->Parent()->Range());
41 };
42 };
43
44 refine(node);
45 node->IterateRecursively(refine);
46 return node;
47 }
48
49 template <typename Expr, typename GetSource, typename SetSource>
LowerOptionalExpr(GetSource const & getSource,SetSource const & setSource,public_lib::Context * ctx,Expr * const expr,ir::ChainExpression * const chain)50 static ir::AstNode *LowerOptionalExpr(GetSource const &getSource, SetSource const &setSource, public_lib::Context *ctx,
51 Expr *const expr, ir::ChainExpression *const chain)
52 {
53 auto *const allocator = ctx->allocator;
54 auto *const parser = ctx->parser->AsETSParser();
55 auto *const varbinder = ctx->parserProgram->VarBinder();
56
57 auto expressionCtx = varbinder::LexicalScope<varbinder::Scope>::Enter(varbinder, NearestScope(expr));
58 auto *tmpIdent = Gensym(allocator);
59 auto *tmpIdentClone = tmpIdent->Clone(allocator, nullptr);
60
61 // '0's act as placeholders
62 auto *sequenceExpr = parser->CreateFormattedExpression(
63 "let @@I1 = 0;"
64 "(@@I2 == null ? undefined : 0);",
65 tmpIdent, tmpIdentClone);
66 sequenceExpr->SetParent(chain->Parent());
67 InitScopesPhaseETS::RunExternalNode(sequenceExpr, ctx->parserProgram->VarBinder());
68
69 auto const &stmts = sequenceExpr->AsBlockExpression()->Statements();
70 stmts[0]->AsVariableDeclaration()->Declarators()[0]->SetInit(getSource(expr));
71 stmts[1]->AsExpressionStatement()->GetExpression()->AsConditionalExpression()->SetAlternate(chain->GetExpression());
72
73 setSource(expr, parser->CreateFormattedExpression("@@I1", tmpIdentClone->Clone(allocator, nullptr)));
74 return sequenceExpr;
75 }
76
LowerExpression(public_lib::Context * ctx,ir::MemberExpression * const expr,ir::ChainExpression * chain)77 static ir::AstNode *LowerExpression(public_lib::Context *ctx, ir::MemberExpression *const expr,
78 ir::ChainExpression *chain)
79 {
80 ASSERT(expr->IsOptional());
81 expr->ClearOptional();
82 return LowerOptionalExpr<ir::MemberExpression>([](auto *e) { return e->Object(); },
83 [](auto *e, auto *obj) { e->SetObject(obj); }, ctx, expr, chain);
84 }
85
LowerExpression(public_lib::Context * ctx,ir::CallExpression * const expr,ir::ChainExpression * chain)86 static ir::AstNode *LowerExpression(public_lib::Context *ctx, ir::CallExpression *const expr,
87 ir::ChainExpression *chain)
88 {
89 ASSERT(expr->IsOptional());
90 expr->ClearOptional();
91 return LowerOptionalExpr<ir::CallExpression>([](auto *e) { return e->Callee(); },
92 [](auto *e, auto *callee) { e->SetCallee(callee); }, ctx, expr, chain);
93 }
94
FindOptionalInChain(ir::Expression * expr)95 static ir::Expression *FindOptionalInChain(ir::Expression *expr)
96 {
97 if (expr->IsMemberExpression()) {
98 auto typed = expr->AsMemberExpression();
99 return typed->IsOptional() ? typed : FindOptionalInChain(typed->Object());
100 }
101 if (expr->IsCallExpression()) {
102 auto typed = expr->AsCallExpression();
103 return typed->IsOptional() ? typed : FindOptionalInChain(typed->Callee());
104 }
105 if (expr->IsTSNonNullExpression()) {
106 return FindOptionalInChain(expr->AsTSNonNullExpression()->Expr());
107 }
108 UNREACHABLE();
109 }
110
LowerChain(public_lib::Context * ctx,ir::ChainExpression * const chain)111 static ir::AstNode *LowerChain(public_lib::Context *ctx, ir::ChainExpression *const chain)
112 {
113 auto optional = FindOptionalInChain(chain->GetExpression());
114 if (optional->IsMemberExpression()) {
115 return LowerExpression(ctx, optional->AsMemberExpression(), chain);
116 }
117 if (optional->IsCallExpression()) {
118 return LowerExpression(ctx, optional->AsCallExpression(), chain);
119 }
120 UNREACHABLE();
121 }
122
Perform(public_lib::Context * ctx,parser::Program * program)123 bool OptionalLowering::Perform(public_lib::Context *ctx, parser::Program *program)
124 {
125 for (auto &[_, ext_programs] : program->ExternalSources()) {
126 (void)_;
127 for (auto *extProg : ext_programs) {
128 Perform(ctx, extProg);
129 }
130 }
131
132 program->Ast()->TransformChildrenRecursively(
133 // CC-OFFNXT(G.FMT.14-CPP) project code style
134 [ctx](ir::AstNode *const node) -> ir::AstNode * {
135 if (node->IsChainExpression()) {
136 return RefineSourceRanges(LowerChain(ctx, node->AsChainExpression()));
137 }
138 return node;
139 },
140 Name());
141
142 return true;
143 }
144
Postcondition(public_lib::Context * ctx,const parser::Program * program)145 bool OptionalLowering::Postcondition(public_lib::Context *ctx, const parser::Program *program)
146 {
147 for (auto &[_, ext_programs] : program->ExternalSources()) {
148 (void)_;
149 for (auto *extProg : ext_programs) {
150 if (!Postcondition(ctx, extProg)) {
151 return false;
152 }
153 }
154 }
155
156 return !program->Ast()->IsAnyChild([](const ir::AstNode *node) {
157 return node->IsChainExpression() || (node->IsMemberExpression() && node->AsMemberExpression()->IsOptional()) ||
158 (node->IsCallExpression() && node->AsCallExpression()->IsOptional());
159 });
160 }
161
162 } // namespace ark::es2panda::compiler
163