1 /**
2 * Copyright (c) 2023-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 "promiseVoid.h"
17 #include "checker/ETSchecker.h"
18 #include "checker/checker.h"
19 #include "compiler/core/ASTVerifier.h"
20 #include "compiler/core/compilerContext.h"
21 #include "generated/signatures.h"
22 #include "ir/base/scriptFunction.h"
23 #include "ir/ets/etsTypeReference.h"
24 #include "ir/ets/etsTypeReferencePart.h"
25 #include "ir/expressions/functionExpression.h"
26 #include "ir/expressions/identifier.h"
27 #include "ir/statements/returnStatement.h"
28 #include "ir/typeNode.h"
29 #include "lexer/token/sourceLocation.h"
30 #include "ir/astNode.h"
31 #include "ir/statements/blockStatement.h"
32 #include "util/ustring.h"
33
34 namespace panda::es2panda::compiler {
HandleAsyncScriptFunctionBody(checker::ETSChecker * checker,ir::BlockStatement * body)35 static ir::BlockStatement *HandleAsyncScriptFunctionBody(checker::ETSChecker *checker, ir::BlockStatement *body)
36 {
37 (void)checker;
38 body->TransformChildrenRecursively([checker](ir::AstNode *ast) -> ir::AstNode * {
39 if (ast->IsReturnStatement()) {
40 auto *returnStmt = ast->AsReturnStatement();
41 const auto *arg = returnStmt->Argument();
42 if (arg == nullptr) {
43 auto *voidId =
44 checker->AllocNode<ir::Identifier>(compiler::Signatures::VOID_OBJECT, checker->Allocator());
45 const auto &returnLoc = returnStmt->Range();
46 voidId->SetRange({returnLoc.end, returnLoc.end});
47 returnStmt->SetArgument(voidId);
48 }
49 }
50 return ast;
51 });
52 return body;
53 }
54
SetRangeRecursively(ir::TypeNode * node,const lexer::SourceRange & loc)55 static void SetRangeRecursively(ir::TypeNode *node, const lexer::SourceRange &loc)
56 {
57 node->SetRange(loc);
58 node->TransformChildrenRecursively([loc](ir::AstNode *ast) -> ir::AstNode * {
59 ast->SetRange(loc);
60 return ast;
61 });
62 }
63
CreatePromiseVoidType(checker::ETSChecker * checker,const lexer::SourceRange & loc)64 static ir::TypeNode *CreatePromiseVoidType(checker::ETSChecker *checker, const lexer::SourceRange &loc)
65 {
66 auto *voidParam = [checker]() {
67 auto paramsVector = ArenaVector<ir::TypeNode *>(checker->Allocator()->Adapter());
68 auto *voidId =
69 checker->AllocNode<ir::Identifier>(compiler::Signatures::BUILTIN_VOID_CLASS, checker->Allocator());
70 voidId->SetReference();
71 auto *part = checker->AllocNode<ir::ETSTypeReferencePart>(voidId);
72 paramsVector.push_back(checker->AllocNode<ir::ETSTypeReference>(part));
73 auto *params = checker->AllocNode<ir::TSTypeParameterInstantiation>(std::move(paramsVector));
74 return params;
75 }();
76
77 auto *promiseVoidType = [checker, voidParam]() {
78 auto *promiseId =
79 checker->AllocNode<ir::Identifier>(compiler::Signatures::BUILTIN_PROMISE_CLASS, checker->Allocator());
80 promiseId->SetReference();
81 auto *part = checker->AllocNode<ir::ETSTypeReferencePart>(promiseId, voidParam, nullptr);
82 auto *type = checker->AllocNode<ir::ETSTypeReference>(part);
83 return type;
84 }();
85
86 SetRangeRecursively(promiseVoidType, loc);
87
88 return promiseVoidType;
89 }
90
CheckForPromiseVoid(const ir::TypeNode * type)91 static bool CheckForPromiseVoid(const ir::TypeNode *type)
92 {
93 if (type == nullptr || !type->IsETSTypeReference()) {
94 return false;
95 }
96
97 auto *typeRef = type->AsETSTypeReference();
98 auto *typePart = typeRef->Part();
99 if (typePart->Previous() != nullptr) {
100 return false;
101 }
102
103 const auto ¶ms = typePart->TypeParams()->Params();
104 if (params.size() != 1) {
105 return false;
106 }
107
108 const auto ¶m = params.at(0);
109 if (!param->IsETSTypeReference()) {
110 return false;
111 }
112
113 const auto *paramRef = param->AsETSTypeReference();
114 const auto *paramPart = paramRef->Part();
115 if (paramPart->Previous() != nullptr) {
116 return false;
117 }
118
119 const auto isTypePromise = typePart->Name()->AsIdentifier()->Name() == compiler::Signatures::BUILTIN_PROMISE_CLASS;
120 const auto isParamVoid = paramPart->Name()->AsIdentifier()->Name() == compiler::Signatures::BUILTIN_VOID_CLASS;
121
122 return isTypePromise && isParamVoid;
123 }
124
125 using AstNodePtr = ir::AstNode *;
126
127 /*
128 * Transformation is basically syntactical: it adds relevant return type and return statements to methods and function
129 * NOTE: but not for lambdas, at least for now
130 * So, the code
131 * async function f() {}
132 * transforms to
133 * async function f(): Promise<void> { return Void; }
134 * */
135
Perform(public_lib::Context * ctx,parser::Program * program)136 bool PromiseVoidInferencePhase::Perform(public_lib::Context *ctx, parser::Program *program)
137 {
138 auto *checker = ctx->checker->AsETSChecker();
139
140 auto genTypeLocation = [](ir::ScriptFunction *function) -> lexer::SourceRange {
141 const auto ¶ms = function->Params();
142 const auto &id = function->Id();
143 const auto &body = function->Body();
144 if (!params.empty()) {
145 const auto &last = params.back();
146 const auto &loc = last->Range();
147 return {loc.end, loc.end};
148 }
149
150 if (id != nullptr) {
151 const auto &loc = id->Range();
152 return {loc.end, loc.end};
153 }
154
155 if (function->HasBody()) {
156 const auto &loc = body->Range();
157 return {loc.start, loc.start};
158 }
159
160 const auto &loc = function->Range();
161 return {loc.end, loc.end};
162 };
163
164 const auto transformer = [checker, genTypeLocation](ir::AstNode *ast) -> AstNodePtr {
165 if (!(ast->IsScriptFunction() && ast->AsScriptFunction()->IsAsyncFunc())) {
166 return ast;
167 }
168
169 auto *function = ast->AsScriptFunction();
170 auto *returnAnn = function->ReturnTypeAnnotation();
171 const auto hasReturnAnn = returnAnn != nullptr;
172 const auto hasPromiseVoid = CheckForPromiseVoid(returnAnn);
173
174 if (!hasReturnAnn) {
175 const auto &loc = genTypeLocation(function);
176 function->SetReturnTypeAnnotation(CreatePromiseVoidType(checker, loc));
177
178 if (function->HasBody()) {
179 HandleAsyncScriptFunctionBody(checker, function->Body()->AsBlockStatement());
180 }
181 } else if (hasPromiseVoid && function->HasBody()) {
182 HandleAsyncScriptFunctionBody(checker, function->Body()->AsBlockStatement());
183 }
184
185 return ast;
186 };
187
188 program->Ast()->TransformChildrenRecursively(transformer);
189
190 return true;
191 }
192
Postcondition(public_lib::Context * ctx,const parser::Program * program)193 bool PromiseVoidInferencePhase::Postcondition(public_lib::Context *ctx, const parser::Program *program)
194 {
195 (void)ctx;
196
197 auto checkFunctionBody = [](const ir::BlockStatement *body) -> bool {
198 if (!body->IsReturnStatement()) {
199 return true;
200 }
201 auto *returnStmt = body->AsReturnStatement();
202 const auto *arg = returnStmt->Argument();
203
204 if (!arg->IsIdentifier()) {
205 return false;
206 }
207
208 const auto *id = arg->AsIdentifier();
209 return id->Name() == compiler::Signatures::VOID_OBJECT;
210
211 return true;
212 };
213
214 auto isOk = true;
215 auto transformer = [checkFunctionBody, &isOk](ir::AstNode *ast) {
216 if (!(ast->IsScriptFunction() && ast->AsScriptFunction()->IsAsyncFunc())) {
217 return;
218 }
219 auto *function = ast->AsScriptFunction();
220 auto *returnAnn = function->ReturnTypeAnnotation();
221 if (!CheckForPromiseVoid(returnAnn)) {
222 return;
223 }
224 if (function->HasBody()) {
225 if (!checkFunctionBody(function->Body()->AsBlockStatement())) {
226 isOk = false;
227 return;
228 }
229 }
230 };
231 program->Ast()->IterateRecursively(transformer);
232
233 return isOk;
234 }
235 } // namespace panda::es2panda::compiler
236