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 "variableNameIdentifierNameSame.h"
17 #include "ir/expressions/identifier.h"
18 #include "ir/ets/etsImportDeclaration.h"
19 
20 namespace ark::es2panda::compiler::ast_verifier {
21 
operator ()(CheckContext &ctx, const ir::AstNode *ast)22 [[nodiscard]] CheckResult VariableNameIdentifierNameSame::operator()(CheckContext &ctx, const ir::AstNode *ast)
23 {
24     if (!ast->IsIdentifier()) {
25         return {CheckDecision::CORRECT, CheckAction::CONTINUE};
26     }
27     const auto *id = ast->AsIdentifier();
28     const auto variable = ast->AsIdentifier()->Variable();
29     if (variable == nullptr || variable->Declaration() == nullptr || variable->Declaration()->Node() == nullptr) {
30         return {CheckDecision::CORRECT, CheckAction::CONTINUE};
31     }
32     const auto variableNode = variable->Declaration()->Node();
33     // NOTE(psaykerone): skip because, this exceptions need to be fixed in checker and lowering
34     if (variableNode->IsExported() || variableNode->IsExportedType() || variableNode->IsDefaultExported() ||
35         id->Name().Utf8().find("field") == 0 || variable->Name().Utf8().find("field") == 0) {
36         return {CheckDecision::CORRECT, CheckAction::CONTINUE};
37     }
38     if (id->Name() == variable->Name()) {
39         return {CheckDecision::CORRECT, CheckAction::CONTINUE};
40     }
41 
42     // For dynamic imports imported identifier name does not match variable name
43     // Example:
44     // import { A as AA } from "dynamic_js_import_tests"
45     // Variable name will be AA
46     // But imported identifier name is A
47     auto parent = ast->Parent();
48     while (parent != nullptr) {
49         if (parent->IsETSImportDeclaration() && parent->AsETSImportDeclaration()->IsPureDynamic()) {
50             return {CheckDecision::CORRECT, CheckAction::CONTINUE};
51         }
52 
53         parent = parent->Parent();
54     }
55 
56     ctx.AddCheckMessage("IDENTIFIER_NAME_DIFFERENCE", *id, id->Start());
57     return {CheckDecision::INCORRECT, CheckAction::CONTINUE};
58 }
59 
60 }  // namespace ark::es2panda::compiler::ast_verifier
61