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