• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "aliveAnalyzer.h"
17 #include <cstddef>
18 
19 #include "checker/types/ets/etsAsyncFuncReturnType.h"
20 #include "ir/base/classDefinition.h"
21 #include "ir/base/classProperty.h"
22 #include "ir/base/methodDefinition.h"
23 #include "ir/base/scriptFunction.h"
24 #include "ir/statements/classDeclaration.h"
25 #include "ir/statements/variableDeclaration.h"
26 #include "ir/statements/doWhileStatement.h"
27 #include "ir/statements/expressionStatement.h"
28 #include "ir/statements/whileStatement.h"
29 #include "ir/statements/forUpdateStatement.h"
30 #include "ir/statements/labelledStatement.h"
31 #include "ir/statements/forOfStatement.h"
32 #include "ir/statements/blockStatement.h"
33 #include "ir/statements/ifStatement.h"
34 #include "ir/statements/switchStatement.h"
35 #include "ir/statements/variableDeclarator.h"
36 #include "ir/statements/throwStatement.h"
37 #include "ir/statements/switchCaseStatement.h"
38 #include "ir/statements/breakStatement.h"
39 #include "ir/statements/continueStatement.h"
40 #include "ir/statements/returnStatement.h"
41 #include "ir/statements/tryStatement.h"
42 #include "ir/expressions/callExpression.h"
43 #include "ir/expressions/identifier.h"
44 #include "ir/ets/etsNewClassInstanceExpression.h"
45 #include "ir/ets/etsStructDeclaration.h"
46 #include "ir/ts/tsInterfaceDeclaration.h"
47 #include "checker/types/globalTypesHolder.h"
48 #include "varbinder/variable.h"
49 #include "varbinder/declaration.h"
50 #include "checker/ETSchecker.h"
51 #include "ir/base/catchClause.h"
52 
53 namespace ark::es2panda::checker {
54 
AnalyzeNodes(const ir::AstNode * node)55 void AliveAnalyzer::AnalyzeNodes(const ir::AstNode *node)
56 {
57     node->Iterate([this](auto *childNode) { AnalyzeNode(childNode); });
58 }
59 
AnalyzeNode(const ir::AstNode * node)60 void AliveAnalyzer::AnalyzeNode(const ir::AstNode *node)
61 {
62     if (node == nullptr) {
63         return;
64     }
65 
66     switch (node->Type()) {
67         case ir::AstNodeType::EXPRESSION_STATEMENT: {
68             AnalyzeNode(node->AsExpressionStatement()->GetExpression());
69             break;
70         }
71         case ir::AstNodeType::STRUCT_DECLARATION: {
72             AnalyzeStructDecl(node->AsETSStructDeclaration());
73             break;
74         }
75         case ir::AstNodeType::CLASS_DECLARATION: {
76             AnalyzeClassDecl(node->AsClassDeclaration());
77             break;
78         }
79         case ir::AstNodeType::METHOD_DEFINITION: {
80             AnalyzeMethodDef(node->AsMethodDefinition());
81             break;
82         }
83         case ir::AstNodeType::VARIABLE_DECLARATION: {
84             AnalyzeVarDef(node->AsVariableDeclaration());
85             break;
86         }
87         case ir::AstNodeType::BLOCK_STATEMENT: {
88             AnalyzeStats(node->AsBlockStatement()->Statements());
89             break;
90         }
91         case ir::AstNodeType::DO_WHILE_STATEMENT: {
92             AnalyzeDoLoop(node->AsDoWhileStatement());
93             break;
94         }
95         default: {
96             break;
97         }
98     }
99 
100     // Helpers to reduce function size and pass code checker
101     AnalyzeNodeHelper1(node);
102     AnalyzeNodeHelper2(node);
103 }
104 
105 // Helper function to reduce AnalyzeNode size and pass code checker
AnalyzeNodeHelper1(const ir::AstNode * node)106 void AliveAnalyzer::AnalyzeNodeHelper1(const ir::AstNode *node)
107 {
108     switch (node->Type()) {
109         case ir::AstNodeType::WHILE_STATEMENT: {
110             AnalyzeWhileLoop(node->AsWhileStatement());
111             break;
112         }
113         case ir::AstNodeType::FOR_UPDATE_STATEMENT: {
114             AnalyzeForLoop(node->AsForUpdateStatement());
115             break;
116         }
117         case ir::AstNodeType::FOR_OF_STATEMENT: {
118             AnalyzeForOfLoop(node->AsForOfStatement());
119             break;
120         }
121         case ir::AstNodeType::IF_STATEMENT: {
122             AnalyzeIf(node->AsIfStatement());
123             break;
124         }
125         case ir::AstNodeType::LABELLED_STATEMENT: {
126             AnalyzeLabelled(node->AsLabelledStatement());
127             break;
128         }
129         case ir::AstNodeType::ETS_NEW_CLASS_INSTANCE_EXPRESSION: {
130             AnalyzeNewClass(node->AsETSNewClassInstanceExpression());
131             break;
132         }
133         case ir::AstNodeType::CALL_EXPRESSION: {
134             AnalyzeCall(node->AsCallExpression());
135             break;
136         }
137         case ir::AstNodeType::THROW_STATEMENT: {
138             AnalyzeThrow(node->AsThrowStatement());
139             break;
140         }
141         case ir::AstNodeType::SWITCH_STATEMENT: {
142             AnalyzeSwitch(node->AsSwitchStatement());
143             break;
144         }
145         default: {
146             break;
147         }
148     }
149 }
150 
151 // Helper function to reduce AnalyzeNode size and pass code checker
AnalyzeNodeHelper2(const ir::AstNode * node)152 void AliveAnalyzer::AnalyzeNodeHelper2(const ir::AstNode *node)
153 {
154     switch (node->Type()) {
155         case ir::AstNodeType::TRY_STATEMENT: {
156             AnalyzeTry(node->AsTryStatement());
157             break;
158         }
159         case ir::AstNodeType::BREAK_STATEMENT: {
160             AnalyzeBreak(node->AsBreakStatement());
161             break;
162         }
163         case ir::AstNodeType::CONTINUE_STATEMENT: {
164             AnalyzeContinue(node->AsContinueStatement());
165             break;
166         }
167         case ir::AstNodeType::RETURN_STATEMENT: {
168             AnalyzeReturn(node->AsReturnStatement());
169             break;
170         }
171         default: {
172             break;
173         }
174     }
175 }
176 
AnalyzeDef(const ir::AstNode * node)177 void AliveAnalyzer::AnalyzeDef(const ir::AstNode *node)
178 {
179     AnalyzeStat(node);
180     if (node != nullptr && node->IsClassStaticBlock() && status_ == LivenessStatus::DEAD) {
181         checker_->ThrowTypeError("Initializer must be able to complete normally.", node->Start());
182     }
183 }
184 
AnalyzeStat(const ir::AstNode * node)185 void AliveAnalyzer::AnalyzeStat(const ir::AstNode *node)
186 {
187     if (node == nullptr) {
188         return;
189     }
190 
191     if (status_ == LivenessStatus::DEAD) {
192         checker_->ThrowTypeError("Unreachable statement.", node->Start());
193     }
194 
195     if (node->IsClassStaticBlock()) {
196         AnalyzeNodes(node);
197         return;
198     }
199 
200     AnalyzeNode(node);
201 }
202 
AnalyzeStats(const ArenaVector<ir::Statement * > & stats)203 void AliveAnalyzer::AnalyzeStats(const ArenaVector<ir::Statement *> &stats)
204 {
205     for (const auto *it : stats) {
206         AnalyzeStat(it);
207     }
208 }
209 
AnalyzeStructDecl(const ir::ETSStructDeclaration * structDecl)210 void AliveAnalyzer::AnalyzeStructDecl(const ir::ETSStructDeclaration *structDecl)
211 {
212     for (const auto *it : structDecl->Definition()->Body()) {
213         AnalyzeNode(it);
214     }
215 }
216 
AnalyzeClassDecl(const ir::ClassDeclaration * classDecl)217 void AliveAnalyzer::AnalyzeClassDecl(const ir::ClassDeclaration *classDecl)
218 {
219     LivenessStatus prevStatus = status_;
220 
221     for (const auto *it : classDecl->Definition()->Body()) {
222         AnalyzeNode(it);
223     }
224 
225     status_ = prevStatus;
226 }
227 
AnalyzeMethodDef(const ir::MethodDefinition * methodDef)228 void AliveAnalyzer::AnalyzeMethodDef(const ir::MethodDefinition *methodDef)
229 {
230     auto *func = methodDef->Function();
231 
232     if (func->Body() == nullptr || func->IsProxy()) {
233         return;
234     }
235 
236     status_ = LivenessStatus::ALIVE;
237     AnalyzeStat(func->Body());
238     ASSERT(methodDef->TsType() && methodDef->TsType()->IsETSFunctionType());
239     const auto *returnType = methodDef->TsType()->AsETSFunctionType()->FindSignature(func)->ReturnType();
240     const auto isVoid = returnType->IsETSVoidType() || returnType == checker_->GlobalVoidType();
241 
242     auto isPromiseVoid = false;
243 
244     if (returnType->IsETSAsyncFuncReturnType()) {
245         const auto *asAsync = returnType->AsETSAsyncFuncReturnType();
246         isPromiseVoid = asAsync->GetPromiseTypeArg() == checker_->GlobalETSUndefinedType();
247     }
248 
249     if (status_ == LivenessStatus::ALIVE && !isVoid && !isPromiseVoid && !checker_->IsAsyncImplMethod(methodDef)) {
250         if (!methodDef->Function()->HasReturnStatement()) {
251             checker_->ThrowTypeError("Function with a non void return type must return a value.", func->Id()->Start());
252         }
253 
254         checker_->ThrowTypeError("Not all code paths return a value.", func->Id()->Start());
255     }
256 
257     ClearPendingExits();
258 }
259 
AnalyzeVarDef(const ir::VariableDeclaration * varDef)260 void AliveAnalyzer::AnalyzeVarDef(const ir::VariableDeclaration *varDef)
261 {
262     for (auto *it : varDef->Declarators()) {
263         if (it->Init() == nullptr) {
264             continue;
265         }
266 
267         AnalyzeNode(it->Init());
268     }
269 }
270 
AnalyzeDoLoop(const ir::DoWhileStatement * doWhile)271 void AliveAnalyzer::AnalyzeDoLoop(const ir::DoWhileStatement *doWhile)
272 {
273     SetOldPendingExits(PendingExits());
274     AnalyzeStat(doWhile->Body());
275     status_ = Or(status_, ResolveContinues(doWhile));
276     AnalyzeNode(doWhile->Test());
277     ASSERT(doWhile->Test()->TsType() && doWhile->Test()->TsType()->IsConditionalExprType());
278     const auto exprRes = doWhile->Test()->TsType()->ResolveConditionExpr();
279     status_ = And(status_, static_cast<LivenessStatus>(!std::get<0>(exprRes) || !std::get<1>(exprRes)));
280     status_ = Or(status_, ResolveBreaks(doWhile));
281 }
282 
AnalyzeWhileLoop(const ir::WhileStatement * whileStmt)283 void AliveAnalyzer::AnalyzeWhileLoop(const ir::WhileStatement *whileStmt)
284 {
285     SetOldPendingExits(PendingExits());
286     AnalyzeNode(whileStmt->Test());
287     ASSERT(whileStmt->Test()->TsType() && whileStmt->Test()->TsType()->IsConditionalExprType());
288     const auto exprRes = whileStmt->Test()->TsType()->ResolveConditionExpr();
289     status_ = And(status_, static_cast<LivenessStatus>(!std::get<0>(exprRes) || std::get<1>(exprRes)));
290     AnalyzeStat(whileStmt->Body());
291     status_ = Or(status_, ResolveContinues(whileStmt));
292     status_ = Or(ResolveBreaks(whileStmt), From(!std::get<0>(exprRes) || !std::get<1>(exprRes)));
293 }
294 
AnalyzeForLoop(const ir::ForUpdateStatement * forStmt)295 void AliveAnalyzer::AnalyzeForLoop(const ir::ForUpdateStatement *forStmt)
296 {
297     AnalyzeNode(forStmt->Init());
298     SetOldPendingExits(PendingExits());
299     const Type *condType {};
300     bool resolveType = false;
301     bool res = false;
302 
303     if (forStmt->Test() != nullptr) {
304         AnalyzeNode(forStmt->Test());
305         ASSERT(forStmt->Test()->TsType() && forStmt->Test()->TsType()->IsConditionalExprType());
306         condType = forStmt->Test()->TsType();
307         std::tie(resolveType, res) = forStmt->Test()->TsType()->ResolveConditionExpr();
308         status_ = From(!resolveType || res);
309     } else {
310         status_ = LivenessStatus::ALIVE;
311     }
312 
313     AnalyzeStat(forStmt->Body());
314     status_ = Or(status_, ResolveContinues(forStmt));
315     AnalyzeNode(forStmt->Update());
316     status_ = Or(ResolveBreaks(forStmt), From(condType != nullptr && (!resolveType || !res)));
317 }
318 
AnalyzeForOfLoop(const ir::ForOfStatement * forOfStmt)319 void AliveAnalyzer::AnalyzeForOfLoop(const ir::ForOfStatement *forOfStmt)
320 {
321     //  Note: iterator definition can be a reference to variable defined in outer scope!
322     if (forOfStmt->Left()->IsVariableDeclaration()) {
323         AnalyzeVarDef(forOfStmt->Left()->AsVariableDeclaration());
324     } else {
325         AnalyzeNode(forOfStmt->Left());
326     }
327     AnalyzeNode(forOfStmt->Right());
328     SetOldPendingExits(PendingExits());
329 
330     AnalyzeStat(forOfStmt->Body());
331     status_ = Or(status_, ResolveContinues(forOfStmt));
332     ResolveBreaks(forOfStmt);
333     status_ = LivenessStatus::ALIVE;
334 }
335 
AnalyzeIf(const ir::IfStatement * ifStmt)336 void AliveAnalyzer::AnalyzeIf(const ir::IfStatement *ifStmt)
337 {
338     AnalyzeNode(ifStmt->Test());
339     AnalyzeStat(ifStmt->Consequent());
340     if (ifStmt->Alternate() != nullptr) {
341         LivenessStatus prevStatus = status_;
342         status_ = LivenessStatus::ALIVE;
343         AnalyzeStat(ifStmt->Alternate());
344         status_ = Or(status_, prevStatus);
345     } else {
346         status_ = LivenessStatus::ALIVE;
347     }
348 }
349 
AnalyzeLabelled(const ir::LabelledStatement * labelledStmt)350 void AliveAnalyzer::AnalyzeLabelled(const ir::LabelledStatement *labelledStmt)
351 {
352     SetOldPendingExits(PendingExits());
353     AnalyzeStat(labelledStmt->Body());
354     status_ = Or(status_, ResolveBreaks(labelledStmt));
355 }
356 
AnalyzeNewClass(const ir::ETSNewClassInstanceExpression * newClass)357 void AliveAnalyzer::AnalyzeNewClass(const ir::ETSNewClassInstanceExpression *newClass)
358 {
359     for (const auto *it : newClass->GetArguments()) {
360         AnalyzeNode(it);
361     }
362 
363     if (newClass->ClassDefinition() != nullptr) {
364         AnalyzeNode(newClass->ClassDefinition());
365     }
366 }
367 
AnalyzeCall(const ir::CallExpression * callExpr)368 void AliveAnalyzer::AnalyzeCall(const ir::CallExpression *callExpr)
369 {
370     AnalyzeNode(callExpr->Callee());
371     for (const auto *it : callExpr->Arguments()) {
372         AnalyzeNode(it);
373     }
374     if (callExpr->Signature()->ReturnType() == checker_->GetGlobalTypesHolder()->GlobalBuiltinNeverType()) {
375         MarkDead();
376     }
377 }
378 
AnalyzeThrow(const ir::ThrowStatement * throwStmt)379 void AliveAnalyzer::AnalyzeThrow(const ir::ThrowStatement *throwStmt)
380 {
381     AnalyzeNode(throwStmt->Argument());
382     MarkDead();
383 }
384 
AnalyzeSwitch(const ir::SwitchStatement * switchStmt)385 void AliveAnalyzer::AnalyzeSwitch(const ir::SwitchStatement *switchStmt)
386 {
387     SetOldPendingExits(PendingExits());
388 
389     AnalyzeNode(switchStmt->Discriminant());
390 
391     bool hasDefault = false;
392     for (std::size_t i = 0, size = switchStmt->Cases().size(); i < size; i++) {
393         const auto *caseClause = switchStmt->Cases()[i];
394         status_ = LivenessStatus::ALIVE;
395 
396         if (caseClause->Test() == nullptr) {
397             hasDefault = true;
398         } else {
399             AnalyzeNode(caseClause->Test());
400         }
401 
402         AnalyzeStats(caseClause->Consequent());
403 
404         if (status_ == LivenessStatus::ALIVE && !caseClause->Consequent().empty() && i < size - 1) {
405             // NOTE(user) Add lint categories and option to enable/disable compiler warnings
406             checker_->Warning("Possible fall-through into case", caseClause->Start());
407         }
408     }
409 
410     if (!hasDefault) {
411         status_ = LivenessStatus::ALIVE;
412     }
413 
414     status_ = Or(status_, ResolveBreaks(switchStmt));
415 }
416 
AnalyzeBreak(const ir::BreakStatement * breakStmt)417 void AliveAnalyzer::AnalyzeBreak(const ir::BreakStatement *breakStmt)
418 {
419     RecordExit(PendingExit(breakStmt));
420 }
421 
AnalyzeContinue(const ir::ContinueStatement * contStmt)422 void AliveAnalyzer::AnalyzeContinue(const ir::ContinueStatement *contStmt)
423 {
424     RecordExit(PendingExit(contStmt));
425 }
426 
AnalyzeReturn(const ir::ReturnStatement * retStmt)427 void AliveAnalyzer::AnalyzeReturn(const ir::ReturnStatement *retStmt)
428 {
429     AnalyzeNode(retStmt->Argument());
430     RecordExit(PendingExit(retStmt));
431 }
432 
AnalyzeTry(const ir::TryStatement * tryStmt)433 void AliveAnalyzer::AnalyzeTry(const ir::TryStatement *tryStmt)
434 {
435     status_ = LivenessStatus::ALIVE;
436     bool isAlive = false;
437     AnalyzeStats(tryStmt->Block()->Statements());
438 
439     if (status_ != LivenessStatus::DEAD) {
440         isAlive = true;
441     }
442 
443     for (const auto &it : tryStmt->CatchClauses()) {
444         status_ = LivenessStatus::ALIVE;
445         AnalyzeStats(it->Body()->Statements());
446         if (status_ == LivenessStatus::ALIVE) {
447             isAlive = true;
448         }
449     }
450 
451     if (tryStmt->FinallyBlock() != nullptr) {
452         status_ = LivenessStatus::ALIVE;
453         AnalyzeStats(tryStmt->FinallyBlock()->Statements());
454         const_cast<ir::TryStatement *>(tryStmt)->SetFinallyCanCompleteNormally(status_ == LivenessStatus::ALIVE);
455         if (status_ == LivenessStatus::DEAD) {
456             isAlive = false;
457             // NOTE(user) Add lint categories and option to enable/disable compiler warnings
458             checker_->Warning("Finally clause cannot complete normally", tryStmt->FinallyBlock()->Start());
459         }
460     }
461 
462     status_ = isAlive ? LivenessStatus::ALIVE : LivenessStatus::DEAD;
463 }
464 }  // namespace ark::es2panda::checker
465