1 /**
2 * Copyright (c) 2021 - 2023 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 "savedBindingsCtx.h"
17
18 #include <ir/module/exportDefaultDeclaration.h>
19 #include <ir/module/exportAllDeclaration.h>
20 #include <ir/statements/functionDeclaration.h>
21 #include <ir/base/scriptFunction.h>
22
23 namespace ark::es2panda::compiler {
24
BindImportDecl(ir::ImportDeclaration * importDecl)25 void ImportDeclarationContext::BindImportDecl(ir::ImportDeclaration *importDecl)
26 {
27 varbinder::ModuleScope::ImportDeclList declList(Allocator()->Adapter());
28
29 for (const auto &[name, variable] : VarBinder()->GetScope()->OrderedBindings(Allocator())) {
30 if (SavedBindings().find(name) != SavedBindings().end()) {
31 continue;
32 }
33
34 declList.push_back(variable->Declaration()->AsImportDecl());
35 }
36
37 VarBinder()->GetScope()->AsModuleScope()->AddImportDecl(importDecl, std::move(declList));
38 }
39
BindExportDecl(ir::AstNode * exportDecl)40 void ExportDeclarationContext::BindExportDecl(ir::AstNode *exportDecl)
41 {
42 if (VarBinder() == nullptr) {
43 return;
44 }
45
46 varbinder::ModuleScope::ExportDeclList declList(Allocator()->Adapter());
47
48 if (exportDecl->IsExportDefaultDeclaration()) {
49 auto *decl = exportDecl->AsExportDefaultDeclaration();
50 auto *rhs = decl->Decl();
51
52 if (VarBinder()->GetScope()->Bindings().size() == SavedBindings().size()) {
53 if (rhs->IsFunctionDeclaration()) {
54 VarBinder()->AddDecl<varbinder::FunctionDecl>(rhs->Start(), VarBinder()->Allocator(),
55 util::StringView(DEFAULT_EXPORT),
56 rhs->AsFunctionDeclaration()->Function());
57 } else {
58 VarBinder()->AddDecl<varbinder::ConstDecl>(rhs->Start(), util::StringView(DEFAULT_EXPORT));
59 }
60 }
61 }
62
63 for (const auto &[name, variable] : VarBinder()->GetScope()->Bindings()) {
64 if (SavedBindings().find(name) != SavedBindings().end()) {
65 continue;
66 }
67
68 util::StringView exportName(exportDecl->IsExportDefaultDeclaration() ? "default" : name);
69
70 variable->AddFlag(varbinder::VariableFlags::LOCAL_EXPORT);
71 auto *decl =
72 VarBinder()->AddDecl<varbinder::ExportDecl>(variable->Declaration()->Node()->Start(), exportName, name);
73 declList.push_back(decl);
74 }
75
76 auto *moduleScope = VarBinder()->GetScope()->AsModuleScope();
77 moduleScope->AddExportDecl(exportDecl, std::move(declList));
78 }
79
80 } // namespace ark::es2panda::compiler