Skip to content

Commit

Permalink
fix: no source map when starts with a newline
Browse files Browse the repository at this point in the history
  • Loading branch information
SyMind committed Oct 9, 2024
1 parent 86517df commit 35dae15
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 15 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"mappings": "AAAA,SAASA,EAAIC,CAAI,CAAEC,CAAK,EACtBD,EAAKE,SAAS,CAAC,CACXC,QAAS,CAAC,EAAEF,EAAME,OAAO,CAAC,CAAC,EACvBF,EAAMG,IAAI,CACJ,CAAC;AAAE;AAAS;AAC5B;AAAS;AACT;AAAI,GAAG,EAAEH,EAAMG,IAAI,CAAC,CAAC,CACL,QACT,CAAC,AACN,EACF,CACAL",
"mappings": "AAAA,SAASA,EAAIC,CAAI,CAAEC,CAAK,EACtBD,EAAKE,SAAS,CAAC,CACXC,QAAS,CAAC,EAAEF,EAAME,OAAO,CAAC,CAAC,EACvBF,EAAMG,IAAI,CACJ;AAAG;AAAS;AAC5B;AAAS;AACT;AAAI,GAAG,EAAEH,EAAMG,IAAI,CAAC,CAAC,CACL,QACT,CAAC,AACN,EACF,CACAL",
"names": [
"foo",
"span",
Expand Down
35 changes: 21 additions & 14 deletions crates/swc_ecma_codegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ fn replace_close_inline_script(raw: &str) -> Cow<str> {
Cow::Owned(result)
}

static NEW_LINE_TPL_REGEX: Lazy<regex::Regex> = Lazy::new(|| regex::Regex::new(r"\\n|\n").unwrap());

impl<W, S: SourceMapper> Emitter<'_, W, S>
where
W: WriteJs,
Expand Down Expand Up @@ -1986,22 +1988,27 @@ where
let v = get_template_element_from_raw(&raw, self.cfg.ascii_only);
let span = node.span();

// Search for newline chars. We search only for `\n`, since both `\r` and
// `\r\n` are normalized to `\n` during parse. We exclude `\u2028` and
// `\u2029` for performance reasons, they're so uncommon that it's probably
// ok. It's also unclear how other sourcemap utilities handle them...
let mut last = 0;
for (i, _) in v.match_indices('\n') {
if i + 1 < v.len() {
// We mark the start of each line, which happens directly after this newline
// char unless this is the last char.
self.wr.add_srcmap(span.lo + BytePos((i + 1) as u32))?;
let mut last_offset_gen = 0;
let mut last_offset_origin = 0;
for ((offset_gen, _), mat) in v
.match_indices('\n')
.zip(NEW_LINE_TPL_REGEX.find_iter(&raw))
{
// If the string starts with a newline char, then adding a mark is redundant.
// This catches both "no newlines" and "newline after several chars".
if offset_gen != 0 {
self.wr
.add_srcmap(span.lo + BytePos(last_offset_origin as u32))?;
}
self.wr.write_str_lit(DUMMY_SP, &v[last..=i])?;
last = i;

self.wr
.write_str_lit(DUMMY_SP, &v[last_offset_gen..=offset_gen])?;
last_offset_gen = offset_gen + 1;
last_offset_origin = mat.end();
}
self.wr.add_srcmap(span.lo + BytePos(last as u32))?;
self.wr.write_str_lit(DUMMY_SP, &v[last..])?;
self.wr
.add_srcmap(span.lo + BytePos(last_offset_origin as u32))?;
self.wr.write_str_lit(DUMMY_SP, &v[last_offset_gen..])?;
self.wr.add_srcmap(span.hi)?;
} else {
self.wr.write_str_lit(node.span(), &raw)?;
Expand Down

0 comments on commit 35dae15

Please sign in to comment.