swc_ecma_minifier/util/
unit.rs

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
#![allow(dead_code)]

use std::fmt::Debug;

use swc_ecma_ast::*;
use swc_ecma_transforms_base::{fixer::fixer, hygiene::hygiene};
use swc_ecma_utils::DropSpan;
use swc_ecma_visit::{visit_mut_pass, VisitMut, VisitMutWith};

use crate::debug::dump;

/// Indicates a unit of minifaction.
pub(crate) trait CompileUnit:
    swc_ecma_codegen::Node
    + Clone
    + VisitMutWith<DropSpan>
    + VisitMutWith<crate::debug::Debugger>
    + Debug
{
    fn is_module() -> bool;

    fn dump(&self) -> String {
        #[cfg(feature = "debug")]
        {
            self.force_dump()
        }
        #[cfg(not(feature = "debug"))]
        {
            String::new()
        }
    }

    fn force_dump(&self) -> String;

    fn apply<V>(&mut self, visitor: &mut V)
    where
        V: VisitMut;
}

impl CompileUnit for Module {
    fn is_module() -> bool {
        true
    }

    fn force_dump(&self) -> String {
        let _noop_sub =
            tracing::subscriber::set_default(tracing::subscriber::NoSubscriber::default());

        dump(
            &Program::Module(self.clone())
                .apply(fixer(None))
                .apply(hygiene())
                .apply(visit_mut_pass(DropSpan {})),
            true,
        )
    }

    fn apply<V>(&mut self, visitor: &mut V)
    where
        V: VisitMut,
    {
        self.visit_mut_with(&mut *visitor);

        crate::debug::invoke_module(self);
    }
}

impl CompileUnit for Script {
    fn is_module() -> bool {
        false
    }

    fn force_dump(&self) -> String {
        let _noop_sub =
            tracing::subscriber::set_default(tracing::subscriber::NoSubscriber::default());

        dump(
            &Program::Script(self.clone())
                .apply(fixer(None))
                .apply(hygiene())
                .apply(visit_mut_pass(DropSpan {})),
            true,
        )
    }

    fn apply<V>(&mut self, visitor: &mut V)
    where
        V: VisitMut,
    {
        self.visit_mut_with(&mut *visitor);

        crate::debug::invoke_script(self);
    }
}