1 /*
2  * Copyright (c) 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 "everyChildHasValidParent.h"
17 #include "ir/base/methodDefinition.h"
18 
19 namespace ark::es2panda::compiler::ast_verifier {
20 
operator ()(CheckContext &ctx, const ir::AstNode *ast)21 CheckResult EveryChildHasValidParent::operator()(CheckContext &ctx, const ir::AstNode *ast)
22 {
23     auto result = std::make_tuple(CheckDecision::CORRECT, CheckAction::CONTINUE);
24     if (ast->IsETSScript()) {
25         return result;
26     }
27 
28     auto maybeOverloadMethod = [](const ir::AstNode *root, const ir::AstNode *node) -> bool {
29         if (root->IsClassDefinition() && node->IsMethodDefinition() && node->Parent()->IsMethodDefinition()) {
30             auto maybeBaseOverloadMethod = node->Parent()->AsMethodDefinition();
31             auto overloads = maybeBaseOverloadMethod->Overloads();
32             auto res =
33                 std::find_if(overloads.begin(), overloads.end(), [node](ir::MethodDefinition *m) { return m == node; });
34             return res != overloads.end();
35         }
36         return false;
37     };
38 
39     ast->Iterate([&](const ir::AstNode *node) {
40         if (ir::AstNode const *parent = node->Parent(); ast != parent) {
41             //  NOTE: Temporary suppress.
42             //  Should be removed after new ENUMs support will be implemented: #14443
43             if (ast->IsClassDeclaration() && parent != nullptr && parent->IsETSNewClassInstanceExpression()) {
44                 return;
45             }
46 
47             //  NOTE: Temporary suppress.
48             //  Should be removed after proper overload method's parent setting
49             //  For now there is no right decision who is parent of overload method:
50             //  baseOverloadMethod or ClassDefininiton, but the first is set
51             if (maybeOverloadMethod(ast, node)) {
52                 return;
53             }
54 
55             ctx.AddCheckMessage("INCORRECT_PARENT_REF", *node, node->Start());
56             result = {CheckDecision::INCORRECT, CheckAction::CONTINUE};
57         }
58     });
59 
60     return result;
61 }
62 
63 }  // namespace ark::es2panda::compiler::ast_verifier
64