Skip to main content

turbopack_ecmascript/references/
member.rs

1use anyhow::Result;
2use bincode::{Decode, Encode};
3use swc_core::{
4    atoms::atom,
5    base::SwcComments,
6    common::{
7        DUMMY_SP, Span,
8        comments::{Comment, CommentKind, Comments},
9    },
10    ecma::ast::{Expr, MemberExpr, MemberProp},
11    quote,
12};
13use turbo_rcstr::RcStr;
14use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat};
15use turbopack_core::chunk::ChunkingContext;
16
17use crate::{
18    ast_path_trie::{AstPathId, AstPathTrie},
19    code_gen::{CodeGen, CodeGeneration},
20    create_visitor,
21};
22
23#[derive(PartialEq, Eq, ValueDebugFormat, NonLocalValue, Hash, Debug, Encode, Decode)]
24pub struct MemberReplacement {
25    key: RcStr,
26    value: RcStr,
27    path: AstPathId,
28}
29
30impl MemberReplacement {
31    pub fn new(key: RcStr, value: RcStr, path: AstPathId) -> Self {
32        MemberReplacement { key, value, path }
33    }
34
35    pub async fn code_generation(
36        &self,
37        trie: &AstPathTrie,
38        _chunking_context: Vc<Box<dyn ChunkingContext>>,
39    ) -> Result<CodeGeneration> {
40        let comments = SwcComments::default();
41
42        let key = self.key.clone();
43        let value = self.value.clone();
44
45        let comments_clone = comments.clone();
46        let visitor = create_visitor!(trie, self.path, visit_mut_expr, |expr: &mut Expr| {
47            let span = Span::dummy_with_cmt();
48
49            comments_clone.add_leading(
50                span.lo,
51                Comment {
52                    kind: CommentKind::Block,
53                    span: DUMMY_SP,
54                    text: atom!("TURBOPACK member replacement"),
55                },
56            );
57            let member = Expr::Member(MemberExpr {
58                span,
59                obj: Box::new(Expr::Ident((&*key).into())),
60                prop: MemberProp::Ident((&*value).into()),
61            });
62            *expr = quote!("$e" as Expr, e: Expr = member);
63        });
64
65        Ok(CodeGeneration::visitors_with_comments(
66            vec![visitor],
67            comments,
68        ))
69    }
70}
71
72impl From<MemberReplacement> for CodeGen {
73    fn from(val: MemberReplacement) -> Self {
74        CodeGen::MemberReplacement(val)
75    }
76}