#[cfg(not(feature = "sourcemap"))]
use std::marker::PhantomData;
use std::{borrow::Cow, cmp, slice};
use oxc_ast::ast::*;
use oxc_data_structures::{code_buffer::CodeBuffer, stack::Stack};
use oxc_ecmascript::with_number_literal;
use oxc_index::IndexVec;
use oxc_semantic::Scoping;
use oxc_span::{GetSpan, SourceType, Span};
use oxc_str::CompactStr;
use oxc_syntax::{
class::ClassId,
identifier::is_identifier_part_ascii,
operator::{BinaryOperator, UnaryOperator, UpdateOperator},
precedence::Precedence,
};
use rustc_hash::FxHashMap;
mod binary_expr_visitor;
mod cjs_module_lexer;
mod comment;
mod context;
mod r#gen;
mod operator;
mod options;
#[cfg(feature = "sourcemap")]
mod sourcemap_builder;
mod str;
use binary_expr_visitor::BinaryExpressionVisitor;
use comment::CommentsMap;
use operator::Operator;
#[cfg(feature = "sourcemap")]
use sourcemap_builder::SourcemapBuilder;
use str::{Quote, cold_branch, is_script_close_tag};
pub use context::Context;
pub use r#gen::{Gen, GenExpr};
pub use options::{CodegenOptions, CommentOptions, LegalComment};
pub use oxc_data_structures::code_buffer::IndentChar;
#[repr(C, align(128))]
struct Align128<T>(pub(crate) T);
static IDENT_BYTES: Align128<[bool; 256]> = {
let mut slots = [true; 256];
let mut i = 0u8;
while i < 128 {
slots[i as usize] = is_identifier_part_ascii(i as char);
i += 1;
}
Align128(slots)
};
#[non_exhaustive]
pub struct CodegenReturn<'a> {
pub code: String,
#[cfg(feature = "sourcemap")]
pub map: Option<oxc_sourcemap::SourceMap<'a>>,
#[cfg(not(feature = "sourcemap"))]
_source_map_lifetime: PhantomData<&'a ()>,
pub legal_comments: Vec<Comment>,
}
pub struct Codegen<'a> {
pub(crate) options: CodegenOptions,
source_text: Option<&'a str>,
scoping: Option<Scoping>,
private_member_mappings: Option<IndexVec<ClassId, FxHashMap<String, CompactStr>>>,
code: CodeBuffer,
prev_op_end: usize,
need_space_before_identifier: usize,
need_space_before_dot: usize,
print_next_indent_as_space: bool,
binary_expr_stack: Stack<BinaryExpressionVisitor<'a>>,
class_stack: Stack<ClassId>,
next_class_id: ClassId,
is_jsx: bool,
needs_semicolon: bool,
prev_op: Option<Operator>,
start_of_stmt: usize,
start_of_arrow_expr: usize,
start_of_default_export: usize,
indent: u32,
quote: Quote,
comments: CommentsMap,
has_property_key_annotations: bool,
annotation_comments: FxHashMap<u32, Comment>,
orphan_comment_keys: Vec<u32>,
#[cfg(feature = "sourcemap")]
sourcemap_builder: Option<SourcemapBuilder<'a>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NonAsciiEscape {
Identifier,
RegExp,
TemplateRaw,
Directive,
}
impl Default for Codegen<'_> {
fn default() -> Self {
Self::new()
}
}
impl<'a> From<Codegen<'a>> for String {
fn from(val: Codegen<'a>) -> Self {
val.into_source_text()
}
}
impl<'a> From<Codegen<'a>> for Cow<'a, str> {
fn from(val: Codegen<'a>) -> Self {
Cow::Owned(val.into_source_text())
}
}
impl<'a> Codegen<'a> {
#[must_use]
pub fn new() -> Self {
let options = CodegenOptions::default();
Self {
options,
source_text: None,
scoping: None,
private_member_mappings: None,
code: CodeBuffer::default(),
needs_semicolon: false,
need_space_before_dot: 0,
print_next_indent_as_space: false,
binary_expr_stack: Stack::with_capacity(12),
class_stack: Stack::with_capacity(4),
next_class_id: ClassId::from_usize(0),
prev_op_end: 0,
need_space_before_identifier: 0,
prev_op: None,
start_of_stmt: 0,
start_of_arrow_expr: 0,
start_of_default_export: 0,
is_jsx: false,
indent: 0,
quote: Quote::Double,
comments: CommentsMap::default(),
has_property_key_annotations: false,
annotation_comments: FxHashMap::default(),
orphan_comment_keys: Vec::new(),
#[cfg(feature = "sourcemap")]
sourcemap_builder: None,
}
}
#[must_use]
pub fn with_options(mut self, options: CodegenOptions) -> Self {
self.quote = if options.single_quote { Quote::Single } else { Quote::Double };
self.code = CodeBuffer::with_indent(options.indent_char, options.indent_width);
self.options = options;
self
}
#[must_use]
pub fn with_source_text(mut self, source_text: &'a str) -> Self {
self.source_text = Some(source_text);
self
}
#[must_use]
pub fn with_source_type(mut self, source_type: SourceType) -> Self {
self.is_jsx = source_type.is_jsx();
self
}
#[must_use]
pub fn with_scoping(mut self, scoping: Option<Scoping>) -> Self {
self.scoping = scoping;
self
}
#[must_use]
pub fn with_private_member_mappings(
mut self,
mappings: Option<IndexVec<ClassId, FxHashMap<String, CompactStr>>>,
) -> Self {
self.private_member_mappings = mappings;
self
}
#[must_use]
pub fn build(mut self, program: &Program<'a>) -> CodegenReturn<'a> {
self.quote = if self.options.single_quote { Quote::Single } else { Quote::Double };
self.source_text = Some(program.source_text);
self.indent = self.options.initial_indent;
self.code.reserve(program.source_text.len());
self.build_comments(&program.comments);
#[cfg(feature = "sourcemap")]
if let Some(path) = &self.options.source_map_path {
self.sourcemap_builder = Some(SourcemapBuilder::new(path, program.source_text));
}
program.print(&mut self, Context::default());
let legal_comments = self.handle_eof_linked_or_external_comments(program);
let code = self.code.into_string();
#[cfg(feature = "sourcemap")]
let map = self.sourcemap_builder.map(SourcemapBuilder::into_sourcemap);
CodegenReturn {
code,
#[cfg(feature = "sourcemap")]
map,
#[cfg(not(feature = "sourcemap"))]
_source_map_lifetime: PhantomData,
legal_comments,
}
}
#[must_use]
pub fn into_source_text(self) -> String {
self.code.into_string()
}
#[inline]
pub fn print_ascii_byte(&mut self, byte: u8) {
self.code.print_ascii_byte(byte);
}
#[inline]
pub fn print_str(&mut self, s: &str) {
self.code.print_str_short(s);
}
#[inline]
pub fn print_name(&mut self, s: &str) {
if !self.options.ascii_only || s.is_ascii() {
self.code.print_str_short(s);
} else {
self.print_non_ascii_escaped(s, NonAsciiEscape::Identifier);
self.need_space_before_identifier = self.code.len();
}
}
#[cold]
pub(crate) fn print_non_ascii_escaped(&mut self, s: &str, mode: NonAsciiEscape) {
let raw = mode != NonAsciiEscape::Identifier;
let mut start = 0;
for (i, ch) in s.char_indices() {
if ch.is_ascii() {
continue;
}
let mut end = i;
let mut escaped = false;
if raw {
let backslashes =
s.as_bytes()[start..i].iter().rev().take_while(|&&b| b == b'\\').count();
escaped = backslashes % 2 == 1;
if escaped {
end = i - 1;
}
}
if start < end {
if mode == NonAsciiEscape::TemplateRaw {
self.print_str_escaping_script_close_tag(&s[start..end]);
} else {
self.code.print_str(&s[start..end]);
}
}
start = i + ch.len_utf8();
let line_continuation = escaped
&& matches!(mode, NonAsciiEscape::TemplateRaw | NonAsciiEscape::Directive)
&& matches!(ch, '\u{2028}' | '\u{2029}');
if line_continuation {
self.print_str("\\\n");
continue;
}
match mode {
NonAsciiEscape::RegExp => self.print_unicode_escape_utf16(ch),
NonAsciiEscape::Identifier
| NonAsciiEscape::TemplateRaw
| NonAsciiEscape::Directive => self.print_unicode_escape(ch),
}
}
if start < s.len() {
if mode == NonAsciiEscape::TemplateRaw {
self.print_str_escaping_script_close_tag(&s[start..]);
} else {
self.code.print_str(&s[start..]);
}
}
}
#[inline]
pub(crate) fn print_unicode_escape(&mut self, ch: char) {
if let Ok(unit) = u16::try_from(ch as u32) {
self.print_u16_escape(unit);
} else {
self.print_code_point_escape(ch as u32);
}
}
#[inline]
fn print_unicode_escape_utf16(&mut self, ch: char) {
let mut units = [0u16; 2];
for unit in ch.encode_utf16(&mut units) {
self.print_u16_escape(*unit);
}
}
#[inline]
fn print_code_point_escape(&mut self, cp: u32) {
const HEX: &[u8; 16] = b"0123456789ABCDEF";
self.print_str("\\u{");
let mut started = false;
for shift in (0..8).rev() {
let nibble = (cp >> (shift * 4)) & 0xF;
if nibble != 0 || started || shift == 0 {
started = true;
self.print_ascii_byte(HEX[nibble as usize]);
}
}
self.print_ascii_byte(b'}');
}
#[inline]
fn print_u16_escape(&mut self, unit: u16) {
const HEX: &[u8; 16] = b"0123456789ABCDEF";
let bytes = [
b'\\',
b'u',
HEX[(unit >> 12) as usize & 0xF],
HEX[(unit >> 8) as usize & 0xF],
HEX[(unit >> 4) as usize & 0xF],
HEX[unit as usize & 0xF],
];
unsafe { self.code.print_bytes_unchecked(&bytes) };
}
#[inline]
pub(crate) fn print_template_quasi_raw(&mut self, raw: &str, tagged: bool) {
let mut start = 0;
if self.options.minify && !tagged {
let bytes = raw.as_bytes();
for (index, _) in raw.match_indices("\\$") {
if bytes.get(index + 2) == Some(&b'{') {
continue;
}
let preceding_backslashes =
bytes[..index].iter().rev().take_while(|&&b| b == b'\\').count();
if preceding_backslashes % 2 != 0 {
continue;
}
self.print_template_quasi_raw_chunk(&raw[start..index], tagged);
start = index + 1;
}
}
self.print_template_quasi_raw_chunk(&raw[start..], tagged);
}
#[inline]
fn print_template_quasi_raw_chunk(&mut self, raw: &str, tagged: bool) {
if !self.options.ascii_only || tagged || raw.is_ascii() {
self.print_str_escaping_script_close_tag(raw);
} else {
self.print_non_ascii_escaped(raw, NonAsciiEscape::TemplateRaw);
}
}
#[inline]
pub(crate) fn print_directive_raw(&mut self, raw: &str) {
if !self.options.ascii_only || raw.is_ascii() {
self.code.print_str(raw);
} else {
self.print_non_ascii_escaped(raw, NonAsciiEscape::Directive);
}
}
#[inline]
pub(crate) fn print_regex_pattern(&mut self, pattern: &str) {
if !self.options.ascii_only || pattern.is_ascii() {
self.code.print_str(pattern);
} else {
self.print_non_ascii_escaped(pattern, NonAsciiEscape::RegExp);
}
}
#[inline]
pub fn print_str_escaping_script_close_tag(&mut self, s: &str) {
let bytes = s.as_bytes();
let mut consumed = 0;
let mut search_bytes = |mut ptr: *const u8, last_ptr| {
loop {
let byte = unsafe { *ptr.as_ref_unchecked() };
if byte == b'<' {
let slice = unsafe { slice::from_raw_parts(ptr, 8) };
if is_script_close_tag(slice) {
unsafe {
let index = ptr.offset_from_unsigned(bytes.as_ptr());
let before = bytes.get_unchecked(consumed..=index);
self.code.print_bytes_unchecked(before);
consumed = index + 2;
}
self.print_str("\\/");
}
}
if ptr == last_ptr {
break;
}
ptr = unsafe { ptr.add(1) };
}
};
let (chunks, last_chunk) = bytes.as_chunks::<16>();
for (chunk_index, chunk) in chunks.iter().enumerate() {
let mut contains_lt = false;
for &byte in chunk {
if byte == b'<' {
contains_lt = true;
}
}
if contains_lt {
cold_branch(|| unsafe {
let index = chunk_index * 16;
let remaining_bytes = bytes.len() - index;
let last_offset = cmp::min(remaining_bytes - 8, 15);
let ptr = bytes.as_ptr().add(index);
let last_ptr = ptr.add(last_offset);
search_bytes(ptr, last_ptr);
});
}
}
if last_chunk.len() >= 8 {
let ptr = last_chunk.as_ptr();
let last_ptr = unsafe { ptr.add(last_chunk.len() - 8) };
search_bytes(ptr, last_ptr);
}
unsafe {
let remaining = bytes.get_unchecked(consumed..);
self.code.print_bytes_unchecked(remaining);
}
}
#[inline]
pub fn print_expression(&mut self, expr: &Expression<'_>) {
expr.print_expr(self, Precedence::Lowest, Context::empty());
}
pub fn print_string(&mut self, s: &str) {
self.print_string_impl(s.into(), false);
}
}
impl<'a> Codegen<'a> {
#[inline]
fn code(&self) -> &CodeBuffer {
&self.code
}
#[inline]
fn code_len(&self) -> usize {
self.code().len()
}
#[inline]
fn print_soft_space(&mut self) {
if !self.options.minify {
self.print_ascii_byte(b' ');
}
}
#[inline]
fn print_hard_space(&mut self) {
self.print_ascii_byte(b' ');
}
#[inline]
fn print_soft_newline(&mut self) {
if !self.options.minify {
self.print_ascii_byte(b'\n');
}
}
#[inline]
fn print_hard_newline(&mut self) {
self.print_ascii_byte(b'\n');
}
#[inline]
fn print_semicolon(&mut self) {
self.print_ascii_byte(b';');
}
#[inline]
fn print_comma(&mut self) {
self.print_ascii_byte(b',');
}
#[inline]
fn print_space_before_identifier(&mut self) {
let Some(byte) = self.last_byte() else { return };
let force_print_space = self.need_space_before_identifier == self.code.len();
let last_byte_is_ident = IDENT_BYTES.0[byte as usize];
if force_print_space || last_byte_is_ident {
self.print_hard_space();
}
}
#[inline]
fn last_byte(&self) -> Option<u8> {
self.code.last_byte()
}
#[inline]
fn indent(&mut self) {
if !self.options.minify {
self.indent += 1;
}
}
#[inline]
fn dedent(&mut self) {
if !self.options.minify {
self.indent -= 1;
}
}
#[inline]
fn enter_class(&mut self) {
let class_id = self.next_class_id;
self.next_class_id = ClassId::from_usize(self.next_class_id.index() + 1);
self.class_stack.push(class_id);
}
#[inline]
fn exit_class(&mut self) {
self.class_stack.pop();
}
#[inline]
fn current_class_ids(&self) -> impl ExactSizeIterator<Item = ClassId> {
self.class_stack.iter().rev().copied()
}
#[inline]
fn wrap<F: FnOnce(&mut Self)>(&mut self, wrap: bool, f: F) {
if wrap {
self.print_ascii_byte(b'(');
}
f(self);
if wrap {
self.print_ascii_byte(b')');
}
}
#[inline]
fn print_indent(&mut self) {
if self.options.minify {
return;
}
if self.consume_pending_indent_space() {
return;
}
self.code.print_indent(self.indent as usize);
}
#[inline]
fn consume_pending_indent_space(&mut self) -> bool {
if self.print_next_indent_as_space {
self.print_soft_space();
self.print_next_indent_as_space = false;
true
} else {
false
}
}
#[inline]
fn clear_pending_indent_space(&mut self) {
self.print_next_indent_as_space = false;
}
#[inline]
fn print_semicolon_after_statement(&mut self) {
if self.options.minify {
self.needs_semicolon = true;
} else {
self.print_str(";\n");
}
}
#[inline]
fn print_semicolon_if_needed(&mut self) {
if self.needs_semicolon {
self.print_semicolon();
self.needs_semicolon = false;
}
}
#[inline]
fn print_ellipsis(&mut self) {
self.print_str("...");
}
#[inline]
fn print_colon(&mut self) {
self.print_ascii_byte(b':');
}
#[inline]
fn print_equal(&mut self) {
self.print_ascii_byte(b'=');
}
fn print_curly_braces<F: FnOnce(&mut Self)>(&mut self, span: Span, single_line: bool, op: F) {
self.add_source_mapping(span);
self.print_ascii_byte(b'{');
if !single_line {
self.print_soft_newline();
self.indent();
}
op(self);
if !single_line {
self.dedent();
self.print_indent();
}
self.add_source_mapping_end(span);
self.print_ascii_byte(b'}');
}
fn print_block_start(&mut self, span: Span) {
self.add_source_mapping(span);
self.print_ascii_byte(b'{');
self.print_soft_newline();
self.indent();
}
fn print_block_end(&mut self, span: Span) {
self.dedent();
self.print_indent();
self.add_source_mapping_end(span);
self.print_ascii_byte(b'}');
}
fn print_body(&mut self, stmt: &Statement<'_>, ctx: Context) {
match stmt {
Statement::BlockStatement(stmt) => {
self.print_soft_space();
self.print_block_statement(stmt, ctx);
self.print_soft_newline();
}
Statement::EmptyStatement(_) => {
self.print_semicolon();
self.print_soft_newline();
}
stmt => {
self.print_next_indent_as_space = true;
stmt.print(self, ctx);
}
}
}
fn print_block_statement(&mut self, stmt: &BlockStatement<'_>, ctx: Context) {
let single_line = stmt.body.is_empty() && !self.has_orphan_comments_before(stmt.span.end);
self.print_curly_braces(stmt.span, single_line, |p| {
p.print_stmts_with_orphan_flush(&stmt.body, stmt.span.end, ctx);
});
self.needs_semicolon = false;
}
fn print_stmts_with_orphan_flush(
&mut self,
stmts: &[Statement<'_>],
scope_end: u32,
ctx: Context,
) {
for stmt in stmts {
self.print_orphan_comments_before(stmt.span().start);
self.print_semicolon_if_needed();
stmt.print(self, ctx);
}
self.print_orphan_comments_before(scope_end);
}
fn print_directives_and_statements(
&mut self,
directives: &[Directive<'_>],
stmts: &[Statement<'_>],
scope_end: u32,
ctx: Context,
) {
for directive in directives {
directive.print(self, ctx);
}
let Some((first, rest)) = stmts.split_first() else {
self.print_orphan_comments_before(scope_end);
return;
};
self.print_orphan_comments_before(first.span().start);
if let Statement::ExpressionStatement(stmt) = first
&& let expr = stmt.expression.without_parentheses()
&& let Expression::StringLiteral(string) = expr
{
self.print_comments_at(stmt.span.start);
if self.indent > 0 || self.print_next_indent_as_space {
self.print_indent();
self.add_source_mapping(stmt.span);
}
if self.options.minify {
self.print_string_literal_as_template(string);
} else {
self.print_ascii_byte(b'(');
self.print_string_literal(string, true);
self.print_ascii_byte(b')');
}
self.print_semicolon_after_statement();
} else {
first.print(self, ctx);
}
self.print_stmts_with_orphan_flush(rest, scope_end, ctx);
}
#[inline]
fn print_list<T: Gen>(&mut self, items: &[T], ctx: Context) {
let Some((first, rest)) = items.split_first() else {
return;
};
first.print(self, ctx);
for item in rest {
self.print_comma();
self.print_soft_space();
item.print(self, ctx);
}
}
#[inline]
fn print_expressions<T: GenExpr>(&mut self, items: &[T], precedence: Precedence, ctx: Context) {
let Some((first, rest)) = items.split_first() else {
return;
};
first.print_expr(self, precedence, ctx);
for item in rest {
self.print_comma();
self.print_soft_space();
item.print_expr(self, precedence, ctx);
}
}
fn print_arguments(&mut self, span: Span, arguments: &[Argument<'_>], ctx: Context) {
self.print_ascii_byte(b'(');
let has_comment_before_right_paren = span.end > 0 && self.has_comment(span.end - 1);
let has_comment = has_comment_before_right_paren
|| arguments.iter().any(|item| self.has_comment(item.span().start));
if has_comment {
self.indent();
self.print_list_with_comments(arguments, ctx);
if !has_comment_before_right_paren
|| (span.end > 0 && !self.print_expr_comments(span.end - 1))
{
self.print_soft_newline();
}
self.dedent();
self.print_indent();
} else {
self.print_list(arguments, ctx);
}
self.add_source_mapping_end(span);
self.print_ascii_byte(b')');
}
fn print_list_with_comments(&mut self, items: &[Argument<'_>], ctx: Context) {
let Some((first, rest)) = items.split_first() else {
return;
};
if self.print_expr_comments(first.span().start) {
self.print_indent();
} else {
self.print_soft_newline();
self.print_indent();
}
first.print(self, ctx);
for item in rest {
self.print_comma();
if self.print_expr_comments(item.span().start) {
self.print_indent();
} else {
self.print_soft_newline();
self.print_indent();
}
item.print(self, ctx);
}
}
fn print_jsx_identifier_reference(&mut self, ident: &IdentifierReference<'_>) {
let name = self.get_identifier_reference_name(ident);
self.add_source_mapping_for_name(ident.span, name);
self.print_str(name);
}
#[inline]
fn get_identifier_reference_name(&self, reference: &IdentifierReference<'a>) -> &'a str {
if let Some(scoping) = &self.scoping
&& let Some(reference_id) = reference.reference_id.get()
&& let Some(name) = scoping.get_reference_name(reference_id)
{
return unsafe { std::mem::transmute_copy(&name) };
}
reference.name.as_str()
}
#[inline]
fn get_binding_identifier_name(&self, ident: &BindingIdentifier<'a>) -> &'a str {
if let Some(scoping) = &self.scoping
&& let Some(symbol_id) = ident.symbol_id.get()
{
let name = scoping.symbol_name(symbol_id);
return unsafe { std::mem::transmute_copy(&name) };
}
ident.name.as_str()
}
fn print_space_before_operator(&mut self, next: Operator) {
if self.prev_op_end != self.code.len() {
return;
}
let Some(prev) = self.prev_op else { return };
let bin_op_add = Operator::Binary(BinaryOperator::Addition);
let bin_op_sub = Operator::Binary(BinaryOperator::Subtraction);
let un_op_pos = Operator::Unary(UnaryOperator::UnaryPlus);
let un_op_pre_inc = Operator::Update(UpdateOperator::Increment);
let un_op_neg = Operator::Unary(UnaryOperator::UnaryNegation);
let un_op_pre_dec = Operator::Update(UpdateOperator::Decrement);
let un_op_not = Operator::Unary(UnaryOperator::LogicalNot);
if ((prev == bin_op_add || prev == un_op_pos)
&& (next == bin_op_add || next == un_op_pos || next == un_op_pre_inc))
|| ((prev == bin_op_sub || prev == un_op_neg)
&& (next == bin_op_sub || next == un_op_neg || next == un_op_pre_dec))
|| (prev == un_op_not
&& next == un_op_pre_dec
&& self.code.peek_nth_byte_back(1) == Some(b'<'))
|| (prev == un_op_not
&& matches!(
next,
Operator::Binary(BinaryOperator::Equality | BinaryOperator::StrictEquality)
))
{
self.print_hard_space();
}
}
fn print_non_negative_float(&mut self, num: f64) {
with_number_literal(num, |literal| {
self.print_str(literal);
if !literal.bytes().any(|b| matches!(b, b'.' | b'e' | b'x')) {
self.need_space_before_dot = self.code_len();
}
});
}
fn print_decorators(&mut self, decorators: &[Decorator<'_>], ctx: Context) {
for decorator in decorators {
decorator.print(self, ctx);
self.print_soft_space();
self.print_space_before_identifier();
}
}
#[cfg(feature = "sourcemap")]
fn add_source_mapping(&mut self, span: Span) {
if let Some(sourcemap_builder) = self.sourcemap_builder.as_mut()
&& !span.is_empty()
{
sourcemap_builder.add_source_mapping(self.code.as_bytes(), span.start, None);
}
}
#[cfg(not(feature = "sourcemap"))]
#[inline]
#[expect(clippy::needless_pass_by_ref_mut, clippy::unused_self)]
fn add_source_mapping(&mut self, _span: Span) {}
#[cfg(feature = "sourcemap")]
fn add_source_mapping_end(&mut self, span: Span) {
if let Some(sourcemap_builder) = self.sourcemap_builder.as_mut()
&& !span.is_empty()
{
let end = span.end - 1;
if let Some(source_text) = self.source_text {
#[expect(clippy::cast_possible_truncation)]
if end >= source_text.len() as u32 {
return;
}
}
sourcemap_builder.add_source_mapping(self.code.as_bytes(), end, None);
}
}
#[cfg(not(feature = "sourcemap"))]
#[inline]
#[expect(clippy::needless_pass_by_ref_mut, clippy::unused_self)]
fn add_source_mapping_end(&mut self, _span: Span) {}
#[cfg(feature = "sourcemap")]
#[inline]
fn add_source_mapping_after_postfix(&mut self, span: Span, precedence: Precedence) {
#[inline(never)]
fn add_mapping(
sourcemap_builder: &mut SourcemapBuilder<'_>,
output: &[u8],
source_text: Option<&str>,
span: Span,
) {
if !span.is_empty()
&& matches!(output.last(), Some(b')' | b']'))
&& source_text.is_none_or(|src| (span.end as usize) < src.len())
{
sourcemap_builder.add_source_mapping(output, span.end, None);
}
}
if precedence == Precedence::Postfix
&& let Some(sourcemap_builder) = self.sourcemap_builder.as_mut()
{
add_mapping(sourcemap_builder, self.code.as_bytes(), self.source_text, span);
}
}
#[cfg(not(feature = "sourcemap"))]
#[inline]
#[expect(clippy::needless_pass_by_ref_mut, clippy::unused_self)]
fn add_source_mapping_after_postfix(&mut self, _span: Span, _precedence: Precedence) {}
#[cfg(feature = "sourcemap")]
fn add_source_mapping_for_name(&mut self, span: Span, name: &str) {
if let Some(sourcemap_builder) = self.sourcemap_builder.as_mut()
&& !span.is_empty()
{
sourcemap_builder.add_source_mapping_for_name(self.code.as_bytes(), span, name);
}
}
#[cfg(not(feature = "sourcemap"))]
#[inline]
#[expect(clippy::needless_pass_by_ref_mut, clippy::unused_self)]
fn add_source_mapping_for_name(&mut self, _span: Span, _name: &str) {}
#[cfg(feature = "sourcemap")]
fn add_source_mapping_for_private_name(&mut self, span: Span, name: &str) {
if let Some(sourcemap_builder) = self.sourcemap_builder.as_mut()
&& !span.is_empty()
{
sourcemap_builder.add_source_mapping_for_private_name(self.code.as_bytes(), span, name);
}
}
#[cfg(not(feature = "sourcemap"))]
#[inline]
#[expect(clippy::needless_pass_by_ref_mut, clippy::unused_self)]
fn add_source_mapping_for_private_name(&mut self, _span: Span, _name: &str) {}
}