forked from denoland/deno_ast
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexports.rs
More file actions
245 lines (226 loc) · 6.95 KB
/
exports.rs
File metadata and controls
245 lines (226 loc) · 6.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use serde::Deserialize;
use serde::Serialize;
use crate::ParsedSource;
use crate::ProgramRef;
use crate::swc::ast::ExportSpecifier;
use crate::swc::ast::ModuleDecl;
use crate::swc::ast::ModuleItem;
use crate::swc::atoms::Atom;
use crate::swc::utils::find_pat_ids;
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ModuleExportsAndReExports {
pub exports: Vec<String>,
pub reexports: Vec<String>,
}
impl ParsedSource {
/// Analyzes the ES runtime exports for require ESM.
///
/// This is used during CJS export analysis when a CJS module
/// re-exports an ESM module and the original CJS module needs
/// to know the exports of the ESM module so it can create its
/// wrapper ESM module.
pub fn analyze_es_runtime_exports(&self) -> ModuleExportsAndReExports {
let mut result = ModuleExportsAndReExports::default();
if let ProgramRef::Module(n) = self.program_ref() {
for m in &n.body {
match m {
ModuleItem::ModuleDecl(m) => match m {
ModuleDecl::Import(_) => {}
ModuleDecl::ExportAll(n) => {
result
.reexports
.push(n.src.value.to_string_lossy().into_owned());
}
ModuleDecl::ExportDecl(d) => {
match &d.decl {
swc_ecma_ast::Decl::Class(d) => {
result.exports.push(d.ident.sym.to_string());
}
swc_ecma_ast::Decl::Fn(d) => {
result.exports.push(d.ident.sym.to_string());
}
swc_ecma_ast::Decl::Var(d) => {
for d in &d.decls {
for id in find_pat_ids::<_, Atom>(&d.name) {
result.exports.push(id.to_string());
}
}
}
swc_ecma_ast::Decl::TsEnum(d) => {
result.exports.push(d.id.sym.to_string())
}
swc_ecma_ast::Decl::TsModule(ts_module_decl) => {
match &ts_module_decl.id {
swc_ecma_ast::TsModuleName::Ident(ident) => {
result.exports.push(ident.sym.to_string())
}
swc_ecma_ast::TsModuleName::Str(_) => {
// ignore
}
}
}
swc_ecma_ast::Decl::Using(d) => {
for d in &d.decls {
for id in find_pat_ids::<_, Atom>(&d.name) {
result.exports.push(id.to_string());
}
}
}
swc_ecma_ast::Decl::TsInterface(_)
| swc_ecma_ast::Decl::TsTypeAlias(_) => {
// ignore types
}
}
}
ModuleDecl::ExportNamed(n) => {
for s in &n.specifiers {
match s {
ExportSpecifier::Namespace(s) => {
result.exports.push(s.name.atom().to_string());
}
ExportSpecifier::Default(_) => {
result.exports.push("default".to_string());
}
ExportSpecifier::Named(n) => {
result.exports.push(
n.exported
.as_ref()
.map(|e| e.atom().to_string())
.unwrap_or_else(|| n.orig.atom().to_string()),
);
}
}
}
}
ModuleDecl::ExportDefaultExpr(_)
| ModuleDecl::ExportDefaultDecl(_) => {
result.exports.push("default".to_string());
}
ModuleDecl::TsImportEquals(_)
| ModuleDecl::TsExportAssignment(_) => {
// ignore because it's cjs
}
ModuleDecl::TsNamespaceExport(_) => {
// ignore `export as namespace x;` as it's type only
}
},
ModuleItem::Stmt(_) => {}
}
}
}
result
}
}
#[cfg(test)]
mod test {
use std::cell::RefCell;
use deno_media_type::MediaType;
use crate::ModuleSpecifier;
use crate::ParseParams;
use crate::parse_module;
use super::ModuleExportsAndReExports;
struct Tester {
analysis: RefCell<ModuleExportsAndReExports>,
}
impl Tester {
pub fn assert_exports(&self, values: Vec<&str>) {
let mut analysis = self.analysis.borrow_mut();
assert_eq!(analysis.exports, values);
analysis.exports.clear();
}
pub fn assert_reexports(&self, values: Vec<&str>) {
let mut analysis = self.analysis.borrow_mut();
assert_eq!(analysis.reexports, values);
analysis.reexports.clear();
}
pub fn assert_empty(&self) {
let analysis = self.analysis.borrow();
if !analysis.exports.is_empty() {
panic!("Had exports: {}", analysis.exports.join(", "))
}
if !analysis.reexports.is_empty() {
panic!("Had reexports: {}", analysis.reexports.join(", "))
}
}
}
impl Drop for Tester {
fn drop(&mut self) {
// ensures that all values have been asserted for
if !std::thread::panicking() {
self.assert_empty();
}
}
}
fn parse(source: &str) -> Tester {
let parsed_source = parse_module(ParseParams {
specifier: ModuleSpecifier::parse("file:///example.ts").unwrap(),
text: source.into(),
media_type: MediaType::TypeScript,
capture_tokens: true,
scope_analysis: false,
maybe_syntax: None,
})
.unwrap();
let analysis = parsed_source.analyze_es_runtime_exports();
Tester {
analysis: RefCell::new(analysis),
}
}
#[test]
fn runtime_exports_basic() {
let tester = parse(
"
export class A {}
export enum B {}
export module C.Test {}
export namespace C2.Test {}
export function d() {}
export const e = 1, f = 2;
export { g, h1 as h, other as 'testing-this' };
export * as y from './other.js';
export { z } from './other.js';
class Ignored1 {}
enum Ignored2 {}
module Ignored3 {}
namespace Ignored4 {}
function Ignored5() {}
const Ignored6 = 1;
",
);
tester.assert_exports(vec![
"A",
"B",
"C",
"C2",
"d",
"e",
"f",
"g",
"h",
"testing-this",
"y",
"z",
]);
}
#[test]
fn runtime_exports_default_expr() {
let tester = parse("export default 5;");
tester.assert_exports(vec!["default"]);
}
#[test]
fn runtime_exports_default_decl() {
let tester = parse("export default class MyClass {}");
tester.assert_exports(vec!["default"]);
}
#[test]
fn runtime_exports_default_named_export() {
let tester = parse("export { a as default }");
tester.assert_exports(vec!["default"]);
}
#[test]
fn runtime_re_export() {
let tester = parse("export * from './other.js';");
tester.assert_reexports(vec!["./other.js"]);
}
}