farmfe_plugin_tree_shake 2.2.0

Tree shake plugin of farm.
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use std::{fmt, mem};

use farmfe_core::{
  HashMap, HashSet,
  module::{Module, ModuleId, ModuleSystem},
  swc_common::comments::SingleThreadedComments,
};

use crate::statement_graph::{
  ExportInfo, ExportSpecifierInfo, ImportInfo, StatementGraph, StatementId, UsedStatementIdent,
  traced_used_import::TracedUsedImportStatement,
};

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum UsedExportsIdent {
  /// Local ident
  SwcIdent(String),
  /// Default ident
  Default,
  /// All idents is used and may be exported from other module
  /// Marked as [UsedExportsIdent::ExportAll] when all potential exports of `export * from 'xxx'` are used.
  /// Usually works for side effect module(e.g. entry module) that re-export other modules
  ExportAll,
  /// All idents are used and may be imported from other module
  /// Marked as [UsedExportsIdent::ImportAll] when `import * as xx from 'xxx'` are used.
  ImportAll,
}

impl UsedExportsIdent {
  pub fn is_default(&self) -> bool {
    matches!(self, Self::Default)
  }

  pub fn is_ident_matched(&self, ident_name: &str) -> bool {
    matches!(self, Self::SwcIdent(i) if i == ident_name)
      || (ident_name == "default" && self.is_default()) // handle `export { a as default }`
  }

  pub fn expect_ident(&self) -> &str {
    if let Self::SwcIdent(ident) = self {
      ident.as_str()
    } else {
      unreachable!("called expect_ident of UsedExportsIdent on no SwcIdent value")
    }
  }
}

impl fmt::Display for UsedExportsIdent {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      UsedExportsIdent::SwcIdent(ident) => f.write_str(ident),
      UsedExportsIdent::Default => f.write_str("default"),
      UsedExportsIdent::ExportAll => f.write_str("*"),
      UsedExportsIdent::ImportAll => f.write_str("import_*_as"),
    }
  }
}

impl From<String> for UsedExportsIdent {
  fn from(value: String) -> Self {
    if value == "default" {
      Self::Default
    } else {
      Self::SwcIdent(value)
    }
  }
}

#[derive(Debug, Clone)]
pub enum UsedExports {
  All,
  Partial(HashSet<UsedExportsIdent>),
}

impl Default for UsedExports {
  fn default() -> Self {
    UsedExports::Partial(Default::default())
  }
}

impl UsedExports {
  pub fn extend(&mut self, other: UsedExports) {
    match (self, other) {
      (UsedExports::All, _) => {}
      (self_value, UsedExports::All) => {
        *self_value = UsedExports::All;
      }
      (UsedExports::Partial(self_used_exports), UsedExports::Partial(other_used_exports)) => {
        self_used_exports.extend(other_used_exports);
      }
    }
  }

  pub fn as_partial(&self) -> &HashSet<UsedExportsIdent> {
    match self {
      UsedExports::All => panic!("UsedExports is not Partial"),
      UsedExports::Partial(res) => res,
    }
  }

  pub fn add_used_export(&mut self, used_export: UsedExportsIdent) {
    // All means all exports are used, only handle Partial here
    if let UsedExports::Partial(used_exports) = self {
      used_exports.insert(used_export);
    }
  }

  pub fn is_empty(&self) -> bool {
    match self {
      UsedExports::All => false,
      UsedExports::Partial(used_exports) => used_exports.is_empty(),
    }
  }

  pub fn set_export_all(&mut self) {
    if let UsedExports::Partial(_) = self {
      *self = UsedExports::All;
    }
  }

  pub fn to_string_vec(&self) -> Vec<String> {
    match self {
      Self::Partial(self_used_exports) => self_used_exports.iter().map(|i| i.to_string()).collect(),
      Self::All => {
        vec!["All".to_string()]
      }
    }
  }

  pub fn contains(&self, used_export: &UsedExportsIdent) -> bool {
    match self {
      UsedExports::All => true,
      UsedExports::Partial(used_exports) => used_exports.contains(used_export),
    }
  }
}

// TODO cache tree shake module
pub struct TreeShakeModule {
  pub module_id: ModuleId,
  pub side_effects: bool,
  pub stmt_graph: StatementGraph,
  /// true if the module or it's dependency modules contains self executed statement or has side effects
  pub contains_self_executed_stmt: bool,
  /// used exports will be analyzed when tree shaking
  /// side effects statement will be added to used exports too.
  pub handled_used_exports: UsedExports,
  /// pending used exports will be used to analyze the used exports of the module
  pub pending_used_exports: UsedExports,
  pub module_system: ModuleSystem,
}

