swc_ecma_codegen/
lib.rs

1#![recursion_limit = "1024"]
2#![deny(clippy::all)]
3#![deny(unused)]
4#![allow(clippy::match_like_matches_macro)]
5#![allow(clippy::nonminimal_bool)]
6#![allow(non_local_definitions)]
7
8use std::{borrow::Cow, fmt::Write, io, ops::Deref, str};
9
10use compact_str::{format_compact, CompactString};
11use memchr::memmem::Finder;
12use once_cell::sync::Lazy;
13use swc_atoms::Atom;
14use swc_common::{
15    comments::{CommentKind, Comments},
16    sync::Lrc,
17    BytePos, SourceMap, SourceMapper, Span, Spanned, DUMMY_SP,
18};
19use swc_ecma_ast::*;
20use swc_ecma_codegen_macros::node_impl;
21
22pub use self::config::Config;
23use self::{text_writer::WriteJs, util::StartsWithAlphaNum};
24use crate::util::EndsWithAlphaNum;
25
26#[macro_use]
27pub mod macros;
28mod class;
29mod comments;
30mod config;
31mod decl;
32mod expr;
33mod jsx;
34mod lit;
35mod module_decls;
36mod object;
37mod pat;
38mod stmt;
39#[cfg(test)]
40mod tests;
41pub mod text_writer;
42mod typescript;
43pub mod util;
44
45pub type Result = io::Result<()>;
46
47/// Generate a code from a syntax node using default options.
48pub fn to_code_default(
49    cm: Lrc<SourceMap>,
50    comments: Option<&dyn Comments>,
51    node: &impl Node,
52) -> String {
53    let mut buf = std::vec::Vec::new();
54    {
55        let mut emitter = Emitter {
56            cfg: Default::default(),
57            cm: cm.clone(),
58            comments,
59            wr: text_writer::JsWriter::new(cm, "\n", &mut buf, None),
60        };
61        node.emit_with(&mut emitter).unwrap();
62    }
63
64    String::from_utf8(buf).expect("codegen generated non-utf8 output")
65}
66
67/// Generate a code from a syntax node using default options.
68pub fn to_code_with_comments(comments: Option<&dyn Comments>, node: &impl Node) -> String {
69    to_code_default(Default::default(), comments, node)
70}
71
72/// Generate a code from a syntax node using default options.
73pub fn to_code(node: &impl Node) -> String {
74    to_code_with_comments(None, node)
75}
76
77pub trait Node: Spanned {
78    fn emit_with<W, S>(&self, e: &mut Emitter<'_, W, S>) -> Result
79    where
80        W: WriteJs,
81        S: SourceMapper + SourceMapperExt;
82}
83impl<N: Node> Node for Box<N> {
84    #[inline]
85    fn emit_with<W, S>(&self, e: &mut Emitter<'_, W, S>) -> Result
86    where
87        W: WriteJs,
88        S: SourceMapper + SourceMapperExt,
89    {
90        (**self).emit_with(e)
91    }
92}
93impl<N: Node> Node for &N {
94    #[inline]
95    fn emit_with<W, S>(&self, e: &mut Emitter<'_, W, S>) -> Result
96    where
97        W: WriteJs,
98        S: SourceMapper + SourceMapperExt,
99    {
100        (**self).emit_with(e)
101    }
102}
103
104pub struct Emitter<'a, W, S: SourceMapper>
105where
106    W: WriteJs,
107    S: SourceMapperExt,
108{
109    pub cfg: config::Config,
110    pub cm: Lrc<S>,
111    pub comments: Option<&'a dyn Comments>,
112    pub wr: W,
113}
114
115enum CowStr<'a> {
116    Borrowed(&'a str),
117    Owned(CompactString),
118}
119
120impl Deref for CowStr<'_> {
121    type Target = str;
122
123    fn deref(&self) -> &str {
124        match self {
125            CowStr::Borrowed(s) => s,
126            CowStr::Owned(s) => s.as_str(),
127        }
128    }
129}
130
131static NEW_LINE_TPL_REGEX: Lazy<regex::Regex> = Lazy::new(|| regex::Regex::new(r"\\n|\n").unwrap());
132
133impl<W, S: SourceMapper> Emitter<'_, W, S>
134where
135    W: WriteJs,
136    S: SourceMapperExt,
137{
138    pub fn emit_program(&mut self, node: &Program) -> Result {
139        node.emit_with(self)
140    }
141
142    pub fn emit_module(&mut self, node: &Module) -> Result {
143        node.emit_with(self)
144    }
145
146    pub fn emit_script(&mut self, node: &Script) -> Result {
147        node.emit_with(self)
148    }
149
150    fn emit_new(&mut self, node: &NewExpr, should_ignore_empty_args: bool) -> Result {
151        self.wr.commit_pending_semi()?;
152
153        self.emit_leading_comments_of_span(node.span(), false)?;
154
155        srcmap!(self, node, true);
156
157        keyword!(self, "new");
158
159        let starts_with_alpha_num = node.callee.starts_with_alpha_num();
160
161        if starts_with_alpha_num {
162            space!(self);
163        } else {
164            formatting_space!(self);
165        }
166        emit!(self, node.callee);
167
168        if let Some(type_args) = &node.type_args {
169            emit!(self, type_args);
170        }
171
172        if let Some(ref args) = node.args {
173            if !(self.cfg.minify && args.is_empty() && should_ignore_empty_args) {
174                punct!(self, "(");
175                self.emit_expr_or_spreads(node.span(), args, ListFormat::NewExpressionArguments)?;
176                punct!(self, ")");
177            }
178        }
179
180        // srcmap!(self, node, false);
181
182        // if it's false, it means it doesn't come from emit_expr,
183        // we need to compensate that
184        if !should_ignore_empty_args && self.comments.is_some() {
185            self.emit_trailing_comments_of_pos(node.span().hi, true, true)?;
186        }
187
188        Ok(())
189    }
190
191    fn emit_template_for_tagged_template(&mut self, node: &Tpl) -> Result {
192        debug_assert!(node.quasis.len() == node.exprs.len() + 1);
193
194        self.emit_leading_comments_of_span(node.span(), false)?;
195
196        srcmap!(self, node, true);
197
198        punct!(self, "`");
199
200        for i in 0..(node.quasis.len() + node.exprs.len()) {
201            if i % 2 == 0 {
202                self.emit_template_element_for_tagged_template(&node.quasis[i / 2])?;
203            } else {
204                punct!(self, "${");
205                emit!(self, node.exprs[i / 2]);
206                punct!(self, "}");
207            }
208        }
209
210        punct!(self, "`");
211
212        srcmap!(self, node, false);
213
214        Ok(())
215    }
216
217    fn emit_atom(&mut self, span: Span, value: &Atom) -> Result {
218        self.wr.write_str_lit(span, value)?;
219
220        Ok(())
221    }
222
223    /// Prints operator and right node of a binary expression.
224    #[inline(never)]
225    fn emit_bin_expr_trailing(&mut self, node: &BinExpr) -> Result {
226        // let indent_before_op = needs_indention(node, &node.left, node.op);
227        // let indent_after_op = needs_indention(node, node.op, &node.right);
228        let is_kwd_op = match node.op {
229            op!("in") | op!("instanceof") => true,
230            _ => false,
231        };
232
233        let need_pre_space = if self.cfg.minify {
234            if is_kwd_op {
235                node.left.ends_with_alpha_num()
236            } else {
237                // space is mandatory to avoid outputting -->
238                match *node.left {
239                    Expr::Update(UpdateExpr {
240                        prefix: false, op, ..
241                    }) => matches!(
242                        (op, node.op),
243                        (op!("--"), op!(">") | op!(">>") | op!(">>>") | op!(">="))
244                    ),
245                    _ => false,
246                }
247            }
248        } else {
249            is_kwd_op
250                || match *node.left {
251                    Expr::Update(UpdateExpr { prefix: false, .. }) => true,
252                    _ => false,
253                }
254        };
255        if need_pre_space {
256            space!(self);
257        } else {
258            formatting_space!(self);
259        }
260        operator!(self, node.op.as_str());
261
262        let need_post_space = if self.cfg.minify {
263            if is_kwd_op {
264                node.right.starts_with_alpha_num()
265            } else if node.op == op!("/") {
266                let span = node.right.span();
267
268                span.is_pure()
269                    || self
270                        .comments
271                        .is_some_and(|comments| comments.has_leading(node.right.span().lo))
272            } else {
273                require_space_before_rhs(&node.right, &node.op)
274            }
275        } else {
276            is_kwd_op
277                || match *node.right {
278                    Expr::Unary(..) | Expr::Update(UpdateExpr { prefix: true, .. }) => true,
279                    _ => false,
280                }
281        };
282        if need_post_space {
283            space!(self);
284        } else {
285            formatting_space!(self);
286        }
287        emit!(self, node.right);
288
289        Ok(())
290    }
291
292    /// prints `(b){}` from `function a(b){}`
293    fn emit_fn_trailing(&mut self, node: &Function) -> Result {
294        if let Some(type_params) = &node.type_params {
295            emit!(self, type_params);
296        }
297
298        punct!(self, "(");
299        self.emit_list(node.span, Some(&node.params), ListFormat::CommaListElements)?;
300        punct!(self, ")");
301
302        if let Some(ty) = &node.return_type {
303            punct!(self, ":");
304            formatting_space!(self);
305            emit!(self, ty);
306        }
307
308        if let Some(body) = &node.body {
309            formatting_space!(self);
310            self.emit_block_stmt_inner(body, true)?;
311        } else {
312            semi!(self);
313        }
314
315        Ok(())
316
317        // srcmap!(emitter,node, false);
318    }
319
320    fn emit_template_element_for_tagged_template(&mut self, node: &TplElement) -> Result {
321        srcmap!(self, node, true);
322
323        self.wr.write_str_lit(DUMMY_SP, &node.raw)?;
324
325        srcmap!(self, node, false);
326
327        Ok(())
328    }
329
330    fn emit_expr_or_spreads(
331        &mut self,
332        parent_node: Span,
333        nodes: &[ExprOrSpread],
334        format: ListFormat,
335    ) -> Result {
336        self.emit_list(parent_node, Some(nodes), format)
337    }
338
339    fn emit_ident_like(&mut self, span: Span, sym: &Atom, optional: bool) -> Result {
340        // TODO: Use write_symbol when ident is a symbol.
341        self.emit_leading_comments_of_span(span, false)?;
342
343        // Source map
344        self.wr.commit_pending_semi()?;
345
346        srcmap!(self, span, true);
347        // TODO: span
348
349        if self.cfg.ascii_only {
350            if self.wr.can_ignore_invalid_unicodes() {
351                self.wr
352                    .write_symbol(DUMMY_SP, &get_ascii_only_ident(sym, false, self.cfg.target))?;
353            } else {
354                self.wr.write_symbol(
355                    DUMMY_SP,
356                    &get_ascii_only_ident(&handle_invalid_unicodes(sym), false, self.cfg.target),
357                )?;
358            }
359        } else if self.wr.can_ignore_invalid_unicodes() {
360            self.wr.write_symbol(DUMMY_SP, sym)?;
361        } else {
362            self.wr
363                .write_symbol(DUMMY_SP, &handle_invalid_unicodes(sym))?;
364        }
365
366        if optional {
367            punct!(self, "?");
368        }
369
370        // Call emitList directly since it could be an array of
371        // TypeParameterDeclarations _or_ type arguments
372
373        // emitList(node, node.typeArguments, ListFormat::TypeParameters);
374
375        Ok(())
376    }
377
378    fn emit_list<N: Node>(
379        &mut self,
380        parent_node: Span,
381        children: Option<&[N]>,
382        format: ListFormat,
383    ) -> Result {
384        self.emit_list5(
385            parent_node,
386            children,
387            format,
388            0,
389            children.map(|c| c.len()).unwrap_or(0),
390        )
391    }
392
393    /// This method exists to reduce compile time.
394    #[inline(never)]
395    fn emit_first_of_list5(
396        &mut self,
397        parent_node: Span,
398        children: Option<usize>,
399        format: ListFormat,
400        start: usize,
401        count: usize,
402    ) -> Option<Result> {
403        if children.is_none() && format.contains(ListFormat::OptionalIfUndefined) {
404            return Some(Ok(()));
405        }
406
407        let is_empty = children.is_none() || start > children.unwrap() || count == 0;
408        if is_empty && format.contains(ListFormat::OptionalIfEmpty) {
409            return Some(Ok(()));
410        }
411
412        if format.contains(ListFormat::BracketsMask) {
413            if let Err(err) = self.wr.write_punct(None, format.opening_bracket()) {
414                return Some(Err(err));
415            }
416
417            if is_empty {
418                if let Err(err) = self.emit_trailing_comments_of_pos(
419                    {
420                        // TODO: children.lo()
421
422                        parent_node.lo()
423                    },
424                    true,
425                    false,
426                ) {
427                    return Some(Err(err));
428                }
429            }
430        }
431
432        None
433    }
434
435    /// This method exists to reduce compile time.
436    #[inline(never)]
437    fn emit_pre_child_for_list5(
438        &mut self,
439        parent_node: Span,
440        format: ListFormat,
441        previous_sibling: Option<Span>,
442        child: Span,
443        should_decrease_indent_after_emit: &mut bool,
444        should_emit_intervening_comments: &mut bool,
445    ) -> Result {
446        // Write the delimiter if this is not the first node.
447        if let Some(previous_sibling) = previous_sibling {
448            // i.e
449            //      function commentedParameters(
450            //          /* Parameter a */
451            //          a
452            // /* End of parameter a */
453            // -> this comment isn't considered to be trailing comment of parameter "a" due
454            // to newline ,
455            if format.contains(ListFormat::DelimitersMask)
456                && previous_sibling.hi != parent_node.hi()
457                && self.comments.is_some()
458            {
459                self.emit_leading_comments(previous_sibling.hi(), true)?;
460            }
461
462            self.write_delim(format)?;
463
464            // Write either a line terminator or whitespace to separate the elements.
465
466            if self.cm.should_write_separating_line_terminator(
467                Some(previous_sibling),
468                Some(child),
469                format,
470            ) {
471                // If a synthesized node in a single-line list starts on a new
472                // line, we should increase the indent.
473                if (format & (ListFormat::LinesMask | ListFormat::Indented))
474                    == ListFormat::SingleLine
475                    && !self.cfg.minify
476                {
477                    self.wr.increase_indent()?;
478                    *should_decrease_indent_after_emit = true;
479                }
480
481                if !self.cfg.minify {
482                    self.wr.write_line()?;
483                }
484                *should_emit_intervening_comments = false;
485            } else if format.contains(ListFormat::SpaceBetweenSiblings) {
486                formatting_space!(self);
487            }
488        }
489
490        Ok(())
491    }
492
493    /// This method exists to reduce compile time.
494    #[inline(never)]
495    fn emit_list_finisher_of_list5(
496        &mut self,
497        parent_node: Span,
498        format: ListFormat,
499        previous_sibling: Option<Span>,
500        last_child: Option<Span>,
501    ) -> Result {
502        // Write a trailing comma, if requested.
503        let has_trailing_comma = format.contains(ListFormat::ForceTrailingComma)
504            || format.contains(ListFormat::AllowTrailingComma) && {
505                if parent_node.is_dummy() {
506                    false
507                } else {
508                    match self.cm.span_to_snippet(parent_node) {
509                        Ok(snippet) => {
510                            if snippet.len() < 3 {
511                                false
512                            } else {
513                                let last_char = snippet.chars().last().unwrap();
514                                snippet[..snippet.len() - last_char.len_utf8()]
515                                    .trim()
516                                    .ends_with(',')
517                            }
518                        }
519                        _ => false,
520                    }
521                }
522            };
523
524        if has_trailing_comma
525            && format.contains(ListFormat::CommaDelimited)
526            && (!self.cfg.minify || !format.contains(ListFormat::CanSkipTrailingComma))
527        {
528            punct!(self, ",");
529            formatting_space!(self);
530        }
531
532        {
533            // Emit any trailing comment of the last element in the list
534            // i.e
535            //       var array = [...
536            //          2
537            //          /* end of element 2 */
538            //       ];
539
540            let emit_trailing_comments = {
541                // TODO:
542                //
543                // !(getEmitFlags(previousSibling).contains(EmitFlags::NoTrailingComments))
544
545                true
546            };
547
548            if let Some(previous_sibling) = previous_sibling {
549                if format.contains(ListFormat::DelimitersMask)
550                    && previous_sibling.hi() != parent_node.hi()
551                    && emit_trailing_comments
552                    && self.comments.is_some()
553                {
554                    self.emit_leading_comments(previous_sibling.hi(), true)?;
555                }
556            }
557        }
558
559        // Decrease the indent, if requested.
560        if format.contains(ListFormat::Indented) && !self.cfg.minify {
561            self.wr.decrease_indent()?;
562        }
563
564        // Write the closing line terminator or closing whitespace.
565        if self
566            .cm
567            .should_write_closing_line_terminator(parent_node, last_child, format)
568        {
569            if !self.cfg.minify {
570                self.wr.write_line()?;
571            }
572        } else if format.contains(ListFormat::SpaceBetweenBraces) && !self.cfg.minify {
573            self.wr.write_space()?;
574        }
575
576        Ok(())
577    }
578
579    /// This method exists to reduce compile time.
580    #[inline(never)]
581    fn emit_last_of_list5(
582        &mut self,
583        parent_node: Span,
584        is_empty: bool,
585        format: ListFormat,
586        _start: usize,
587        _count: usize,
588    ) -> Result {
589        if format.contains(ListFormat::BracketsMask) {
590            if is_empty {
591                self.emit_leading_comments(
592                    {
593                        //TODO: children.hi()
594
595                        parent_node.hi()
596                    },
597                    true,
598                )?; // Emit leading comments within empty lists
599            }
600            self.wr.write_punct(None, format.closing_bracket())?;
601        }
602
603        Ok(())
604    }
605
606    fn emit_list5<N: Node>(
607        &mut self,
608        parent_node: Span,
609        children: Option<&[N]>,
610        format: ListFormat,
611        start: usize,
612        count: usize,
613    ) -> Result {
614        if let Some(result) =
615            self.emit_first_of_list5(parent_node, children.map(|v| v.len()), format, start, count)
616        {
617            return result;
618        }
619
620        let is_empty = children.is_none() || start > children.unwrap().len() || count == 0;
621
622        if is_empty {
623            // Write a line terminator if the parent node was multi-line
624
625            if format.contains(ListFormat::MultiLine) {
626                if !self.cfg.minify {
627                    self.wr.write_line()?;
628                }
629            } else if format.contains(ListFormat::SpaceBetweenBraces)
630                && !(format.contains(ListFormat::NoSpaceIfEmpty))
631                && !self.cfg.minify
632            {
633                self.wr.write_space()?;
634            }
635        } else {
636            let children = children.unwrap();
637
638            // Write the opening line terminator or leading whitespace.
639            let may_emit_intervening_comments =
640                !format.intersects(ListFormat::NoInterveningComments);
641            let mut should_emit_intervening_comments = may_emit_intervening_comments;
642            if self.cm.should_write_leading_line_terminator(
643                parent_node,
644                children.first().map(|v| v.span()),
645                format,
646            ) {
647                if !self.cfg.minify {
648                    self.wr.write_line()?;
649                }
650                should_emit_intervening_comments = false;
651            } else if format.contains(ListFormat::SpaceBetweenBraces) && !self.cfg.minify {
652                self.wr.write_space()?;
653            }
654
655            // Increase the indent, if requested.
656            if format.contains(ListFormat::Indented) && !self.cfg.minify {
657                self.wr.increase_indent()?;
658            }
659
660            // Emit each child.
661            let mut previous_sibling: Option<Span> = None;
662            let mut should_decrease_indent_after_emit = false;
663            for i in 0..count {
664                let child = &children[start + i];
665
666                self.emit_pre_child_for_list5(
667                    parent_node,
668                    format,
669                    previous_sibling,
670                    child.span(),
671                    &mut should_decrease_indent_after_emit,
672                    &mut should_emit_intervening_comments,
673                )?;
674
675                child.emit_with(self)?;
676
677                // Emit this child.
678                if should_emit_intervening_comments {
679                    if self.comments.is_some() {
680                        let comment_range = child.comment_range();
681                        self.emit_trailing_comments_of_pos(comment_range.hi(), false, true)?;
682                    }
683                } else {
684                    should_emit_intervening_comments = may_emit_intervening_comments;
685                }
686
687                if should_decrease_indent_after_emit {
688                    self.wr.decrease_indent()?;
689                    should_decrease_indent_after_emit = false;
690                }
691
692                previous_sibling = Some(child.span());
693            }
694
695            self.emit_list_finisher_of_list5(
696                parent_node,
697                format,
698                previous_sibling,
699                children.last().map(|v| v.span()),
700            )?;
701        }
702
703        // self.handlers.onAfterEmitNodeArray(children);
704
705        self.emit_last_of_list5(parent_node, is_empty, format, start, count)?;
706        Ok(())
707    }
708}
709
710/// Statements
711impl<W, S: SourceMapper> Emitter<'_, W, S>
712where
713    W: WriteJs,
714    S: SourceMapperExt,
715{
716    fn emit_block_stmt_inner(&mut self, node: &BlockStmt, skip_first_src_map: bool) -> Result {
717        self.emit_leading_comments_of_span(node.span(), false)?;
718
719        if !skip_first_src_map {
720            srcmap!(self, node, true);
721        }
722        punct!(self, "{");
723
724        let emit_new_line = !self.cfg.minify
725            && !(node.stmts.is_empty() && is_empty_comments(&node.span(), &self.comments));
726
727        let mut list_format = ListFormat::MultiLineBlockStatements;
728
729        if !emit_new_line {
730            list_format -= ListFormat::MultiLine | ListFormat::Indented;
731        }
732
733        self.emit_list(node.span(), Some(&node.stmts), list_format)?;
734
735        self.emit_leading_comments_of_span(node.span(), true)?;
736
737        srcmap!(self, node, false, true);
738        punct!(self, "}");
739
740        Ok(())
741    }
742
743    fn has_trailing_comment(&self, span: Span) -> bool {
744        if let Some(cmt) = self.comments {
745            let hi = span.hi;
746
747            if cmt.has_trailing(hi) {
748                return true;
749            }
750        }
751
752        false
753    }
754
755    fn simple_assign_target_has_leading_comment(&self, arg: &SimpleAssignTarget) -> bool {
756        match arg {
757            SimpleAssignTarget::Ident(i) => {
758                span_has_leading_comment(self.comments.as_ref().unwrap(), i.span)
759            }
760            SimpleAssignTarget::Member(m) => {
761                if self.has_leading_comment(&m.obj) {
762                    return true;
763                }
764
765                false
766            }
767
768            SimpleAssignTarget::SuperProp(m) => {
769                if span_has_leading_comment(self.comments.as_ref().unwrap(), m.span) {
770                    return true;
771                }
772
773                false
774            }
775
776            _ => false,
777        }
778    }
779
780    fn has_leading_comment(&self, arg: &Expr) -> bool {
781        let cmt = if let Some(cmt) = self.comments {
782            if span_has_leading_comment(cmt, arg.span()) {
783                return true;
784            }
785
786            cmt
787        } else {
788            return false;
789        };
790
791        match arg {
792            Expr::Call(c) => {
793                let has_leading = match &c.callee {
794                    Callee::Super(callee) => span_has_leading_comment(cmt, callee.span),
795                    Callee::Import(callee) => span_has_leading_comment(cmt, callee.span),
796                    Callee::Expr(callee) => self.has_leading_comment(callee),
797                };
798
799                if has_leading {
800                    return true;
801                }
802            }
803
804            Expr::Member(m) => {
805                if self.has_leading_comment(&m.obj) {
806                    return true;
807                }
808            }
809
810            Expr::SuperProp(m) => {
811                if span_has_leading_comment(cmt, m.span) {
812                    return true;
813                }
814            }
815
816            Expr::Bin(e) => {
817                if self.has_leading_comment(&e.left) {
818                    return true;
819                }
820            }
821
822            Expr::Cond(e) => {
823                if self.has_leading_comment(&e.test) {
824                    return true;
825                }
826            }
827
828            Expr::Seq(e) => {
829                if let Some(e) = e.exprs.first() {
830                    if self.has_leading_comment(e) {
831                        return true;
832                    }
833                }
834            }
835
836            Expr::Assign(e) => {
837                let lo = e.span.lo;
838
839                if cmt.has_leading(lo) {
840                    return true;
841                }
842
843                let has_leading = match &e.left {
844                    AssignTarget::Simple(e) => self.simple_assign_target_has_leading_comment(e),
845
846                    AssignTarget::Pat(p) => match p {
847                        AssignTargetPat::Array(a) => span_has_leading_comment(cmt, a.span),
848                        AssignTargetPat::Object(o) => span_has_leading_comment(cmt, o.span),
849                        AssignTargetPat::Invalid(..) => false,
850                    },
851                };
852
853                if has_leading {
854                    return true;
855                }
856            }
857
858            Expr::OptChain(e) => match &*e.base {
859                OptChainBase::Member(m) => {
860                    if self.has_leading_comment(&m.obj) {
861                        return true;
862                    }
863                }
864                OptChainBase::Call(c) => {
865                    if self.has_leading_comment(&c.callee) {
866                        return true;
867                    }
868                }
869            },
870
871            _ => {}
872        }
873
874        false
875    }
876}
877
878impl<W, S: SourceMapper> Emitter<'_, W, S>
879where
880    W: WriteJs,
881    S: SourceMapperExt,
882{
883    fn write_delim(&mut self, f: ListFormat) -> Result {
884        match f & ListFormat::DelimitersMask {
885            ListFormat::None => {}
886            ListFormat::CommaDelimited => self.wr.write_punct(None, ",")?,
887            ListFormat::BarDelimited => {
888                if !self.cfg.minify {
889                    self.wr.write_space()?;
890                }
891                self.wr.write_punct(None, "|")?;
892            }
893            ListFormat::AmpersandDelimited => {
894                if !self.cfg.minify {
895                    self.wr.write_space()?;
896                }
897                self.wr.write_punct(None, "&")?;
898            }
899            _ => unreachable!(),
900        }
901
902        Ok(())
903    }
904}
905
906/// In some cases, we need to emit a space between the operator and the operand.
907/// One obvious case is when the operator is an identifier, like delete or
908/// typeof. We also need to do this for plus and minus expressions in certain
909/// cases. Specifically, consider the following two cases (parens are just for
910/// clarity of exposition, and not part of the source code):
911///
912///  (+(+1))
913///  (+(++1))
914///
915/// We need to emit a space in both cases. In the first case, the absence of a
916/// space will make the resulting expression a prefix increment operation. And
917/// in the second, it will make the resulting expression a prefix increment
918/// whose operand is a plus expression - (++(+x)) The same is true of minus of
919/// course.
920fn should_emit_whitespace_before_operand(node: &UnaryExpr) -> bool {
921    match *node {
922        UnaryExpr {
923            op: op!("void"), ..
924        }
925        | UnaryExpr {
926            op: op!("typeof"), ..
927        }
928        | UnaryExpr {
929            op: op!("delete"), ..
930        } => return node.arg.starts_with_alpha_num(),
931        _ => {}
932    }
933
934    match &*node.arg {
935        Expr::Update(UpdateExpr {
936            op: op!("++"),
937            prefix: true,
938            ..
939        })
940        | Expr::Unary(UnaryExpr {
941            op: op!(unary, "+"),
942            ..
943        }) if node.op == op!(unary, "+") => true,
944        Expr::Update(UpdateExpr {
945            op: op!("--"),
946            prefix: true,
947            ..
948        })
949        | Expr::Unary(UnaryExpr {
950            op: op!(unary, "-"),
951            ..
952        }) if node.op == op!(unary, "-") => true,
953
954        Expr::Lit(Lit::Num(v)) if v.value.is_sign_negative() && node.op == op!(unary, "-") => true,
955
956        _ => false,
957    }
958}
959
960impl<N> Node for Option<N>
961where
962    N: Node,
963{
964    fn emit_with<W, S>(&self, e: &mut Emitter<'_, W, S>) -> Result
965    where
966        W: WriteJs,
967        S: SourceMapper + SourceMapperExt,
968    {
969        match *self {
970            Some(ref n) => n.emit_with(e),
971            None => Ok(()),
972        }
973    }
974}
975
976fn get_template_element_from_raw(
977    s: &str,
978    ascii_only: bool,
979    reduce_escaped_newline: bool,
980) -> String {
981    fn read_escaped(
982        radix: u32,
983        len: Option<usize>,
984        buf: &mut String,
985        iter: impl Iterator<Item = char>,
986    ) {
987        let mut v = 0;
988        let mut pending = None;
989
990        for (i, c) in iter.enumerate() {
991            if let Some(len) = len {
992                if i == len {
993                    pending = Some(c);
994                    break;
995                }
996            }
997
998            match c.to_digit(radix) {
999                None => {
1000                    pending = Some(c);
1001                    break;
1002                }
1003                Some(d) => {
1004                    v = v * radix + d;
1005                }
1006            }
1007        }
1008
1009        match radix {
1010            16 => {
1011                match v {
1012                    0 => match pending {
1013                        Some('1'..='9') => write!(buf, "\\x00").unwrap(),
1014                        _ => write!(buf, "\\0").unwrap(),
1015                    },
1016                    1..=15 => write!(buf, "\\x0{v:x}").unwrap(),
1017                    // '\x20'..='\x7e'
1018                    32..=126 => {
1019                        let c = char::from_u32(v);
1020
1021                        match c {
1022                            Some(c) => write!(buf, "{c}").unwrap(),
1023                            _ => {
1024                                unreachable!()
1025                            }
1026                        }
1027                    }
1028                    // '\x10'..='\x1f'
1029                    // '\u{7f}'..='\u{ff}'
1030                    _ => {
1031                        write!(buf, "\\x{v:x}").unwrap();
1032                    }
1033                }
1034            }
1035
1036            _ => unreachable!(),
1037        }
1038
1039        if let Some(pending) = pending {
1040            buf.push(pending);
1041        }
1042    }
1043
1044    let mut buf = String::with_capacity(s.len());
1045    let mut iter = s.chars().peekable();
1046
1047    let mut is_dollar_prev = false;
1048
1049    while let Some(c) = iter.next() {
1050        let unescape = match c {
1051            '\\' => match iter.next() {
1052                Some(c) => match c {
1053                    'n' => {
1054                        if reduce_escaped_newline {
1055                            Some('\n')
1056                        } else {
1057                            buf.push('\\');
1058                            buf.push('n');
1059
1060                            None
1061                        }
1062                    }
1063                    't' => Some('\t'),
1064                    'x' => {
1065                        read_escaped(16, Some(2), &mut buf, &mut iter);
1066
1067                        None
1068                    }
1069                    // TODO handle `\u1111` and `\u{1111}` too
1070                    // Source - https://github.com/eslint/eslint/blob/main/lib/rules/no-useless-escape.js
1071                    '\u{2028}' | '\u{2029}' => None,
1072                    // `\t` and `\h` are special cases, because they can be replaced on real
1073                    // characters `\xXX` can be replaced on character
1074                    '\\' | 'r' | 'v' | 'b' | 'f' | 'u' | '\r' | '\n' | '`' | '0'..='7' => {
1075                        buf.push('\\');
1076                        buf.push(c);
1077
1078                        None
1079                    }
1080                    '$' if iter.peek() == Some(&'{') => {
1081                        buf.push('\\');
1082                        buf.push('$');
1083
1084                        None
1085                    }
1086                    '{' if is_dollar_prev => {
1087                        buf.push('\\');
1088                        buf.push('{');
1089
1090                        is_dollar_prev = false;
1091
1092                        None
1093                    }
1094                    _ => Some(c),
1095                },
1096                None => Some('\\'),
1097            },
1098            _ => Some(c),
1099        };
1100
1101        match unescape {
1102            Some(c @ '$') => {
1103                is_dollar_prev = true;
1104
1105                buf.push(c);
1106            }
1107            Some('\x00') => {
1108                let next = iter.peek();
1109
1110                match next {
1111                    Some('1'..='9') => buf.push_str("\\x00"),
1112                    _ => buf.push_str("\\0"),
1113                }
1114            }
1115            // Octal doesn't supported in template literals, except in tagged templates, but
1116            // we don't use this for tagged templates, they are printing as is
1117            Some('\u{0008}') => buf.push_str("\\b"),
1118            Some('\u{000c}') => buf.push_str("\\f"),
1119            Some('\n') => buf.push('\n'),
1120            // `\r` is impossible here, because it was removed on parser stage
1121            Some('\u{000b}') => buf.push_str("\\v"),
1122            Some('\t') => buf.push('\t'),
1123            // Print `"` and `'` without quotes
1124            Some(c @ '\x20'..='\x7e') => {
1125                buf.push(c);
1126            }
1127            Some(c @ '\u{7f}'..='\u{ff}') => {
1128                let _ = write!(buf, "\\x{:x}", c as u8);
1129            }
1130            Some('\u{2028}') => {
1131                buf.push_str("\\u2028");
1132            }
1133            Some('\u{2029}') => {
1134                buf.push_str("\\u2029");
1135            }
1136            Some('\u{FEFF}') => {
1137                buf.push_str("\\uFEFF");
1138            }
1139            // TODO(kdy1): Surrogate pairs
1140            Some(c) => {
1141                if !ascii_only || c.is_ascii() {
1142                    buf.push(c);
1143                } else {
1144                    buf.extend(c.escape_unicode().map(|c| {
1145                        if c == 'u' {
1146                            c
1147                        } else {
1148                            c.to_ascii_uppercase()
1149                        }
1150                    }));
1151                }
1152            }
1153            None => {}
1154        }
1155    }
1156
1157    buf
1158}
1159
1160fn get_ascii_only_ident(sym: &str, may_need_quote: bool, target: EsVersion) -> CowStr {
1161    if sym.is_ascii() {
1162        return CowStr::Borrowed(sym);
1163    }
1164
1165    let mut first = true;
1166    let mut buf = CompactString::with_capacity(sym.len() + 8);
1167    let mut iter = sym.chars().peekable();
1168    let mut need_quote = false;
1169
1170    while let Some(c) = iter.next() {
1171        match c {
1172            '\x00' => {
1173                if may_need_quote {
1174                    need_quote = true;
1175                    let _ = write!(buf, "\\x00");
1176                } else {
1177                    let _ = write!(buf, "\\u0000");
1178                }
1179            }
1180            '\u{0008}' => buf.push_str("\\b"),
1181            '\u{000c}' => buf.push_str("\\f"),
1182            '\n' => buf.push_str("\\n"),
1183            '\r' => buf.push_str("\\r"),
1184            '\u{000b}' => buf.push_str("\\v"),
1185            '\t' => buf.push('\t'),
1186            '\\' => {
1187                let next = iter.peek();
1188
1189                match next {
1190                    // TODO fix me - workaround for surrogate pairs
1191                    Some('u') => {
1192                        let mut inner_iter = iter.clone();
1193
1194                        inner_iter.next();
1195
1196                        let mut is_curly = false;
1197                        let mut next = inner_iter.peek();
1198
1199                        if next == Some(&'{') {
1200                            is_curly = true;
1201
1202                            inner_iter.next();
1203                            next = inner_iter.peek();
1204                        }
1205
1206                        if let Some(c @ 'D' | c @ 'd') = next {
1207                            let mut inner_buf = String::new();
1208
1209                            inner_buf.push('\\');
1210                            inner_buf.push('u');
1211
1212                            if is_curly {
1213                                inner_buf.push('{');
1214                            }
1215
1216                            inner_buf.push(*c);
1217
1218                            inner_iter.next();
1219
1220                            let mut is_valid = true;
1221
1222                            for _ in 0..3 {
1223                                let c = inner_iter.next();
1224
1225                                match c {
1226                                    Some('0'..='9') | Some('a'..='f') | Some('A'..='F') => {
1227                                        inner_buf.push(c.unwrap());
1228                                    }
1229                                    _ => {
1230                                        is_valid = false;
1231
1232                                        break;
1233                                    }
1234                                }
1235                            }
1236
1237                            if is_curly {
1238                                inner_buf.push('}');
1239                            }
1240
1241                            if is_valid {
1242                                buf.push_str(&inner_buf);
1243
1244                                let end = if is_curly { 7 } else { 5 };
1245
1246                                for _ in 0..end {
1247                                    iter.next();
1248                                }
1249                            }
1250                        } else {
1251                            buf.push_str("\\\\");
1252                        }
1253                    }
1254                    _ => {
1255                        buf.push_str("\\\\");
1256                    }
1257                }
1258            }
1259            '\'' => {
1260                buf.push('\'');
1261            }
1262            '"' => {
1263                buf.push('"');
1264            }
1265            '\x01'..='\x0f' if !first => {
1266                if may_need_quote {
1267                    need_quote = true;
1268                    let _ = write!(buf, "\\x{:x}", c as u8);
1269                } else {
1270                    let _ = write!(buf, "\\u00{:x}", c as u8);
1271                }
1272            }
1273            '\x10'..='\x1f' if !first => {
1274                if may_need_quote {
1275                    need_quote = true;
1276                    let _ = write!(buf, "\\x{:x}", c as u8);
1277                } else {
1278                    let _ = write!(buf, "\\u00{:x}", c as u8);
1279                }
1280            }
1281            '\x20'..='\x7e' => {
1282                buf.push(c);
1283            }
1284            '\u{7f}'..='\u{ff}' => {
1285                if may_need_quote {
1286                    need_quote = true;
1287                    let _ = write!(buf, "\\x{:x}", c as u8);
1288                } else {
1289                    let _ = write!(buf, "\\u00{:x}", c as u8);
1290                }
1291            }
1292            '\u{2028}' => {
1293                buf.push_str("\\u2028");
1294            }
1295            '\u{2029}' => {
1296                buf.push_str("\\u2029");
1297            }
1298            '\u{FEFF}' => {
1299                buf.push_str("\\uFEFF");
1300            }
1301            _ => {
1302                if c.is_ascii() {
1303                    buf.push(c);
1304                } else if c > '\u{FFFF}' {
1305                    // if we've got this far the char isn't reserved and if the callee has specified
1306                    // we should output unicode for non-ascii chars then we have
1307                    // to make sure we output unicode that is safe for the target
1308                    // Es5 does not support code point escapes and so surrograte formula must be
1309                    // used
1310                    if target <= EsVersion::Es5 {
1311                        // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
1312                        let h = ((c as u32 - 0x10000) / 0x400) + 0xd800;
1313                        let l = (c as u32 - 0x10000) % 0x400 + 0xdc00;
1314
1315                        let _ = write!(buf, r#""\u{h:04X}\u{l:04X}""#);
1316                    } else {
1317                        let _ = write!(buf, "\\u{{{:04X}}}", c as u32);
1318                    }
1319                } else {
1320                    let _ = write!(buf, "\\u{:04X}", c as u16);
1321                }
1322            }
1323        }
1324        first = false;
1325    }
1326
1327    if need_quote {
1328        CowStr::Owned(format_compact!("\"{}\"", buf))
1329    } else {
1330        CowStr::Owned(buf)
1331    }
1332}
1333
1334fn handle_invalid_unicodes(s: &str) -> Cow<str> {
1335    static NEEDLE: Lazy<Finder> = Lazy::new(|| Finder::new("\\\0"));
1336    if NEEDLE.find(s.as_bytes()).is_none() {
1337        return Cow::Borrowed(s);
1338    }
1339
1340    Cow::Owned(s.replace("\\\0", "\\"))
1341}
1342
1343fn require_space_before_rhs(rhs: &Expr, op: &BinaryOp) -> bool {
1344    match rhs {
1345        Expr::Lit(Lit::Num(v)) if v.value.is_sign_negative() && *op == op!(bin, "-") => true,
1346
1347        Expr::Update(UpdateExpr {
1348            prefix: true,
1349            op: update,
1350            ..
1351        }) => matches!(
1352            (op, update),
1353            (op!(bin, "-"), op!("--")) | (op!(bin, "+"), op!("++"))
1354        ),
1355
1356        // space is mandatory to avoid outputting <!--
1357        Expr::Unary(UnaryExpr {
1358            op: op!("!"), arg, ..
1359        }) if *op == op!("<") || *op == op!("<<") => {
1360            if let Expr::Update(UpdateExpr { op: op!("--"), .. }) = &**arg {
1361                true
1362            } else {
1363                false
1364            }
1365        }
1366
1367        Expr::Unary(UnaryExpr { op: unary, .. }) => matches!(
1368            (op, unary),
1369            (op!(bin, "-"), op!(unary, "-")) | (op!(bin, "+"), op!(unary, "+"))
1370        ),
1371
1372        Expr::Bin(BinExpr { left, .. }) => require_space_before_rhs(left, op),
1373
1374        _ => false,
1375    }
1376}
1377
1378fn is_empty_comments(span: &Span, comments: &Option<&dyn Comments>) -> bool {
1379    span.is_dummy() || comments.map_or(true, |c| !c.has_leading(span.span_hi() - BytePos(1)))
1380}
1381
1382fn span_has_leading_comment(cmt: &dyn Comments, span: Span) -> bool {
1383    let lo = span.lo;
1384
1385    if lo.is_dummy() {
1386        return false;
1387    }
1388
1389    // see #415
1390    if let Some(cmt) = cmt.get_leading(lo) {
1391        if cmt.iter().any(|cmt| {
1392            cmt.kind == CommentKind::Line
1393                || cmt
1394                    .text
1395                    .chars()
1396                    // https://tc39.es/ecma262/#table-line-terminator-code-points
1397                    .any(|c| c == '\n' || c == '\r' || c == '\u{2028}' || c == '\u{2029}')
1398        }) {
1399            return true;
1400        }
1401    }
1402
1403    false
1404}
1405
1406#[node_impl]
1407impl MacroNode for Program {
1408    fn emit(&mut self, emitter: &mut Macro) -> Result {
1409        match self {
1410            Program::Module(m) => emit!(m),
1411            Program::Script(s) => emit!(s),
1412            // TODO: reenable once experimental_metadata breaking change is merged
1413            // _ => unreachable!(),
1414        }
1415
1416        Ok(())
1417    }
1418}
1419
1420#[node_impl]
1421impl MacroNode for Module {
1422    #[tracing::instrument(level = "debug", skip_all)]
1423    fn emit(&mut self, emitter: &mut Macro) -> Result {
1424        emitter.emit_leading_comments_of_span(self.span(), false)?;
1425
1426        if self.body.is_empty() {
1427            srcmap!(emitter, self, true);
1428        }
1429
1430        if let Some(ref shebang) = self.shebang {
1431            punct!(emitter, "#!");
1432            emitter.wr.write_str_lit(DUMMY_SP, shebang)?;
1433            emitter.wr.write_line()?;
1434        }
1435        for stmt in &self.body {
1436            emit!(stmt);
1437        }
1438
1439        emitter.emit_trailing_comments_of_pos(self.span().hi, true, true)?;
1440        if !emitter.cfg.omit_last_semi {
1441            emitter.wr.commit_pending_semi()?;
1442        }
1443
1444        Ok(())
1445    }
1446}
1447
1448#[node_impl]
1449impl MacroNode for Script {
1450    #[tracing::instrument(level = "debug", skip_all)]
1451    fn emit(&mut self, emitter: &mut Macro) -> Result {
1452        emitter.emit_leading_comments_of_span(self.span(), false)?;
1453
1454        if self.body.is_empty() {
1455            srcmap!(emitter, self, true);
1456        }
1457
1458        if let Some(ref shebang) = self.shebang {
1459            punct!(emitter, "#!");
1460            emitter.wr.write_str_lit(DUMMY_SP, shebang)?;
1461            emitter.wr.write_line()?;
1462        }
1463        for stmt in &self.body {
1464            emit!(stmt);
1465        }
1466
1467        emitter.emit_trailing_comments_of_pos(self.span().hi, true, true)?;
1468        if !emitter.cfg.omit_last_semi {
1469            emitter.wr.commit_pending_semi()?;
1470        }
1471
1472        Ok(())
1473    }
1474}
1475
1476#[node_impl]
1477impl MacroNode for ModuleItem {
1478    fn emit(&mut self, emitter: &mut Macro) -> Result {
1479        emitter.emit_leading_comments_of_span(self.span(), false)?;
1480        match self {
1481            ModuleItem::Stmt(stmt) => emit!(stmt),
1482            ModuleItem::ModuleDecl(decl) => emit!(decl),
1483        }
1484        emitter.emit_trailing_comments_of_pos(self.span().hi, true, true)?;
1485
1486        Ok(())
1487    }
1488}
1489
1490#[node_impl]
1491impl MacroNode for Callee {
1492    fn emit(&mut self, emitter: &mut Macro) -> Result {
1493        match self {
1494            Callee::Expr(e) => {
1495                if let Expr::New(new) = &**e {
1496                    emitter.emit_new(new, false)?;
1497                } else {
1498                    emit!(e);
1499                }
1500            }
1501            Callee::Super(n) => emit!(n),
1502            Callee::Import(n) => emit!(n),
1503        }
1504
1505        Ok(())
1506    }
1507}
1508
1509#[node_impl]
1510impl MacroNode for Super {
1511    fn emit(&mut self, emitter: &mut Macro) -> Result {
1512        keyword!(emitter, self.span, "super");
1513
1514        Ok(())
1515    }
1516}
1517
1518#[node_impl]
1519impl MacroNode for Import {
1520    fn emit(&mut self, emitter: &mut Macro) -> Result {
1521        keyword!(emitter, self.span, "import");
1522        match self.phase {
1523            ImportPhase::Source => {
1524                punct!(emitter, ".");
1525                keyword!(emitter, "source")
1526            }
1527            ImportPhase::Defer => {
1528                punct!(emitter, ".");
1529                keyword!(emitter, "defer")
1530            }
1531            _ => {}
1532        }
1533
1534        Ok(())
1535    }
1536}
1537
1538#[node_impl]
1539impl MacroNode for Expr {
1540    fn emit(&mut self, emitter: &mut Macro) -> Result {
1541        match self {
1542            Expr::Array(n) => emit!(n),
1543            Expr::Arrow(n) => emit!(n),
1544            Expr::Assign(n) => emit!(n),
1545            Expr::Await(n) => emit!(n),
1546            Expr::Bin(n) => emit!(n),
1547            Expr::Call(n) => emit!(n),
1548            Expr::Class(n) => emit!(n),
1549            Expr::Cond(n) => emit!(n),
1550            Expr::Fn(n) => emit!(n),
1551            Expr::Ident(n) => emit!(n),
1552            Expr::Lit(n) => emit!(n),
1553            Expr::Member(n) => emit!(n),
1554            Expr::SuperProp(n) => emit!(n),
1555            Expr::MetaProp(n) => emit!(n),
1556            Expr::New(n) => emit!(n),
1557            Expr::Object(n) => emit!(n),
1558            Expr::Paren(n) => emit!(n),
1559            Expr::Seq(n) => emit!(n),
1560            Expr::TaggedTpl(n) => emit!(n),
1561            Expr::This(n) => emit!(n),
1562            Expr::Tpl(n) => emit!(n),
1563            Expr::Unary(n) => emit!(n),
1564            Expr::Update(n) => emit!(n),
1565            Expr::Yield(n) => emit!(n),
1566            Expr::PrivateName(n) => emit!(n),
1567
1568            Expr::JSXMember(n) => emit!(n),
1569            Expr::JSXNamespacedName(n) => emit!(n),
1570            Expr::JSXEmpty(n) => emit!(n),
1571            Expr::JSXElement(n) => emit!(n),
1572            Expr::JSXFragment(n) => emit!(n),
1573
1574            Expr::TsAs(n) => emit!(n),
1575            Expr::TsNonNull(n) => emit!(n),
1576            Expr::TsTypeAssertion(n) => emit!(n),
1577            Expr::TsConstAssertion(n) => emit!(n),
1578            Expr::TsInstantiation(n) => emit!(n),
1579            Expr::OptChain(n) => emit!(n),
1580            Expr::Invalid(n) => emit!(n),
1581            Expr::TsSatisfies(n) => {
1582                emit!(n)
1583            }
1584        }
1585
1586        if emitter.comments.is_some() {
1587            emitter.emit_trailing_comments_of_pos(self.span().hi, true, true)?;
1588        }
1589
1590        Ok(())
1591    }
1592}
1593
1594#[node_impl]
1595impl MacroNode for OptChainExpr {
1596    fn emit(&mut self, emitter: &mut Macro) -> Result {
1597        emitter.emit_leading_comments_of_span(self.span(), false)?;
1598
1599        match &*self.base {
1600            OptChainBase::Member(e) => {
1601                if let Expr::New(new) = &*e.obj {
1602                    emitter.emit_new(new, false)?;
1603                } else {
1604                    emit!(e.obj);
1605                }
1606                if self.optional {
1607                    punct!(emitter, "?.");
1608                } else if !e.prop.is_computed() {
1609                    punct!(emitter, ".");
1610                }
1611
1612                match &e.prop {
1613                    MemberProp::Computed(computed) => emit!(computed),
1614                    MemberProp::Ident(i) => emit!(i),
1615                    MemberProp::PrivateName(p) => emit!(p),
1616                }
1617            }
1618            OptChainBase::Call(e) => {
1619                debug_assert!(!e.callee.is_new());
1620                emit!(e.callee);
1621
1622                if self.optional {
1623                    punct!(emitter, "?.");
1624                }
1625
1626                punct!(emitter, "(");
1627                emitter.emit_expr_or_spreads(
1628                    self.span(),
1629                    &e.args,
1630                    ListFormat::CallExpressionArguments,
1631                )?;
1632                punct!(emitter, ")");
1633            }
1634        }
1635
1636        Ok(())
1637    }
1638}
1639
1640#[node_impl]
1641impl MacroNode for Invalid {
1642    fn emit(&mut self, emitter: &mut Macro) -> Result {
1643        emitter.emit_leading_comments_of_span(self.span, false)?;
1644
1645        emitter.wr.write_str_lit(self.span, "<invalid>")?;
1646
1647        Ok(())
1648    }
1649}
1650
1651#[node_impl]
1652impl MacroNode for CallExpr {
1653    fn emit(&mut self, emitter: &mut Macro) -> Result {
1654        emitter.wr.commit_pending_semi()?;
1655
1656        emitter.emit_leading_comments_of_span(self.span(), false)?;
1657
1658        srcmap!(emitter, self, true);
1659
1660        emit!(self.callee);
1661
1662        if let Some(type_args) = &self.type_args {
1663            emit!(type_args);
1664        }
1665
1666        punct!(emitter, "(");
1667        emitter.emit_expr_or_spreads(
1668            self.span(),
1669            &self.args,
1670            ListFormat::CallExpressionArguments,
1671        )?;
1672        punct!(emitter, ")");
1673
1674        // srcmap!(emitter, self, false);
1675
1676        Ok(())
1677    }
1678}
1679
1680#[node_impl]
1681impl MacroNode for NewExpr {
1682    fn emit(&mut self, emitter: &mut Macro) -> Result {
1683        emitter.emit_new(self, true)?;
1684
1685        Ok(())
1686    }
1687}
1688
1689#[node_impl]
1690impl MacroNode for MemberExpr {
1691    fn emit(&mut self, emitter: &mut Macro) -> Result {
1692        emitter.emit_leading_comments_of_span(self.span(), false)?;
1693
1694        srcmap!(emitter, self, true);
1695
1696        let mut needs_2dots_for_property_access = false;
1697
1698        match &*self.obj {
1699            Expr::New(new) => {
1700                emitter.emit_new(new, false)?;
1701            }
1702            Expr::Lit(Lit::Num(num)) => {
1703                needs_2dots_for_property_access = emitter.emit_num_lit_internal(num, true)?;
1704            }
1705            _ => {
1706                emit!(self.obj);
1707            }
1708        }
1709
1710        match &self.prop {
1711            MemberProp::Computed(computed) => emit!(computed),
1712            MemberProp::Ident(ident) => {
1713                if needs_2dots_for_property_access {
1714                    if self.prop.span().lo() >= BytePos(2) {
1715                        emitter.emit_leading_comments(self.prop.span().lo() - BytePos(2), false)?;
1716                    }
1717                    punct!(emitter, ".");
1718                }
1719                if self.prop.span().lo() >= BytePos(1) {
1720                    emitter.emit_leading_comments(self.prop.span().lo() - BytePos(1), false)?;
1721                }
1722                punct!(emitter, ".");
1723                emit!(ident);
1724            }
1725            MemberProp::PrivateName(private) => {
1726                if needs_2dots_for_property_access {
1727                    if self.prop.span().lo() >= BytePos(2) {
1728                        emitter.emit_leading_comments(self.prop.span().lo() - BytePos(2), false)?;
1729                    }
1730                    punct!(emitter, ".");
1731                }
1732                if self.prop.span().lo() >= BytePos(1) {
1733                    emitter.emit_leading_comments(self.prop.span().lo() - BytePos(1), false)?;
1734                }
1735                punct!(emitter, ".");
1736                emit!(private);
1737            }
1738        }
1739
1740        srcmap!(emitter, self, false);
1741
1742        Ok(())
1743    }
1744}
1745
1746#[node_impl]
1747impl MacroNode for SuperPropExpr {
1748    fn emit(&mut self, emitter: &mut Macro) -> Result {
1749        emitter.emit_leading_comments_of_span(self.span(), false)?;
1750
1751        srcmap!(emitter, self, true);
1752
1753        emit!(self.obj);
1754
1755        match &self.prop {
1756            SuperProp::Computed(computed) => emit!(computed),
1757            SuperProp::Ident(i) => {
1758                if self.prop.span().lo() >= BytePos(1) {
1759                    emitter.emit_leading_comments(self.prop.span().lo() - BytePos(1), false)?;
1760                }
1761                punct!(emitter, ".");
1762                emit!(i);
1763            }
1764        }
1765
1766        Ok(())
1767    }
1768}
1769
1770#[node_impl]
1771impl MacroNode for ArrowExpr {
1772    fn emit(&mut self, emitter: &mut Macro) -> Result {
1773        emitter.emit_leading_comments_of_span(self.span(), false)?;
1774
1775        srcmap!(emitter, self, true);
1776
1777        let space = !emitter.cfg.minify
1778            || match self.params.as_slice() {
1779                [Pat::Ident(_)] => true,
1780                _ => false,
1781            };
1782
1783        if self.is_async {
1784            keyword!(emitter, "async");
1785            if space {
1786                space!(emitter);
1787            } else {
1788                formatting_space!(emitter);
1789            }
1790        }
1791        if self.is_generator {
1792            punct!(emitter, "*")
1793        }
1794
1795        let parens = !emitter.cfg.minify
1796            || match self.params.as_slice() {
1797                [Pat::Ident(i)] => emitter.has_trailing_comment(i.span),
1798                _ => true,
1799            };
1800
1801        emit!(self.type_params);
1802
1803        if parens {
1804            punct!(emitter, "(");
1805        }
1806
1807        emitter.emit_list(self.span, Some(&self.params), ListFormat::CommaListElements)?;
1808        if parens {
1809            punct!(emitter, ")");
1810        }
1811
1812        if let Some(ty) = &self.return_type {
1813            punct!(emitter, ":");
1814            formatting_space!(emitter);
1815            emit!(ty);
1816            formatting_space!(emitter);
1817        }
1818
1819        punct!(emitter, "=>");
1820        emit!(self.body);
1821
1822        Ok(())
1823    }
1824}
1825
1826#[node_impl]
1827impl MacroNode for MetaPropExpr {
1828    fn emit(&mut self, emitter: &mut Macro) -> Result {
1829        if emitter.comments.is_some() {
1830            emitter.emit_leading_comments_of_span(self.span(), false)?;
1831        }
1832
1833        srcmap!(emitter, self, true);
1834
1835        match self.kind {
1836            MetaPropKind::ImportMeta => keyword!(emitter, "import.meta"),
1837
1838            MetaPropKind::NewTarget => keyword!(emitter, "new.target"),
1839        }
1840
1841        Ok(())
1842    }
1843}
1844
1845#[node_impl]
1846impl MacroNode for SeqExpr {
1847    fn emit(&mut self, emitter: &mut Macro) -> Result {
1848        emitter.emit_leading_comments_of_span(self.span(), false)?;
1849
1850        srcmap!(emitter, self, true);
1851
1852        let mut first = true;
1853        //TODO: Indention
1854        for e in &self.exprs {
1855            if first {
1856                first = false
1857            } else {
1858                punct!(emitter, ",");
1859                formatting_space!(emitter);
1860            }
1861
1862            emit!(e);
1863        }
1864
1865        Ok(())
1866    }
1867}
1868
1869#[node_impl]
1870impl MacroNode for AssignExpr {
1871    fn emit(&mut self, emitter: &mut Macro) -> Result {
1872        emitter.emit_leading_comments_of_span(self.span(), false)?;
1873
1874        emit!(self.left);
1875        formatting_space!(emitter);
1876        operator!(emitter, self.op.as_str());
1877        formatting_space!(emitter);
1878        emit!(self.right);
1879
1880        Ok(())
1881    }
1882}
1883
1884#[node_impl]
1885impl MacroNode for BinExpr {
1886    fn emit(&mut self, emitter: &mut Macro) -> Result {
1887        emitter.emit_leading_comments_of_span(self.span(), false)?;
1888
1889        srcmap!(emitter, self, true);
1890
1891        {
1892            let mut left = Some(self);
1893            let mut lefts = Vec::new();
1894            while let Some(l) = left {
1895                lefts.push(l);
1896
1897                match &*l.left {
1898                    Expr::Bin(b) => {
1899                        left = Some(b);
1900                    }
1901                    _ => break,
1902                }
1903            }
1904
1905            let len = lefts.len();
1906
1907            for (i, left) in lefts.into_iter().rev().enumerate() {
1908                if i == 0 {
1909                    emit!(left.left);
1910                }
1911                // Check if it's last
1912                if i + 1 != len {
1913                    emitter.emit_bin_expr_trailing(left)?;
1914                }
1915            }
1916        }
1917
1918        emitter.emit_bin_expr_trailing(self)?;
1919
1920        Ok(())
1921    }
1922}
1923
1924#[node_impl]
1925impl MacroNode for Decorator {
1926    fn emit(&mut self, emitter: &mut Macro) -> Result {
1927        emitter.emit_leading_comments_of_span(self.span(), false)?;
1928
1929        srcmap!(emitter, self, true);
1930
1931        punct!(emitter, "@");
1932        emit!(self.expr);
1933        emitter.wr.write_line()?;
1934
1935        srcmap!(emitter, self, false);
1936
1937        Ok(())
1938    }
1939}
1940
1941#[node_impl]
1942impl MacroNode for CondExpr {
1943    fn emit(&mut self, emitter: &mut Macro) -> Result {
1944        emitter.emit_leading_comments_of_span(self.span(), false)?;
1945
1946        srcmap!(emitter, self, true);
1947
1948        emit!(self.test);
1949        formatting_space!(emitter);
1950        punct!(emitter, "?");
1951        formatting_space!(emitter);
1952        emit!(self.cons);
1953        formatting_space!(emitter);
1954        punct!(emitter, ":");
1955        formatting_space!(emitter);
1956        emit!(self.alt);
1957
1958        Ok(())
1959    }
1960}
1961
1962#[node_impl]
1963impl MacroNode for FnExpr {
1964    fn emit(&mut self, emitter: &mut Macro) -> Result {
1965        emitter.emit_leading_comments_of_span(self.span(), false)?;
1966
1967        emitter.wr.commit_pending_semi()?;
1968
1969        srcmap!(emitter, self, true);
1970
1971        if self.function.is_async {
1972            keyword!(emitter, "async");
1973            space!(emitter);
1974            keyword!(emitter, "function");
1975        } else {
1976            keyword!(emitter, "function");
1977        }
1978
1979        if self.function.is_generator {
1980            punct!(emitter, "*");
1981        }
1982        if let Some(ref i) = self.ident {
1983            space!(emitter);
1984            emit!(i);
1985        }
1986
1987        emitter.emit_fn_trailing(&self.function)?;
1988
1989        Ok(())
1990    }
1991}
1992
1993#[node_impl]
1994impl MacroNode for BlockStmtOrExpr {
1995    fn emit(&mut self, emitter: &mut Macro) -> Result {
1996        match self {
1997            BlockStmtOrExpr::BlockStmt(block) => {
1998                emitter.emit_block_stmt_inner(block, true)?;
1999            }
2000            BlockStmtOrExpr::Expr(expr) => {
2001                emitter.wr.increase_indent()?;
2002                emit!(expr);
2003                emitter.wr.decrease_indent()?;
2004            }
2005        }
2006
2007        Ok(())
2008    }
2009}
2010
2011#[node_impl]
2012impl MacroNode for ThisExpr {
2013    fn emit(&mut self, emitter: &mut Macro) -> Result {
2014        emitter.emit_leading_comments_of_span(self.span(), false)?;
2015
2016        keyword!(emitter, self.span, "this");
2017
2018        Ok(())
2019    }
2020}
2021
2022#[node_impl]
2023impl MacroNode for Tpl {
2024    fn emit(&mut self, emitter: &mut Macro) -> Result {
2025        debug_assert!(self.quasis.len() == self.exprs.len() + 1);
2026
2027        emitter.emit_leading_comments_of_span(self.span(), false)?;
2028
2029        srcmap!(emitter, self, true);
2030
2031        punct!(emitter, "`");
2032
2033        for i in 0..(self.quasis.len() + self.exprs.len()) {
2034            if i % 2 == 0 {
2035                emit!(self.quasis[i / 2]);
2036            } else {
2037                punct!(emitter, "${");
2038                emit!(self.exprs[i / 2]);
2039                punct!(emitter, "}");
2040            }
2041        }
2042
2043        punct!(emitter, "`");
2044
2045        srcmap!(emitter, self, false);
2046
2047        Ok(())
2048    }
2049}
2050
2051#[node_impl]
2052impl MacroNode for TplElement {
2053    fn emit(&mut self, emitter: &mut Macro) -> Result {
2054        let raw = self.raw.replace("\r\n", "\n").replace('\r', "\n");
2055        if emitter.cfg.minify || (emitter.cfg.ascii_only && !self.raw.is_ascii()) {
2056            let v = get_template_element_from_raw(
2057                &raw,
2058                emitter.cfg.ascii_only,
2059                emitter.cfg.reduce_escaped_newline,
2060            );
2061            let span = self.span();
2062
2063            let mut last_offset_gen = 0;
2064            let mut last_offset_origin = 0;
2065            for ((offset_gen, _), mat) in v
2066                .match_indices('\n')
2067                .zip(NEW_LINE_TPL_REGEX.find_iter(&raw))
2068            {
2069                // If the string starts with a newline char, then adding a mark is redundant.
2070                // This catches both "no newlines" and "newline after several chars".
2071                if offset_gen != 0 {
2072                    emitter
2073                        .wr
2074                        .add_srcmap(span.lo + BytePos(last_offset_origin as u32))?;
2075                }
2076
2077                emitter
2078                    .wr
2079                    .write_str_lit(DUMMY_SP, &v[last_offset_gen..=offset_gen])?;
2080                last_offset_gen = offset_gen + 1;
2081                last_offset_origin = mat.end();
2082            }
2083            emitter
2084                .wr
2085                .add_srcmap(span.lo + BytePos(last_offset_origin as u32))?;
2086            emitter.wr.write_str_lit(DUMMY_SP, &v[last_offset_gen..])?;
2087            emitter.wr.add_srcmap(span.hi)?;
2088        } else {
2089            emitter.wr.write_str_lit(self.span(), &raw)?;
2090        }
2091
2092        Ok(())
2093    }
2094}
2095
2096#[node_impl]
2097impl MacroNode for TaggedTpl {
2098    fn emit(&mut self, emitter: &mut Macro) -> Result {
2099        emitter.emit_leading_comments_of_span(self.span(), false)?;
2100
2101        srcmap!(emitter, self, true);
2102
2103        if let Expr::New(new) = &*self.tag {
2104            emitter.emit_new(new, false)?;
2105        } else {
2106            emit!(self.tag);
2107        }
2108
2109        emit!(self.type_params);
2110        emitter.emit_template_for_tagged_template(&self.tpl)?;
2111
2112        srcmap!(emitter, self, false);
2113
2114        Ok(())
2115    }
2116}
2117
2118#[node_impl]
2119impl MacroNode for UnaryExpr {
2120    fn emit(&mut self, emitter: &mut Macro) -> Result {
2121        emitter.emit_leading_comments_of_span(self.span(), false)?;
2122
2123        srcmap!(emitter, self, true);
2124
2125        let need_formatting_space = match self.op {
2126            op!("typeof") | op!("void") | op!("delete") => {
2127                keyword!(emitter, self.op.as_str());
2128
2129                true
2130            }
2131            op!(unary, "+") | op!(unary, "-") | op!("!") | op!("~") => {
2132                punct!(emitter, self.op.as_str());
2133                false
2134            }
2135        };
2136
2137        if should_emit_whitespace_before_operand(self) {
2138            space!(emitter);
2139        } else if need_formatting_space {
2140            formatting_space!(emitter);
2141        }
2142
2143        emit!(self.arg);
2144
2145        Ok(())
2146    }
2147}
2148
2149#[node_impl]
2150impl MacroNode for UpdateExpr {
2151    fn emit(&mut self, emitter: &mut Macro) -> Result {
2152        emitter.emit_leading_comments_of_span(self.span(), false)?;
2153
2154        srcmap!(emitter, self, true);
2155
2156        if self.prefix {
2157            operator!(emitter, self.op.as_str());
2158            //TODO: Check if we should use should_emit_whitespace_before_operand
2159            emit!(self.arg);
2160        } else {
2161            emit!(self.arg);
2162            operator!(emitter, self.op.as_str());
2163        }
2164
2165        Ok(())
2166    }
2167}
2168
2169#[node_impl]
2170impl MacroNode for YieldExpr {
2171    fn emit(&mut self, emitter: &mut Macro) -> Result {
2172        emitter.emit_leading_comments_of_span(self.span(), false)?;
2173
2174        srcmap!(emitter, self, true);
2175
2176        keyword!(emitter, "yield");
2177        if self.delegate {
2178            operator!(emitter, "*");
2179        }
2180
2181        if let Some(ref arg) = self.arg {
2182            let need_paren = self
2183                .arg
2184                .as_deref()
2185                .map(|expr| emitter.has_leading_comment(expr))
2186                .unwrap_or(false);
2187            if need_paren {
2188                punct!(emitter, "(")
2189            } else if !self.delegate && arg.starts_with_alpha_num() {
2190                space!(emitter)
2191            } else {
2192                formatting_space!(emitter)
2193            }
2194
2195            emit!(self.arg);
2196            if need_paren {
2197                punct!(emitter, ")")
2198            }
2199        }
2200
2201        Ok(())
2202    }
2203}
2204
2205#[node_impl]
2206impl MacroNode for ExprOrSpread {
2207    fn emit(&mut self, emitter: &mut Macro) -> Result {
2208        if let Some(span) = self.spread {
2209            emitter.emit_leading_comments_of_span(span, false)?;
2210
2211            punct!(emitter, "...");
2212        }
2213
2214        emit!(self.expr);
2215
2216        Ok(())
2217    }
2218}
2219
2220#[node_impl]
2221impl MacroNode for AwaitExpr {
2222    fn emit(&mut self, emitter: &mut Macro) -> Result {
2223        emitter.emit_leading_comments_of_span(self.span(), false)?;
2224
2225        srcmap!(emitter, self, true);
2226
2227        keyword!(emitter, "await");
2228        space!(emitter);
2229
2230        emit!(self.arg);
2231
2232        Ok(())
2233    }
2234}
2235
2236#[node_impl]
2237impl MacroNode for ArrayLit {
2238    fn emit(&mut self, emitter: &mut Macro) -> Result {
2239        emitter.emit_leading_comments_of_span(self.span(), false)?;
2240
2241        srcmap!(emitter, self, true);
2242
2243        punct!(emitter, "[");
2244        let mut format = ListFormat::ArrayLiteralExpressionElements;
2245        if let Some(None) = self.elems.last() {
2246            format |= ListFormat::ForceTrailingComma;
2247        }
2248
2249        emitter.emit_list(self.span(), Some(&self.elems), format)?;
2250        punct!(emitter, "]");
2251
2252        srcmap!(emitter, self, false);
2253
2254        Ok(())
2255    }
2256}
2257
2258#[node_impl]
2259impl MacroNode for ParenExpr {
2260    fn emit(&mut self, emitter: &mut Macro) -> Result {
2261        emitter.wr.commit_pending_semi()?;
2262
2263        emitter.emit_leading_comments_of_span(self.span(), false)?;
2264
2265        srcmap!(emitter, self, true);
2266
2267        punct!(emitter, "(");
2268        emit!(self.expr);
2269
2270        srcmap!(emitter, self, false, true);
2271        punct!(emitter, ")");
2272
2273        Ok(())
2274    }
2275}
2276
2277#[node_impl]
2278impl MacroNode for PrivateName {
2279    fn emit(&mut self, emitter: &mut Macro) -> Result {
2280        emitter.emit_leading_comments_of_span(self.span(), false)?;
2281
2282        srcmap!(emitter, self, true);
2283
2284        punct!(emitter, "#");
2285        emitter.emit_ident_like(self.span, &self.name, false)?;
2286
2287        srcmap!(emitter, self, false);
2288
2289        Ok(())
2290    }
2291}
2292
2293#[node_impl]
2294impl MacroNode for BindingIdent {
2295    fn emit(&mut self, emitter: &mut Macro) -> Result {
2296        emitter.emit_ident_like(self.span, &self.sym, self.optional)?;
2297
2298        if let Some(ty) = &self.type_ann {
2299            punct!(emitter, ":");
2300            formatting_space!(emitter);
2301            emit!(ty);
2302        }
2303
2304        // Call emitList directly since it could be an array of
2305        // TypeParameterDeclarations _or_ type arguments
2306
2307        // emitList(node, node.typeArguments, ListFormat::TypeParameters);
2308
2309        Ok(())
2310    }
2311}
2312
2313#[node_impl]
2314impl MacroNode for Ident {
2315    fn emit(&mut self, emitter: &mut Macro) -> Result {
2316        emitter.emit_ident_like(self.span, &self.sym, self.optional)?;
2317
2318        Ok(())
2319    }
2320}
2321
2322#[node_impl]
2323impl MacroNode for IdentName {
2324    fn emit(&mut self, emitter: &mut Macro) -> Result {
2325        emitter.emit_ident_like(self.span, &self.sym, false)?;
2326
2327        Ok(())
2328    }
2329}