• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024-2025 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 "boxingForLocals.h"
17 
18 #include "compiler/lowering/util.h"
19 #include "checker/ETSchecker.h"
20 
21 namespace ark::es2panda::compiler {
22 
23 static constexpr std::string_view LOWERING_NAME = "boxing-for-locals";
24 
FindCaptured(public_lib::Context * ctx,ir::ScriptFunction * func)25 static ArenaSet<varbinder::Variable *> FindCaptured(public_lib::Context *ctx, ir::ScriptFunction *func)
26 {
27     auto *allocator = ctx->allocator;
28     auto captured = ArenaSet<varbinder::Variable *>(allocator->Adapter());
29     bool withinLambda = false;
30 
31     auto innermostArrowScopes = ArenaSet<varbinder::Scope *>(allocator->Adapter());
32     innermostArrowScopes.insert(func->Scope());
33     innermostArrowScopes.insert(func->Scope()->ParamScope());
34 
35     std::function<void(ir::AstNode *)> walker = [&](ir::AstNode *ast) {
36         if (ast->IsArrowFunctionExpression() || ast->IsClassDeclaration()) {
37             auto savedWL = withinLambda;
38             auto savedScopes = ArenaSet<varbinder::Scope *>(allocator->Adapter());
39             std::swap(innermostArrowScopes, savedScopes);
40             withinLambda = true;
41 
42             ast->Iterate(walker);
43 
44             withinLambda = savedWL;
45             std::swap(innermostArrowScopes, savedScopes);
46 
47             return;
48         }
49 
50         if (withinLambda && ast->IsScopeBearer()) {
51             innermostArrowScopes.insert(ast->Scope());
52             if (ast->Scope()->IsFunctionScope()) {
53                 innermostArrowScopes.insert(ast->Scope()->AsFunctionScope()->ParamScope());
54             }
55             if (ast->Scope()->IsCatchScope()) {
56                 innermostArrowScopes.insert(ast->Scope()->AsCatchScope()->ParamScope());
57             }
58             if (ast->Scope()->IsLoopScope()) {
59                 innermostArrowScopes.insert(ast->Scope()->AsLoopScope()->DeclScope());
60             }
61         } else if (withinLambda && ast->IsIdentifier()) {
62             auto *var = ast->AsIdentifier()->Variable();
63             if (var == nullptr) {
64                 return;
65             }
66             auto *scope = var->GetScope();
67             if (scope != nullptr && !scope->IsClassScope() && !scope->IsGlobalScope() &&
68                 innermostArrowScopes.count(scope) == 0) {
69                 captured.insert(var);
70             }
71         }
72 
73         ast->Iterate(walker);
74     };
75 
76     func->Iterate(walker);
77 
78     auto varsToBox = ArenaSet<varbinder::Variable *>(allocator->Adapter());
79     return captured;
80 }
81 
FindModified(public_lib::Context * ctx,ir::ScriptFunction * func)82 static ArenaSet<varbinder::Variable *> FindModified(public_lib::Context *ctx, ir::ScriptFunction *func)
83 {
84     auto *allocator = ctx->allocator;
85     auto modified = ArenaSet<varbinder::Variable *>(allocator->Adapter());
86 
87     std::function<void(ir::AstNode *)> walker = [&](ir::AstNode *ast) -> void {
88         if (!ast->IsAssignmentExpression()) {
89             return;
90         }
91 
92         auto expr = ast->AsAssignmentExpression();
93         if (expr->Left()->IsIdentifier()) {
94             ES2PANDA_ASSERT(expr->Left()->Variable() != nullptr);
95             auto *var = expr->Left()->Variable();
96             var->AddFlag(varbinder::VariableFlags::INITIALIZED);
97             modified.insert(var);
98         }
99     };
100 
101     func->IterateRecursively(walker);
102     return modified;
103 }
104 
FindVariablesToBox(public_lib::Context * ctx,ir::ScriptFunction * func)105 static ArenaSet<varbinder::Variable *> FindVariablesToBox(public_lib::Context *ctx, ir::ScriptFunction *func)
106 {
107     auto *allocator = ctx->allocator;
108     auto captured = FindCaptured(ctx, func);
109     auto modified = FindModified(ctx, func);
110 
111     auto varsToBox = ArenaSet<varbinder::Variable *>(allocator->Adapter());
112     std::set_intersection(captured.cbegin(), captured.cend(), modified.cbegin(), modified.cend(),
113                           std::inserter(varsToBox, varsToBox.begin()));
114 
115     return varsToBox;
116 }
117 
HandleFunctionParam(public_lib::Context * ctx,ir::ETSParameterExpression * param,ArenaMap<varbinder::Variable *,varbinder::Variable * > * varsMap)118 static void HandleFunctionParam(public_lib::Context *ctx, ir::ETSParameterExpression *param,
119                                 ArenaMap<varbinder::Variable *, varbinder::Variable *> *varsMap)
120 {
121     auto *allocator = ctx->allocator;
122     auto *checker = ctx->checker->AsETSChecker();
123     auto *varBinder = checker->VarBinder();
124 
125     auto *id = param->Ident()->AsIdentifier();
126     auto *oldVar = id->Variable();
127     auto *oldType = oldVar->TsType();
128     auto *func = param->Parent()->AsScriptFunction();
129     ES2PANDA_ASSERT(func->Body()->IsBlockStatement());  // guaranteed after expressionLambdaLowering
130     auto *body = func->Body()->AsBlockStatement();
131     auto &bodyStmts = body->Statements();
132     auto *scope = body->Scope();
133 
134     auto *initId = allocator->New<ir::Identifier>(id->Name(), allocator);
135     ES2PANDA_ASSERT(initId != nullptr);
136     initId->SetVariable(id->Variable());
137     initId->SetTsType(oldType);
138 
139     // The new variable will have the same name as the parameter. This is not representable in source code.
140     auto *boxedType = checker->GlobalBuiltinBoxType(oldType);
141     ArenaVector<ir::Expression *> newInitArgs {allocator->Adapter()};
142     newInitArgs.push_back(initId);
143     auto *newInit = util::NodeAllocator::ForceSetParent<ir::ETSNewClassInstanceExpression>(
144         allocator, allocator->New<ir::OpaqueTypeNode>(boxedType, allocator), std::move(newInitArgs));
145 
146     auto const newVarName = GenName(allocator);
147     auto *newDeclarator = util::NodeAllocator::ForceSetParent<ir::VariableDeclarator>(
148         allocator, ir::VariableDeclaratorFlag::CONST, allocator->New<ir::Identifier>(newVarName.View(), allocator),
149         newInit);
150     ArenaVector<ir::VariableDeclarator *> declVec {allocator->Adapter()};
151     declVec.emplace_back(newDeclarator);
152 
153     auto *newDecl = allocator->New<varbinder::ConstDecl>(newVarName.View(), newDeclarator);
154     auto *newVar = allocator->New<varbinder::LocalVariable>(newDecl, oldVar->Flags());
155     ES2PANDA_ASSERT(newVar != nullptr);
156     newVar->SetTsType(boxedType);
157 
158     newDeclarator->Id()->AsIdentifier()->SetVariable(newVar);
159     newVar->AddFlag(varbinder::VariableFlags::INITIALIZED);
160     newVar->SetScope(scope);
161     scope->EraseBinding(newVar->Name());
162     scope->InsertBinding(newVar->Name(), newVar);
163 
164     auto *newDeclaration = util::NodeAllocator::ForceSetParent<ir::VariableDeclaration>(
165         allocator, ir::VariableDeclaration::VariableDeclarationKind::CONST, allocator, std::move(declVec));
166     ES2PANDA_ASSERT(newDeclaration != nullptr);
167     newDeclaration->SetParent(body);
168     bodyStmts.insert(bodyStmts.begin(), newDeclaration);
169 
170     auto lexScope = varbinder::LexicalScope<varbinder::Scope>::Enter(varBinder, scope);
171     auto savedContext = checker::SavedCheckerContext(checker, checker::CheckerStatus::NO_OPTS);
172     auto scopeContext = checker::ScopeContext(checker, scope);
173 
174     newDeclaration->Check(checker);
175 
176     varsMap->emplace(oldVar, newVar);
177 }
178 
HandleVariableDeclarator(public_lib::Context * ctx,ir::VariableDeclarator * declarator,ArenaMap<varbinder::Variable *,varbinder::Variable * > * varsMap)179 static ir::AstNode *HandleVariableDeclarator(public_lib::Context *ctx, ir::VariableDeclarator *declarator,
180                                              ArenaMap<varbinder::Variable *, varbinder::Variable *> *varsMap)
181 {
182     auto *allocator = ctx->allocator;
183     auto *checker = ctx->checker->AsETSChecker();
184     auto *varBinder = checker->VarBinder();
185 
186     auto *id = declarator->Id()->AsIdentifier();
187     auto *oldVar = id->Variable();
188     auto *scope = oldVar->GetScope();
189     auto *type = oldVar->TsType();
190     auto *boxedType = checker->GlobalBuiltinBoxType(type);
191 
192     auto initArgs = ArenaVector<ir::Expression *>(allocator->Adapter());
193     if (declarator->Init() != nullptr) {
194         auto *arg = declarator->Init();
195         if (arg->TsType() != type) {
196             arg = util::NodeAllocator::ForceSetParent<ir::TSAsExpression>(
197                 allocator, arg, allocator->New<ir::OpaqueTypeNode>(type, allocator), false);
198         }
199         initArgs.push_back(arg);
200     }
201     auto *newInit = util::NodeAllocator::ForceSetParent<ir::ETSNewClassInstanceExpression>(
202         allocator, allocator->New<ir::OpaqueTypeNode>(boxedType, allocator), std::move(initArgs));
203     auto *newDeclarator = util::NodeAllocator::ForceSetParent<ir::VariableDeclarator>(
204         allocator, declarator->Flag(), allocator->New<ir::Identifier>(id->Name(), allocator), newInit);
205     newDeclarator->SetParent(declarator->Parent());
206 
207     auto *newDecl = allocator->New<varbinder::ConstDecl>(oldVar->Name(), newDeclarator);
208     auto *newVar = allocator->New<varbinder::LocalVariable>(newDecl, oldVar->Flags());
209     ES2PANDA_ASSERT(newVar != nullptr);
210     newDeclarator->Id()->AsIdentifier()->SetVariable(newVar);
211     newVar->AddFlag(varbinder::VariableFlags::INITIALIZED);
212     newVar->SetScope(scope);
213 
214     scope->EraseBinding(oldVar->Name());
215     scope->InsertBinding(newVar->Name(), newVar);
216 
217     auto lexScope = varbinder::LexicalScope<varbinder::Scope>::Enter(varBinder, scope);
218     auto savedContext = checker::SavedCheckerContext(checker, checker::CheckerStatus::NO_OPTS);
219     auto scopeContext = checker::ScopeContext(checker, scope);
220 
221     newDeclarator->Check(checker);
222 
223     varsMap->emplace(oldVar, newVar);
224 
225     return newDeclarator;
226 }
227 
IsBeingDeclared(ir::AstNode * ast)228 static bool IsBeingDeclared(ir::AstNode *ast)
229 {
230     ES2PANDA_ASSERT(ast->IsIdentifier());
231     return (ast->Parent()->IsVariableDeclarator() && ast == ast->Parent()->AsVariableDeclarator()->Id()) ||
232            (ast->Parent()->IsETSParameterExpression() && ast == ast->Parent()->AsETSParameterExpression()->Ident());
233 }
234 
IsPartOfBoxInitializer(public_lib::Context * ctx,ir::AstNode * ast)235 static bool IsPartOfBoxInitializer(public_lib::Context *ctx, ir::AstNode *ast)
236 {
237     ES2PANDA_ASSERT(ast->IsIdentifier());
238     auto *checker = ctx->checker->AsETSChecker();
239     auto *id = ast->AsIdentifier();
240 
241     // NOTE(gogabr): rely on caching for type instantiations, so we can use pointer comparison.
242     return id->Parent()->IsETSNewClassInstanceExpression() &&
243            id->Parent()->AsETSNewClassInstanceExpression()->GetTypeRef()->TsType() ==
244                checker->GlobalBuiltinBoxType(id->TsType());
245 }
246 
OnLeftSideOfAssignment(ir::AstNode * ast)247 static bool OnLeftSideOfAssignment(ir::AstNode *ast)
248 {
249     return ast->Parent()->IsAssignmentExpression() && ast->Parent()->AsAssignmentExpression()->Left() == ast;
250 }
251 
HandleReference(public_lib::Context * ctx,ir::Identifier * id,varbinder::Variable * var)252 static ir::AstNode *HandleReference(public_lib::Context *ctx, ir::Identifier *id, varbinder::Variable *var)
253 {
254     auto *parser = ctx->parser->AsETSParser();
255     auto *checker = ctx->checker->AsETSChecker();
256 
257     // `as` is needed to account for smart types
258     auto *res = parser->CreateFormattedExpression("@@I1.get() as @@T2", var->Name(), id->TsType());
259     res->SetParent(id->Parent());
260     res->AsTSAsExpression()
261         ->Expr()
262         ->AsCallExpression()
263         ->Callee()
264         ->AsMemberExpression()
265         ->Object()
266         ->AsIdentifier()
267         ->SetVariable(var);
268 
269     // NOTE(gogabr) -- The `get` property remains without variable; this is OK for the current checker, but may need
270     // adjustment later.
271     res->Check(checker);
272 
273     ES2PANDA_ASSERT(res->TsType() == id->TsType());
274     res->SetBoxingUnboxingFlags(id->GetBoxingUnboxingFlags());
275 
276     return res;
277 }
278 
HandleAssignment(public_lib::Context * ctx,ir::AssignmentExpression * ass,ArenaMap<varbinder::Variable *,varbinder::Variable * > const & varsMap)279 static ir::AstNode *HandleAssignment(public_lib::Context *ctx, ir::AssignmentExpression *ass,
280                                      ArenaMap<varbinder::Variable *, varbinder::Variable *> const &varsMap)
281 {
282     // Should be true after opAssignment lowering
283     ES2PANDA_ASSERT(ass->OperatorType() == lexer::TokenType::PUNCTUATOR_SUBSTITUTION);
284 
285     auto *parser = ctx->parser->AsETSParser();
286     auto *varBinder = ctx->checker->VarBinder()->AsETSBinder();
287     auto *checker = ctx->checker->AsETSChecker();
288 
289     auto *oldVar = ass->Left()->Variable();
290     auto *newVar = varsMap.find(oldVar)->second;
291     auto *scope = newVar->GetScope();
292     newVar->AddFlag(varbinder::VariableFlags::INITIALIZED);
293 
294     auto *res = parser->CreateFormattedExpression("@@I1.set(@@E2 as @@T3) as @@T4", newVar->Name(), ass->Right(),
295                                                   oldVar->TsType(), ass->TsType());
296     res->SetParent(ass->Parent());
297 
298     // NOTE(gogabr) -- The `get` and `set` properties remain without variable; this is OK for the current checker, but
299     // may need adjustment later.
300     auto lexScope = varbinder::LexicalScope<varbinder::Scope>::Enter(varBinder, scope);
301     auto savedContext = checker::SavedCheckerContext(checker, checker::CheckerStatus::NO_OPTS);
302     auto scopeContext = checker::ScopeContext(checker, scope);
303 
304     varBinder->ResolveReferencesForScopeWithContext(res, scope);
305     res->Check(checker);
306 
307     ES2PANDA_ASSERT(res->TsType() == ass->TsType());
308     res->SetBoxingUnboxingFlags(ass->GetBoxingUnboxingFlags());
309 
310     return res;
311 }
312 
HandleScriptFunction(public_lib::Context * ctx,ir::ScriptFunction * func)313 static void HandleScriptFunction(public_lib::Context *ctx, ir::ScriptFunction *func)
314 {
315     auto *allocator = ctx->allocator;
316     auto varsToBox = FindVariablesToBox(ctx, func);
317     if (varsToBox.empty()) {
318         return;
319     }
320     auto varsMap = ArenaMap<varbinder::Variable *, varbinder::Variable *>(allocator->Adapter());
321 
322     /*
323       The function relies on the following facts:
324       - TransformChildrenRecursively handles children in order
325       - local variables are never used before declaration.
326       This ensures that varsToMap has the appropriate record by the time the variable reference is processed.
327     */
328     auto handleNode = [ctx, &varsToBox, &varsMap](ir::AstNode *ast) {
329         if (ast->IsETSParameterExpression() && varsToBox.count(ast->AsETSParameterExpression()->Variable()) > 0) {
330             HandleFunctionParam(ctx, ast->AsETSParameterExpression(), &varsMap);
331             return ast;  // modifications occur in the containing function
332         }
333         if (ast->IsVariableDeclarator() && ast->AsVariableDeclarator()->Id()->IsIdentifier() &&
334             varsToBox.count(ast->AsVariableDeclarator()->Id()->AsIdentifier()->Variable()) > 0) {
335             return HandleVariableDeclarator(ctx, ast->AsVariableDeclarator(), &varsMap);
336         }
337         if (ast->IsAssignmentExpression() && ast->AsAssignmentExpression()->Left()->IsIdentifier() &&
338             varsToBox.count(ast->AsAssignmentExpression()->Left()->AsIdentifier()->Variable()) > 0) {
339             return HandleAssignment(ctx, ast->AsAssignmentExpression(), varsMap);
340         }
341         if (ast->IsIdentifier() && !IsBeingDeclared(ast) && !IsPartOfBoxInitializer(ctx, ast) &&
342             !OnLeftSideOfAssignment(ast) && varsToBox.count(ast->AsIdentifier()->Variable()) > 0) {
343             return HandleReference(ctx, ast->AsIdentifier(), varsMap.find(ast->AsIdentifier()->Variable())->second);
344         }
345 
346         return ast;
347     };
348 
349     func->TransformChildrenRecursivelyPostorder(handleNode, LOWERING_NAME);
350 }
351 
PerformForModule(public_lib::Context * ctx,parser::Program * program)352 bool BoxingForLocals::PerformForModule(public_lib::Context *ctx, parser::Program *program)
353 {
354     parser::SavedFormattingFileName savedFormattingName(ctx->parser->AsETSParser(), "boxing-for-lambdas");
355 
356     std::function<void(ir::AstNode *)> searchForFunctions = [&](ir::AstNode *ast) {
357         if (ast->IsScriptFunction()) {
358             HandleScriptFunction(ctx, ast->AsScriptFunction());  // no recursion
359         } else {
360             ast->Iterate(searchForFunctions);
361         }
362     };
363     program->Ast()->Iterate(searchForFunctions);
364     return true;
365 }
366 
PostconditionForModule(public_lib::Context * ctx,parser::Program const * program)367 bool BoxingForLocals::PostconditionForModule([[maybe_unused]] public_lib::Context *ctx, parser::Program const *program)
368 {
369     return !program->Ast()->IsAnyChild([](const ir::AstNode *node) {
370         if (node->IsAssignmentExpression() && node->AsAssignmentExpression()->Left()->IsIdentifier()) {
371             auto asExpr = node->AsAssignmentExpression();
372             auto var = asExpr->Left()->AsIdentifier()->Variable();
373             if (var != nullptr && var->IsLocalVariable() && !var->HasFlag(varbinder::VariableFlags::INITIALIZED)) {
374                 return true;
375             }
376         }
377         return false;
378     });
379 }
380 
381 }  // namespace ark::es2panda::compiler
382