impl TreeShakeModule {
  pub fn new(module: &mut Module) -> Self {
    farmfe_core::farm_profile_function!(format!(
      "TreeShakeModule::new {:?}",
      module.id.to_string()
    ));
    let module_system = module.meta.as_script().module_system.clone();

    // 1. generate statement graph
    let comments_meta = module.meta.as_script_mut().take_comments();
    let ast = &module.meta.as_script().ast;
    let comments = SingleThreadedComments::from(comments_meta);
    let stmt_graph = if module_system == ModuleSystem::EsModule {
      StatementGraph::new(module, ast, &comments)
    } else {
      StatementGraph::empty()
    };

    module.meta.as_script_mut().set_comments(comments.into());

    // 2. set default used exports
    let handled_used_exports = UsedExports::Partial(Default::default());

    Self {
      module_id: module.id.clone(),
      contains_self_executed_stmt: !matches!(module_system, ModuleSystem::EsModule)
        || stmt_graph.contains_bare_import_stmt()
        || !stmt_graph.preserved_side_effects_stmts().is_empty(),
      stmt_graph,
      pending_used_exports: handled_used_exports.clone(),
      handled_used_exports,
      side_effects: module.side_effects,
      module_system,
    }
  }

  pub fn is_all_pending_used_exports_handled(&self) -> bool {
    self.pending_used_exports.is_empty()
  }

  pub fn is_used_exports_ident_handled(&self, used_export: &UsedExportsIdent) -> bool {
    match &self.handled_used_exports {
      UsedExports::All => true,
      UsedExports::Partial(used_exports) => used_exports.contains(used_export),
    }
  }

  pub fn clear_pending_used_exports(&mut self) {
    let current_pending_used_exports = mem::take(&mut self.pending_used_exports);

    match current_pending_used_exports {
      UsedExports::Partial(used_exports) => {
        for used_export in used_exports {
          self.handled_used_exports.add_used_export(used_export);
        }
      }
      UsedExports::All => {
        self.handled_used_exports = UsedExports::All;
      }
    }
  }

  pub fn imports(&self) -> Vec<&ImportInfo> {
    let mut imports = vec![];

    for stmt in self.stmt_graph.stmts() {
      if let Some(import) = &stmt.import_info {
        imports.push(import);
      }
    }

    imports
  }

  pub fn exports(&self) -> Vec<&ExportInfo> {
    let mut exports = vec![];

    for stmt in self.stmt_graph.stmts() {
      if let Some(export) = &stmt.export_info {
        exports.push(export);
      }
    }

    exports
  }

  pub fn get_stmt_used_idents_map(
    &self,
    used_exports_idents: Vec<(UsedStatementIdent, usize)>,
  ) -> HashMap<StatementId, HashSet<UsedStatementIdent>> {
    let mut stmt_used_idents_map = HashMap::default();

    for (used_ident, stmt_id) in used_exports_idents {
      let used_idents = stmt_used_idents_map
        .entry(stmt_id)
        .or_insert(HashSet::default());
      used_idents.insert(used_ident);
    }

    stmt_used_idents_map
  }

  /// Trace the used statement starting from pending_used_exports and mark them as used.
  /// Then merge pending_used_exports into used_exports
  pub fn trace_and_mark_used_statements(&mut self) -> Vec<TracedUsedImportStatement> {
    // 1. get used exports
    let used_exports_idents = self.used_exports_to_statement_idents();
    let stmt_used_idents_map = self.get_stmt_used_idents_map(used_exports_idents);

    // 2. trace used statements starting from used exports
    self
      .stmt_graph
      .trace_and_mark_used_statements(stmt_used_idents_map, None)
  }

  /// For param include_default_export: If it's false, the default export will not be included,
  /// for example, export * from 'xxx' should not include default export
  fn all_exports_to_statement_idents(
    &self,
    include_default_export: bool,
  ) -> Vec<(UsedStatementIdent, StatementId)> {
    let mut used_idents = vec![];

    for export_info in self.exports() {
      for sp in &export_info.specifiers {
        match sp {
          ExportSpecifierInfo::Default => {
            if include_default_export {
              used_idents.push((UsedStatementIdent::Default, export_info.stmt_id));
            }
          }
          ExportSpecifierInfo::Named { local, .. } => {
            used_idents.push((
              UsedStatementIdent::SwcIdent(local.clone()),
              export_info.stmt_id,
            ));
          }
          ExportSpecifierInfo::Namespace(ns) => {
            used_idents.push((
              UsedStatementIdent::SwcIdent(ns.clone()),
              export_info.stmt_id,
            ));
          }
          ExportSpecifierInfo::All => {
            used_idents.push((UsedStatementIdent::ExportAll, export_info.stmt_id));
          }
        }
      }
    }

    used_idents
  }

