Skip to main content

turbopack_ecmascript/analyzer/
mod.rs

1use swc_core::{
2    common::Mark,
3    ecma::ast::{Id, Ident},
4};
5
6pub(crate) use self::imports::ImportMap;
7
8pub mod builtin;
9pub mod bump_vec;
10pub(crate) mod cjs_ast;
11pub mod graph;
12pub mod imports;
13pub mod linker;
14pub mod side_effects;
15pub mod top_level_await;
16pub mod well_known;
17
18mod jsvalue;
19pub use bump_vec::BumpVec;
20pub use bumpalo::Bump;
21pub use jsvalue::*;
22pub use thread_local::ThreadLocal;
23pub use well_known::{kinds::*, require_context::*};
24
25fn is_unresolved(i: &Ident, unresolved_mark: Mark) -> bool {
26    i.ctxt.outer() == unresolved_mark
27}
28
29fn is_unresolved_id(i: &Id, unresolved_mark: Mark) -> bool {
30    i.1.outer() == unresolved_mark
31}
32
33/// Whether a visitor — or one of the builtin / well-known rewrite helpers —
34/// changed the `JsValue` it was given. Returned alongside the (possibly
35/// rewritten) value. [`Modified::Yes`] makes the linker re-enter the value for
36/// further processing; [`Modified::No`] means it is final.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum Modified {
39    Yes,
40    No,
41}
42
43impl Modified {
44    /// `true` if the value was modified.
45    pub fn is_modified(self) -> bool {
46        matches!(self, Modified::Yes)
47    }
48}
49
50impl From<bool> for Modified {
51    fn from(modified: bool) -> Self {
52        if modified {
53            Modified::Yes
54        } else {
55            Modified::No
56        }
57    }
58}
59
60#[doc(hidden)]
61pub mod test_utils {
62    use anyhow::Result;
63    use turbo_rcstr::rcstr;
64    use turbo_tasks::{FxIndexMap, PrettyPrintError, Vc};
65    use turbopack_core::compile_time_info::CompileTimeInfo;
66
67    use super::{
68        ConstantValue, JsValue, JsValueUrlKind, Modified, ModuleValue, WellKnownFunctionKind,
69        WellKnownObjectKind,
70        builtin::early_replace_builtin,
71        well_known::{replace_well_known, replace_well_known_global},
72    };
73    use crate::{
74        analyzer::{
75            Bump, RequireContextValue, ThreadLocal, builtin::replace_builtin,
76            imports::ImportAttributes, parse_require_context,
77        },
78        utils::module_value_to_well_known_object,
79    };
80
81    pub async fn early_visitor<'a>(
82        _arena: &'a ThreadLocal<Bump>,
83        mut v: JsValue<'a>,
84    ) -> Result<(JsValue<'a>, Modified)> {
85        let m = early_replace_builtin(&mut v);
86        Ok((v, m))
87    }
88
89    /// Visitor that replaces well known functions and objects with their
90    /// corresponding values. Returns the new value and whether it was modified.
91    pub async fn visitor<'a>(
92        arena: &'a ThreadLocal<Bump>,
93        mut v: JsValue<'a>,
94        compile_time_info: Vc<CompileTimeInfo>,
95        attributes: &ImportAttributes,
96    ) -> Result<(JsValue<'a>, Modified)> {
97        let ImportAttributes { ignore, .. } = *attributes;
98        if replace_well_known_global(&mut v, ignore) {
99            return Ok((v, Modified::Yes));
100        }
101        let mut new_value = match v {
102            JsValue::Call(_, ref call)
103                if matches!(
104                    call.callee(),
105                    JsValue::WellKnownFunction(WellKnownFunctionKind::Import)
106                ) =>
107            {
108                match &call.args()[0] {
109                    JsValue::Constant(ConstantValue::Str(v)) => JsValue::promise(
110                        arena.get_or_default(),
111                        JsValue::Module(ModuleValue {
112                            module: v.as_atom().into_owned().into(),
113                            annotations: None,
114                            analyze_for_constants: false,
115                            reference: None,
116                        }),
117                    ),
118                    _ => v.into_unknown(true, rcstr!("import() non constant")),
119                }
120            }
121            JsValue::Call(_, ref call)
122                if matches!(
123                    call.callee(),
124                    JsValue::WellKnownFunction(WellKnownFunctionKind::CreateRequire)
125                ) =>
126            {
127                if let [JsValue::Member(_, obj, prop)] = call.args()
128                    && matches!(
129                        &**obj,
130                        JsValue::WellKnownObject(WellKnownObjectKind::ImportMeta)
131                    )
132                    && let JsValue::Constant(ConstantValue::Str(prop)) = &**prop
133                    && prop.as_str() == "url"
134                {
135                    JsValue::WellKnownFunction(WellKnownFunctionKind::Require)
136                } else {
137                    v.into_unknown(true, rcstr!("createRequire() non constant"))
138                }
139            }
140            JsValue::Call(_, ref call)
141                if matches!(
142                    call.callee(),
143                    JsValue::WellKnownFunction(WellKnownFunctionKind::RequireResolve)
144                ) =>
145            {
146                match &call.args()[0] {
147                    JsValue::Constant(v) => (v.to_string() + "/resolved/lib/index.js").into(),
148                    _ => v.into_unknown(true, rcstr!("require.resolve non constant")),
149                }
150            }
151            JsValue::Call(_, ref call)
152                if matches!(
153                    call.callee(),
154                    JsValue::WellKnownFunction(WellKnownFunctionKind::ImportMetaGlob)
155                ) =>
156            {
157                v.into_unknown(false, rcstr!("import.meta.glob()"))
158            }
159            JsValue::Call(_, ref call)
160                if matches!(
161                    call.callee(),
162                    JsValue::WellKnownFunction(WellKnownFunctionKind::RequireContext)
163                ) =>
164            {
165                match parse_require_context(call.args()) {
166                    Ok(options) => {
167                        let mut map = FxIndexMap::default();
168
169                        map.insert(
170                            rcstr!("./a"),
171                            format!("[context: {}]/a", options.dir).into(),
172                        );
173                        map.insert(
174                            rcstr!("./b"),
175                            format!("[context: {}]/b", options.dir).into(),
176                        );
177                        map.insert(
178                            rcstr!("./c"),
179                            format!("[context: {}]/c", options.dir).into(),
180                        );
181
182                        JsValue::WellKnownFunction(WellKnownFunctionKind::RequireContextRequire(
183                            Box::new(RequireContextValue(map)),
184                        ))
185                    }
186                    Err(err) => v.into_unknown(true, PrettyPrintError(&err).to_string().into()),
187                }
188            }
189            JsValue::New(_, ref call)
190                if matches!(
191                    call.callee(),
192                    JsValue::WellKnownFunction(WellKnownFunctionKind::URLConstructor)
193                ) =>
194            {
195                if let [
196                    JsValue::Constant(ConstantValue::Str(url)),
197                    JsValue::Member(_, obj, prop),
198                ] = call.args()
199                    && matches!(
200                        &**obj,
201                        JsValue::WellKnownObject(WellKnownObjectKind::ImportMeta)
202                    )
203                    && let JsValue::Constant(ConstantValue::Str(prop)) = &**prop
204                {
205                    if prop.as_str() == "url" {
206                        // TODO avoid clone
207                        JsValue::Url(url.clone(), JsValueUrlKind::Relative)
208                    } else {
209                        v.into_unknown(true, rcstr!("new non constant"))
210                    }
211                } else {
212                    v.into_unknown(true, rcstr!("new non constant"))
213                }
214            }
215            JsValue::FreeVar(ref var) => match &**var {
216                "__dirname" => rcstr!("__dirname").into(),
217                "__filename" => rcstr!("__filename").into(),
218
219                "require" => JsValue::unknown_if(
220                    ignore,
221                    JsValue::WellKnownFunction(WellKnownFunctionKind::Require),
222                    true,
223                    rcstr!("ignored require"),
224                ),
225                "import" => JsValue::unknown_if(
226                    ignore,
227                    JsValue::WellKnownFunction(WellKnownFunctionKind::Import),
228                    true,
229                    rcstr!("ignored import"),
230                ),
231                // Globals like `process` or `URL` are handled by `replace_well_known_global`
232                // above.
233                "define" => JsValue::WellKnownFunction(WellKnownFunctionKind::Define),
234                _ => v.into_unknown(true, rcstr!("unknown global")),
235            },
236            JsValue::Module(ref mv) => {
237                if let Some(wko) = module_value_to_well_known_object(mv) {
238                    wko
239                } else {
240                    return Ok((v, Modified::No));
241                }
242            }
243            _ => {
244                let (mut v, m1) = replace_well_known(arena, v, compile_time_info, true).await?;
245                let m2 = replace_builtin(arena.get_or_default(), &mut v);
246                let m = if m1.is_modified() || m2.is_modified() {
247                    Modified::Yes
248                } else {
249                    Modified::from(v.make_nested_operations_unknown())
250                };
251                return Ok((v, m));
252            }
253        };
254        new_value.normalize_shallow(arena.get_or_default());
255        Ok((new_value, Modified::Yes))
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use std::{mem::take, path::PathBuf, sync::Arc, time::Instant};
262
263    use bumpalo::boxed::Box as BumpBox;
264    use parking_lot::Mutex;
265    use rustc_hash::FxHashMap;
266    use swc_core::{
267        common::{
268            FileName, FilePathMapping, GLOBALS, Globals, Mark, SourceMap,
269            comments::SingleThreadedComments,
270        },
271        ecma::{
272            ast::{EsVersion, Id},
273            parser::parse_file_as_program,
274            transforms::base::resolver,
275            visit::VisitMutWith,
276        },
277        testing::{NormalizedOutput, fixture},
278    };
279    use turbo_rcstr::{RcStr, rcstr};
280    use turbo_tasks::{ResolvedVc, TurboTasks, util::FormatDuration};
281    use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
282    use turbopack_core::{
283        compile_time_info::CompileTimeInfo,
284        environment::{Environment, ExecutionEnvironment, NodeJsEnvironment, NodeJsVersion},
285        target::{Arch, CompileTarget, Endianness, Libc, Platform},
286    };
287
288    use super::{
289        BumpVec, JsValue,
290        graph::{ConditionalKind, Effect, EffectArg, EvalContext, VarGraph, create_graph},
291        linker::link,
292    };
293    use crate::{
294        AnalyzeMode, SpecifiedModuleType,
295        analyzer::{Bump, ThreadLocal, graph::AssignmentScopes, imports::ImportAttributes},
296    };
297
298    #[fixture("tests/analyzer/graph/**/input.js")]
299    fn fixture(input: PathBuf) {
300        let input = RcStr::from(input.to_str().unwrap());
301        let rt = tokio::runtime::Builder::new_multi_thread()
302            .worker_threads(2)
303            .enable_all()
304            .build()
305            .unwrap();
306        rt.block_on(async move {
307            let tt = TurboTasks::new(TurboTasksBackend::new(
308                BackendOptions::default(),
309                noop_backing_storage(),
310            ));
311            tt.run_once(async move {
312                fixture_op(input).read_strongly_consistent().await?;
313                anyhow::Ok(())
314            })
315            .await
316            .unwrap();
317        });
318    }
319
320    #[turbo_tasks::function(operation, root)]
321    async fn fixture_op(input: RcStr) -> anyhow::Result<()> {
322        let input = PathBuf::from(input.as_str());
323        let graph_snapshot_path = input.with_file_name("graph.snapshot");
324        let graph_explained_snapshot_path = input.with_file_name("graph-explained.snapshot");
325        let graph_effects_snapshot_path = input.with_file_name("graph-effects.snapshot");
326        let resolved_explained_snapshot_path = input.with_file_name("resolved-explained.snapshot");
327        let resolved_effects_snapshot_path = input.with_file_name("resolved-effects.snapshot");
328        let large_marker = input.with_file_name("large");
329
330        let cm: Arc<SourceMap> = Arc::new(SourceMap::new(FilePathMapping::empty()));
331        let globals = Arc::new(Globals::new());
332        let arena = ThreadLocal::new();
333
334        // Keep all non-`Send` SWC types (`SingleThreadedComments`, `Lrc<SourceFile>`)
335        // confined to this synchronous block so they don't have to cross an `.await`
336        // and break the `Send` bound on `tt.run_once`'s future.
337        let (eval_context, mut var_graph) = GLOBALS.set(&globals, || {
338            let fm = cm.load_file(&input).unwrap();
339            let comments = SingleThreadedComments::default();
340            let mut m = parse_file_as_program(
341                &fm,
342                Default::default(),
343                EsVersion::latest(),
344                Some(&comments),
345                &mut vec![],
346            )
347            .map_err(|err| anyhow::anyhow!("parse error: {err:?}"))?;
348
349            let unresolved_mark = Mark::new();
350            let top_level_mark = Mark::new();
351            m.visit_mut_with(&mut resolver(unresolved_mark, top_level_mark, false));
352
353            let eval_context = EvalContext::new(
354                Some(&m),
355                unresolved_mark,
356                top_level_mark,
357                Default::default(),
358                Some(&comments),
359            );
360
361            let var_graph = create_graph(
362                arena.get_or_default(),
363                &m,
364                &eval_context,
365                AnalyzeMode::code_generation_and_tracing(),
366                SpecifiedModuleType::EcmaScript,
367                true,
368                false,
369            );
370            anyhow::Ok((eval_context, var_graph))
371        })?;
372        let var_cache = Default::default();
373
374        let mut named_values = var_graph
375            .values
376            .iter()
377            .map(|((id, ctx), value)| {
378                let unique = var_graph.values.keys().filter(|(i, _)| id == i).count() == 1;
379                let value = value.clone_in(arena.get_or_default());
380                if unique {
381                    (id.to_string(), ((id.clone(), *ctx), value))
382                } else {
383                    (format!("{id}{ctx:?}"), ((id.clone(), *ctx), value))
384                }
385            })
386            .collect::<Vec<_>>();
387        named_values.sort_by(|a, b| a.0.cmp(&b.0));
388
389        fn explain_all<'x, 'a: 'x>(
390            values: impl IntoIterator<Item = (&'x String, &'x JsValue<'a>, Option<AssignmentScopes>)>,
391        ) -> String {
392            values
393                .into_iter()
394                .map(|(id, value, assignment_scopes)| {
395                    let non_root_assignments = match assignment_scopes {
396                        Some(AssignmentScopes::AllInModuleEvalScope) => " (const after eval)",
397                        _ => "",
398                    };
399                    let (explainer, hints) = value.explain(10, 5);
400                    format!("{id}{non_root_assignments} = {explainer}{hints}")
401                })
402                .collect::<Vec<_>>()
403                .join("\n\n")
404        }
405
406        {
407            // Dump snapshot of graph
408
409            let large = large_marker.exists();
410
411            if !large {
412                NormalizedOutput::from(format!(
413                    "{:#?}",
414                    named_values
415                        .iter()
416                        .map(|(name, (_, value))| (name, value))
417                        .collect::<Vec<_>>()
418                ))
419                .compare_to_file(&graph_snapshot_path)
420                .unwrap();
421            }
422            NormalizedOutput::from(explain_all(named_values.iter().map(
423                |(name, (id, value))| {
424                    (
425                        name,
426                        value,
427                        eval_context.imports.assignment_scopes.get(id).copied(),
428                    )
429                },
430            )))
431            .compare_to_file(&graph_explained_snapshot_path)
432            .unwrap();
433            if !large {
434                NormalizedOutput::from(format!("{:#?}", var_graph.effects))
435                    .compare_to_file(&graph_effects_snapshot_path)
436                    .unwrap();
437            }
438        }
439
440        {
441            // Dump snapshot of resolved
442
443            let start = Instant::now();
444            let mut resolved = Vec::new();
445            for (name, id) in named_values.iter().map(|(name, (id, _))| (name, id)) {
446                let start = Instant::now();
447                // Ideally this would use eval_context.imports.get_attributes(span), but the
448                // span isn't available here
449                let (res, steps) = resolve(
450                    &arena,
451                    &var_graph,
452                    JsValue::Variable(id.clone()),
453                    ImportAttributes::empty_ref(),
454                    &var_cache,
455                )
456                .await;
457                let time = start.elapsed();
458                if time.as_millis() > 1 {
459                    println!(
460                        "linking {} {name} took {} in {} steps",
461                        input.display(),
462                        FormatDuration(time),
463                        steps
464                    );
465                }
466
467                resolved.push((name.clone(), res));
468            }
469            let time = start.elapsed();
470            if time.as_millis() > 1 {
471                println!("linking {} took {}", input.display(), FormatDuration(time));
472            }
473
474            let start = Instant::now();
475            let explainer = explain_all(resolved.iter().map(|(name, value)| (name, value, None)));
476            let time = start.elapsed();
477            if time.as_millis() > 1 {
478                println!(
479                    "explaining {} took {}",
480                    input.display(),
481                    FormatDuration(time)
482                );
483            }
484
485            NormalizedOutput::from(explainer)
486                .compare_to_file(&resolved_explained_snapshot_path)
487                .unwrap();
488        }
489
490        {
491            // Dump snapshot of resolved effects
492
493            let start = Instant::now();
494            let mut resolved = Vec::new();
495            let mut queue = take(&mut var_graph.effects)
496                .into_iter()
497                .map(|effect| (0, effect))
498                .rev()
499                .collect::<Vec<_>>();
500            let mut i = 0;
501            while let Some((parent, effect)) = queue.pop() {
502                i += 1;
503                let start = Instant::now();
504                async fn handle_args<'a>(
505                    arena: &'a ThreadLocal<Bump>,
506                    args: BumpVec<'a, EffectArg<'a>>,
507                    queue: &mut Vec<(usize, Effect<'a>)>,
508                    var_graph: &VarGraph<'a>,
509                    var_cache: &Mutex<FxHashMap<Id, JsValue<'a>>>,
510                    i: usize,
511                ) -> Vec<JsValue<'a>> {
512                    let mut new_args = Vec::with_capacity(args.len());
513                    for arg in args {
514                        match arg {
515                            EffectArg::Value(v, effects) => {
516                                queue.extend(
517                                    BumpVec::from(effects).into_iter().rev().map(|e| (i, e)),
518                                );
519                                new_args.push(
520                                    resolve(
521                                        arena,
522                                        var_graph,
523                                        v,
524                                        ImportAttributes::empty_ref(),
525                                        var_cache,
526                                    )
527                                    .await
528                                    .0,
529                                );
530                            }
531                            EffectArg::Closure(v, effects) => {
532                                new_args.push(
533                                    resolve(
534                                        arena,
535                                        var_graph,
536                                        v,
537                                        ImportAttributes::empty_ref(),
538                                        var_cache,
539                                    )
540                                    .await
541                                    .0,
542                                );
543                                queue.extend(
544                                    BumpVec::from(BumpBox::into_inner(effects).effects)
545                                        .into_iter()
546                                        .rev()
547                                        .map(|e| (i, e)),
548                                );
549                            }
550                            EffectArg::Spread(effects) => {
551                                queue.extend(
552                                    BumpVec::from(effects).into_iter().rev().map(|e| (i, e)),
553                                );
554                                new_args.push(JsValue::unknown_empty(true, rcstr!("spread")));
555                            }
556                        }
557                    }
558                    new_args
559                }
560                let steps = match effect {
561                    Effect::Conditional {
562                        mut condition,
563                        kind,
564                        ..
565                    } => {
566                        let (condition, steps) = resolve(
567                            &arena,
568                            &var_graph,
569                            take(&mut *condition),
570                            ImportAttributes::empty_ref(),
571                            &var_cache,
572                        )
573                        .await;
574                        resolved.push((format!("{parent} -> {i} conditional"), condition));
575                        match BumpBox::into_inner(kind) {
576                            ConditionalKind::If { then } => {
577                                queue.extend(
578                                    BumpVec::from(then.effects)
579                                        .into_iter()
580                                        .rev()
581                                        .map(|e| (i, e)),
582                                );
583                            }
584                            ConditionalKind::Else { r#else } => {
585                                queue.extend(
586                                    BumpVec::from(r#else.effects)
587                                        .into_iter()
588                                        .rev()
589                                        .map(|e| (i, e)),
590                                );
591                            }
592                            ConditionalKind::IfElse { then, r#else }
593                            | ConditionalKind::Ternary { then, r#else } => {
594                                queue.extend(
595                                    BumpVec::from(r#else.effects)
596                                        .into_iter()
597                                        .rev()
598                                        .map(|e| (i, e)),
599                                );
600                                queue.extend(
601                                    BumpVec::from(then.effects)
602                                        .into_iter()
603                                        .rev()
604                                        .map(|e| (i, e)),
605                                );
606                            }
607                            ConditionalKind::IfElseMultiple { then, r#else } => {
608                                for then in BumpVec::from(then) {
609                                    queue.extend(
610                                        BumpVec::from(then.effects)
611                                            .into_iter()
612                                            .rev()
613                                            .map(|e| (i, e)),
614                                    );
615                                }
616                                for r#else in BumpVec::from(r#else) {
617                                    queue.extend(
618                                        BumpVec::from(r#else.effects)
619                                            .into_iter()
620                                            .rev()
621                                            .map(|e| (i, e)),
622                                    );
623                                }
624                            }
625                            ConditionalKind::And { expr }
626                            | ConditionalKind::Or { expr }
627                            | ConditionalKind::NullishCoalescing { expr }
628                            | ConditionalKind::Labeled { body: expr } => {
629                                queue.extend(
630                                    BumpVec::from(expr.effects)
631                                        .into_iter()
632                                        .rev()
633                                        .map(|e| (i, e)),
634                                );
635                            }
636                        };
637                        steps
638                    }
639                    Effect::Call {
640                        mut func,
641                        args,
642                        new,
643                        span,
644                        ..
645                    } => {
646                        let (func, steps) = resolve(
647                            &arena,
648                            &var_graph,
649                            take(&mut *func),
650                            eval_context.imports.get_attributes(span),
651                            &var_cache,
652                        )
653                        .await;
654                        let new_args =
655                            handle_args(&arena, args, &mut queue, &var_graph, &var_cache, i).await;
656                        resolved.push((
657                            format!("{parent} -> {i} call"),
658                            if new {
659                                JsValue::new_from_iter(arena.get_or_default(), func, new_args)
660                            } else {
661                                JsValue::call_from_iter(arena.get_or_default(), func, new_args)
662                            },
663                        ));
664                        steps
665                    }
666                    Effect::FreeVar { var, .. } => {
667                        resolved.push((format!("{parent} -> {i} free var"), JsValue::FreeVar(var)));
668                        0
669                    }
670                    Effect::TypeOf {
671                        mut arg, effects, ..
672                    } => {
673                        queue.extend(BumpVec::from(effects).into_iter().rev().map(|e| (i, e)));
674                        let (arg, steps) = resolve(
675                            &arena,
676                            &var_graph,
677                            take(&mut *arg),
678                            ImportAttributes::empty_ref(),
679                            &var_cache,
680                        )
681                        .await;
682                        resolved.push((
683                            format!("{parent} -> {i} typeof"),
684                            JsValue::type_of(arena.get_or_default(), arg),
685                        ));
686                        steps
687                    }
688                    Effect::MemberCall {
689                        mut obj,
690                        mut prop,
691                        args,
692                        ..
693                    } => {
694                        let (obj, obj_steps) = resolve(
695                            &arena,
696                            &var_graph,
697                            take(&mut *obj),
698                            ImportAttributes::empty_ref(),
699                            &var_cache,
700                        )
701                        .await;
702                        let (prop, prop_steps) = resolve(
703                            &arena,
704                            &var_graph,
705                            take(&mut *prop),
706                            ImportAttributes::empty_ref(),
707                            &var_cache,
708                        )
709                        .await;
710                        let new_args =
711                            handle_args(&arena, args, &mut queue, &var_graph, &var_cache, i).await;
712                        resolved.push((
713                            format!("{parent} -> {i} member call"),
714                            JsValue::member_call_from_iter(
715                                arena.get_or_default(),
716                                obj,
717                                prop,
718                                new_args,
719                            ),
720                        ));
721                        obj_steps + prop_steps
722                    }
723                    Effect::DynamicImport { args, .. } => {
724                        let new_args =
725                            handle_args(&arena, args, &mut queue, &var_graph, &var_cache, i).await;
726                        resolved.push((
727                            format!("{parent} -> {i} dynamic import"),
728                            JsValue::call_from_iter(
729                                arena.get_or_default(),
730                                JsValue::FreeVar("import".into()),
731                                new_args,
732                            ),
733                        ));
734                        0
735                    }
736                    Effect::Unreachable { .. } => {
737                        resolved.push((
738                            format!("{parent} -> {i} unreachable"),
739                            JsValue::unknown_empty(true, rcstr!("unreachable")),
740                        ));
741                        0
742                    }
743                    Effect::Member {
744                        base_effects: effects,
745                        ..
746                    }
747                    | Effect::In { effects, .. } => {
748                        queue.extend(BumpVec::from(effects).into_iter().rev().map(|e| (i, e)));
749                        0
750                    }
751                    Effect::ImportMeta { .. }
752                    | Effect::ImportedBinding { .. }
753                    | Effect::DestructuredMember { .. } => 0,
754                };
755                let time = start.elapsed();
756                if time.as_millis() > 1 {
757                    println!(
758                        "linking effect {} took {} in {} steps",
759                        input.display(),
760                        FormatDuration(time),
761                        steps
762                    );
763                }
764            }
765            let time = start.elapsed();
766            if time.as_millis() > 1 {
767                println!(
768                    "linking effects {} took {}",
769                    input.display(),
770                    FormatDuration(time)
771                );
772            }
773
774            let start = Instant::now();
775            let explainer = explain_all(resolved.iter().map(|(name, value)| (name, value, None)));
776            let time = start.elapsed();
777            if time.as_millis() > 1 {
778                println!(
779                    "explaining effects {} took {}",
780                    input.display(),
781                    FormatDuration(time)
782                );
783            }
784
785            NormalizedOutput::from(explainer)
786                .compare_to_file(&resolved_effects_snapshot_path)
787                .unwrap();
788        }
789
790        Ok(())
791    }
792
793    /// Builds the var graph for `src` (parsed as a sloppy script unless it uses module syntax)
794    /// and returns whether a direct `eval` was detected.
795    fn detect_direct_eval(src: &str) -> bool {
796        let cm: Arc<SourceMap> = Arc::new(SourceMap::new(FilePathMapping::empty()));
797        let globals = Globals::new();
798        GLOBALS.set(&globals, || {
799            let fm = cm.new_source_file(FileName::Anon.into(), src.to_string());
800            let mut m = parse_file_as_program(
801                &fm,
802                Default::default(),
803                EsVersion::latest(),
804                None,
805                &mut vec![],
806            )
807            .unwrap();
808            let unresolved_mark = Mark::new();
809            let top_level_mark = Mark::new();
810            m.visit_mut_with(&mut resolver(unresolved_mark, top_level_mark, false));
811            let eval_context = EvalContext::new(
812                Some(&m),
813                unresolved_mark,
814                top_level_mark,
815                Default::default(),
816                None,
817            );
818            let arena = Bump::new();
819            create_graph(
820                &arena,
821                &m,
822                &eval_context,
823                AnalyzeMode::code_generation(),
824                SpecifiedModuleType::Automatic,
825                false,
826                false,
827            )
828            .has_direct_eval
829        })
830    }
831
832    #[test]
833    fn direct_eval_detection() {
834        for src in [
835            "eval('x')",
836            "(eval)('x')",
837            "((eval))('x')",
838            "function f() { return eval('x') }",
839            "(() => { eval('x') })()",
840            "class C { m() { eval('x') } }",
841            "if (cond) { eval('x') }",
842            "export const v = eval('x')",
843        ] {
844            assert!(detect_direct_eval(src), "expected direct eval: {src}");
845        }
846
847        for src in [
848            "(0, eval)('x')",
849            "globalThis.eval('x')",
850            "window.eval('x')",
851            "eval?.('x')",
852            "const e = eval; e('x')",
853            "new eval('x')",
854            "function f(eval) { return eval('x') }",
855            "var eval = (x) => x; eval('x')",
856            "export const v = 1",
857        ] {
858            assert!(!detect_direct_eval(src), "expected no direct eval: {src}");
859        }
860    }
861
862    async fn resolve<'a>(
863        arena: &'a ThreadLocal<Bump>,
864        var_graph: &VarGraph<'a>,
865        val: JsValue<'a>,
866        attributes: &ImportAttributes,
867        var_cache: &Mutex<FxHashMap<Id, JsValue<'a>>>,
868    ) -> (JsValue<'a>, u32) {
869        // The caller (`fixture`) runs us inside `tt.run_once`, so a real
870        // turbo-tasks task context is already established here.
871        async {
872            let compile_time_info = CompileTimeInfo::builder(
873                Environment::new(ExecutionEnvironment::NodeJsLambda(
874                    NodeJsEnvironment {
875                        compile_target: CompileTarget {
876                            arch: Arch::X64,
877                            platform: Platform::Linux,
878                            endianness: Endianness::Little,
879                            libc: Libc::Glibc,
880                        }
881                        .resolved_cell(),
882                        node_version: NodeJsVersion::default().resolved_cell(),
883                        cwd: ResolvedVc::cell(None),
884                    }
885                    .resolved_cell(),
886                ))
887                .to_resolved()
888                .await?,
889            )
890            .cell()
891            .await?;
892            link(
893                arena,
894                var_graph,
895                val,
896                &(|val| Box::pin(super::test_utils::early_visitor(arena, val))),
897                &(|val| {
898                    Box::pin(super::test_utils::visitor(
899                        arena,
900                        val,
901                        compile_time_info,
902                        attributes,
903                    ))
904                }),
905                &Default::default(),
906                var_cache,
907            )
908            .await
909        }
910        .await
911        .unwrap()
912    }
913}