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
use std::sync::Arc;

use parking_lot::Mutex;
use swc_atoms::js_word;
use swc_common::{collections::AHashMap, SyntaxContext, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_transforms_optimization::simplify::{expr_simplifier, ExprSimplifierConfig};
use swc_ecma_usage_analyzer::marks::Marks;
use swc_ecma_utils::{undefined, ExprCtx, ExprExt};
use swc_ecma_visit::VisitMutWith;

use crate::{
    compress::{compressor, pure_optimizer, PureOptimizerConfig},
    mode::Mode,
    option::{CompressOptions, TopLevelOptions},
};

pub struct Evaluator {
    expr_ctx: ExprCtx,

    module: Module,
    marks: Marks,
    data: Eval,
    /// We run minification only once.
    done: bool,
}

impl Evaluator {
    pub fn new(module: Module, marks: Marks) -> Self {
        Evaluator {
            expr_ctx: ExprCtx {
                unresolved_ctxt: SyntaxContext::empty().apply_mark(marks.unresolved_mark),
                is_unresolved_ref_safe: false,
            },

            module,
            marks,
            data: Default::default(),
            done: Default::default(),
        }
    }
}

#[derive(Default, Clone)]
struct Eval {
    store: Arc<Mutex<EvalStore>>,
}

#[derive(Default)]
struct EvalStore {
    cache: AHashMap<Id, Box<Expr>>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EvalResult {
    Lit(Lit),
    Undefined,
}

impl Mode for Eval {
    fn store(&self, id: Id, value: &Expr) {
        let mut w = self.store.lock();
        w.cache.insert(id, Box::new(value.clone()));
    }

    fn preserve_vars(&self) -> bool {
        true
    }

    fn should_be_very_correct(&self) -> bool {
        false
    }

    fn force_str_for_tpl(&self) -> bool {
        true
    }
}

impl Evaluator {
    #[tracing::instrument(name = "Evaluator::run", level = "debug", skip_all)]
    fn run(&mut self) {
        if !self.done {
            self.done = true;

            let marks = self.marks;
            let data = self.data.clone();
            //
            self.module.visit_mut_with(&mut compressor(
                marks,
                &CompressOptions {
                    // We should not drop unused variables.
                    unused: false,
                    top_level: Some(TopLevelOptions { functions: true }),
                    ..Default::default()
                },
                None,
                &data,
            ));
        }
    }

    pub fn eval(&mut self, e: &Expr) -> Option<EvalResult> {
        match e {
            Expr::Seq(s) => return self.eval(s.exprs.last()?),

            Expr::Lit(
                l @ Lit::Num(..)
                | l @ Lit::Str(..)
                | l @ Lit::BigInt(..)
                | l @ Lit::Bool(..)
                | l @ Lit::Null(..),
            ) => return Some(EvalResult::Lit(l.clone())),

            Expr::Tpl(t) => {
                return self.eval_tpl(t);
            }

            Expr::TaggedTpl(t) => {
                // Handle `String.raw`

                match &*t.tag {
                    Expr::Member(MemberExpr {
                        obj: tag_obj,
                        prop: MemberProp::Ident(prop),
                        ..
                    }) if tag_obj.is_global_ref_to(&self.expr_ctx, "String")
                        && prop.sym == *"raw" =>
                    {
                        return self.eval_tpl(&t.tpl);
                    }

                    _ => {}
                }
            }

            Expr::Cond(c) => {
                let test = self.eval(&c.test)?;

                if is_truthy(&test)? {
                    return self.eval(&c.cons);
                } else {
                    return self.eval(&c.alt);
                }
            }

            // TypeCastExpression, ExpressionStatement etc
            Expr::TsTypeAssertion(e) => {
                return self.eval(&e.expr);
            }

            Expr::TsConstAssertion(e) => {
                return self.eval(&e.expr);
            }

            // "foo".length
            Expr::Member(MemberExpr { obj, prop, .. })
                if obj.is_lit() && prop.is_ident_with("length") => {}

            Expr::Unary(UnaryExpr {
                op: op!("void"), ..
            }) => return Some(EvalResult::Undefined),

            Expr::Unary(UnaryExpr {
                op: op!("!"), arg, ..
            }) => {
                let arg = self.eval(arg)?;

                if is_truthy(&arg)? {
                    return Some(EvalResult::Lit(Lit::Bool(Bool {
                        span: DUMMY_SP,
                        value: false,
                    })));
                } else {
                    return Some(EvalResult::Lit(Lit::Bool(Bool {
                        span: DUMMY_SP,
                        value: true,
                    })));
                }
            }

            _ => {}
        }

        Some(EvalResult::Lit(self.eval_as_expr(e)?.lit()?))
    }

    fn eval_as_expr(&mut self, e: &Expr) -> Option<Box<Expr>> {
        match e {
            Expr::Ident(i) => {
                self.run();

                let lock = self.data.store.lock();
                let val = lock.cache.get(&i.to_id())?;

                return Some(val.clone());
            }

            Expr::Member(MemberExpr {
                span, obj, prop, ..
            }) if !prop.is_computed() => {
                let obj = self.eval_as_expr(obj)?;

                let mut e = Expr::Member(MemberExpr {
                    span: *span,
                    obj,
                    prop: prop.clone(),
                });

                e.visit_mut_with(&mut expr_simplifier(
                    self.marks.unresolved_mark,
                    ExprSimplifierConfig {},
                ));
                return Some(Box::new(e));
            }
            _ => {}
        }

        None
    }

    pub fn eval_tpl(&mut self, q: &Tpl) -> Option<EvalResult> {
        self.run();

        let mut exprs = vec![];

        for expr in &q.exprs {
            let res = self.eval(expr)?;
            exprs.push(match res {
                EvalResult::Lit(v) => Box::new(Expr::Lit(v)),
                EvalResult::Undefined => undefined(DUMMY_SP),
            });
        }

        let mut e = Expr::Tpl(Tpl {
            span: q.span,
            exprs,
            quasis: q.quasis.clone(),
        });

        {
            e.visit_mut_with(&mut pure_optimizer(
                &Default::default(),
                None,
                self.marks,
                PureOptimizerConfig {
                    enable_join_vars: false,
                    force_str_for_tpl: self.data.force_str_for_tpl(),
                    #[cfg(feature = "debug")]
                    debug_infinite_loop: false,
                },
            ));
        }

        Some(EvalResult::Lit(e.lit()?))
    }
}

fn is_truthy(lit: &EvalResult) -> Option<bool> {
    match lit {
        EvalResult::Lit(v) => match v {
            Lit::Str(v) => Some(v.value != js_word!("")),
            Lit::Bool(v) => Some(v.value),
            Lit::Null(_) => Some(false),
            Lit::Num(v) => Some(v.value != 0.0 && v.value != -0.0),
            _ => None,
        },
        EvalResult::Undefined => Some(false),
    }
}