  pub fn used_exports_to_statement_idents(&self) -> Vec<(UsedStatementIdent, StatementId)> {
    farmfe_core::farm_profile_function!(format!(
      "used_exports_idents {:?}",
      self.module_id.to_string()
    ));

    match &self.pending_used_exports {
      UsedExports::All => {
        // all exported identifiers are used
        self.all_exports_to_statement_idents(true)
      }
      UsedExports::Partial(idents) => {
        // statement `import * as xxx from './xxx'` is marked as used, and the usage can not be statically determined, e.g. xxx[expr].
        // so we need to mark all exported idents as used the same as UsedExports::All
        if idents.contains(&UsedExportsIdent::ImportAll) {
          // all export information needs to be collected
          return self.all_exports_to_statement_idents(true);
        }
        // statement `export * from './xxx'` is marked as used, we need to mark all exported idents as used the same as UsedExports::All
        // except the default export when idents does not contain default export
        if idents.contains(&UsedExportsIdent::ExportAll) {
          return self.all_exports_to_statement_idents(idents.contains(&UsedExportsIdent::Default));
        }

        self.used_exports_idents_to_statement_idents(idents)
      }
    }
  }

  pub fn used_exports_idents_to_statement_idents(
    &self,
    idents: &HashSet<UsedExportsIdent>,
  ) -> Vec<(UsedStatementIdent, StatementId)> {
    let mut used_idents = vec![];

    // find exported ident for every used idents.
    for ident in idents {
      let mut export_all_stmt_ids: Option<Vec<usize>> = None;
      // find the export info that contains the ident
      let export_info = self.exports().into_iter().find(|export_info| {
        export_info.specifiers.iter().any(|sp| match sp {
          ExportSpecifierInfo::Default => ident.is_default(),
          ExportSpecifierInfo::Named { local, exported } => {
            let exported_ident = if let Some(exported) = exported {
              exported
            } else {
              local
            };

            ident.is_ident_matched(exported_ident.sym.as_str())
          }
          ExportSpecifierInfo::Namespace(ns) => ident.is_ident_matched(ns.sym.as_str()),
          ExportSpecifierInfo::All => {
            /* Deal with All later */
            if let Some(export_all_stmt_id) = &mut export_all_stmt_ids {
              export_all_stmt_id.push(export_info.stmt_id);
            } else {
              export_all_stmt_ids = Some(vec![export_info.stmt_id]);
            }
            false
          }
        })
      });

      if let Some(export_info) = export_info {
        for sp in &export_info.specifiers {
          match sp {
            ExportSpecifierInfo::Default => {
              if ident.is_default() {
                used_idents.push((UsedStatementIdent::Default, export_info.stmt_id));
              }
            }
            ExportSpecifierInfo::Named { local, exported } => {
              if let Some(exported) = exported {
                if ident.is_ident_matched(exported.sym.as_str()) {
                  used_idents.push((
                    UsedStatementIdent::SwcIdent(local.clone()),
                    export_info.stmt_id,
                  ));
                }
              } else if ident.is_ident_matched(local.sym.as_str()) {
                used_idents.push((
                  UsedStatementIdent::SwcIdent(local.clone()),
                  export_info.stmt_id,
                ));
              }
            }
            ExportSpecifierInfo::Namespace(ns) => {
              if ident.is_ident_matched(ns.sym.as_str()) {
                used_idents.push((
                  UsedStatementIdent::SwcIdent(ns.clone()),
                  export_info.stmt_id,
                ));
              }
            }
            ExportSpecifierInfo::All => {
              unreachable!()
            }
          }
        }
      } else {
        // if export info is not found, and there are ExportSpecifierInfo::All, then the ident may be exported by `export * from 'xxx'`
        if let Some(export_all_stmt_id) = export_all_stmt_ids {
          let ident = ident.expect_ident().to_string();
          // skip default for export * from 'xxx'
          if ident != *"default" {
            for export_all_stmt_id in export_all_stmt_id {
              used_idents.push((
                UsedStatementIdent::InExportAll(ident.clone()),
                export_all_stmt_id,
              ));
            }
          }
        }
      }
    }

    used_idents
  }
}