1 /**
2 * Copyright (c) 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 "convertPrimitiveCastMethodCall.h"
17
18 #include "checker/ETSchecker.h"
19 #include "compiler/lowering/util.h"
20
21 namespace ark::es2panda::compiler {
22
Name() const23 std::string_view ConvertPrimitiveCastMethodCall::Name() const
24 {
25 return "ConvertPrimitiveCastMethodCall";
26 }
27
28 // Convert all MemberExpressions like 'a.toInt()' where 'a' has any primitive type into AsExpression like 'a as int'
ConvertMemberExpressionToAsExpression(ir::CallExpression * call,checker::ETSChecker * checker)29 static ir::AstNode *ConvertMemberExpressionToAsExpression(ir::CallExpression *call, checker::ETSChecker *checker)
30 {
31 auto allocator = checker->Allocator();
32 auto me = call->Callee()->AsMemberExpression();
33 auto toType = call->Signature()->ReturnType();
34
35 auto res = util::NodeAllocator::ForceSetParent<ir::TSAsExpression>(
36 allocator, me->Object()->Clone(allocator, nullptr)->AsExpression(),
37 checker->AllocNode<ir::OpaqueTypeNode>(toType, allocator), false);
38 res->SetParent(call->Parent());
39 res->SetBoxingUnboxingFlags(call->GetBoxingUnboxingFlags());
40
41 {
42 auto scope = varbinder::LexicalScope<varbinder::Scope>::Enter(checker->VarBinder(), NearestScope(me));
43 CheckLoweredNode(checker->VarBinder()->AsETSBinder(), checker, res);
44 }
45 return res;
46 }
47
PerformForModule(public_lib::Context * const ctx,parser::Program * const program)48 bool ConvertPrimitiveCastMethodCall::PerformForModule(public_lib::Context *const ctx, parser::Program *const program)
49 {
50 auto checker = ctx->checker->AsETSChecker();
51 program->Ast()->TransformChildrenRecursively(
52 // CC-OFFNXT(G.FMT.14-CPP) project code style
53 [checker](checker::AstNodePtr ast) -> checker::AstNodePtr {
54 if (ast->IsCallExpression() && ast->AsCallExpression()->Callee()->IsMemberExpression() &&
55 ast->AsCallExpression()->Callee()->HasAstNodeFlags(
56 ir::AstNodeFlags::TMP_CONVERT_PRIMITIVE_CAST_METHOD_CALL)) {
57 return ConvertMemberExpressionToAsExpression(ast->AsCallExpression(), checker);
58 }
59 return ast;
60 },
61 Name());
62
63 return true;
64 }
65
66 } // namespace ark::es2panda::compiler
67