Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(swc_ecma_codegen): fix LineCol calculation of printed files #6763

Merged
merged 1 commit into from
Jan 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions crates/swc/tests/source_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use swc::{
},
Compiler,
};
use swc_ecma_parser::Syntax;
use testing::{assert_eq, NormalizedOutput, StdErr, Tester};
use walkdir::WalkDir;

Expand Down Expand Up @@ -426,3 +427,87 @@ fn issue_4578() {
)
.unwrap();
}

#[test]
fn issue_6694() {
Tester::new().print_errors(|cm, handler| {
let c = Compiler::new(cm.clone());
let fm = cm.new_source_file(
swc_common::FileName::Real("./app.js".into()),
r#"/**
* foo
* @param data foo
* @returns foo
*/
export const fixupRiskConfigData = (data: any): types.RiskConfigType => {
if (x) {
return 123;
} else {
return 456;
}
};"#
.replace('\n', "\r\n"),
);
let result = c.process_js_file(
fm,
&handler,
&Options {
swcrc: false,
source_maps: Some(SourceMapsConfig::Bool(true)),
config: Config {
jsc: JscConfig {
target: Some(swc_ecma_ast::EsVersion::Es5),
syntax: Some(Syntax::Typescript(Default::default())),
..Default::default()
},
is_module: IsModule::Bool(true),
inline_sources_content: true.into(),
emit_source_map_columns: true.into(),
..Default::default()
},
..Default::default()
},
);

fn line_col(needle: &str, haystack: &str) -> Option<(u32, u32)> {
let lines = haystack.lines().enumerate();
for (i, line) in lines {
if let Some(c) = line.find(needle) {
return Some((i as _, c as _));
}
}

None
}

match result {
Ok(result) => {
assert!(result.map.is_some());
let map = result.map.unwrap();

let source_map = sourcemap::SourceMap::from_slice(map.as_bytes())
.expect("failed to deserialize sourcemap");

// "export"
let export_line_col =
line_col("export", &result.code).expect("failed to find `export`");
let token = source_map
.lookup_token(export_line_col.0, export_line_col.1)
.expect("failed to find token");
assert_eq!(token.get_src(), (5, 0));

// "if"
let if_line_col = line_col("if", &result.code).expect("failed to find `export`");
let token = source_map
.lookup_token(if_line_col.0, export_line_col.1)
.expect("failed to find token");
assert_eq!(token.get_src(), (6, 2));
}
Err(err) => {
panic!("Error: {:#?}", err);
}
}

Ok(())
});
}
3 changes: 3 additions & 0 deletions crates/swc_common/src/syntax_pos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1220,7 +1220,10 @@ pub struct LineInfo {
/// Used to create a `.map` file.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct LineCol {
/// Index of line, starting from 0.
pub line: u32,

/// UTF-16 column in line, starting from 0.
pub col: u32,
}

Expand Down
22 changes: 20 additions & 2 deletions crates/swc_common/src/syntax_pos/analyze_source_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,11 +282,29 @@ mod tests {
non_narrow_chars: vec![(2 + 1000, 4), (24 + 1000, 0)],
);

test!(
case: unix_lf,
text: "/**\n * foo\n */\n012345678\nabcdef012345678\na",
source_file_start_pos: 0,
lines: vec![0, 4, 11, 15, 25, 41],
multi_byte_chars: vec![],
non_narrow_chars: vec![],
);

test!(
case: windows_cr,
text: "/**\r * foo\r */\r012345678\rabcdef012345678\ra",
source_file_start_pos: 0,
lines: vec![0, 4, 11, 15, 25, 41],
multi_byte_chars: vec![],
non_narrow_chars: vec![],
);

test!(
case: windows_crlf,
text: "012345678\r\nabcdef012345678\r\na",
text: "/**\r\n * foo\r\n */\r\n012345678\r\nabcdef012345678\r\na",
source_file_start_pos: 0,
lines: vec![0, 11, 28],
lines: vec![0, 5, 13, 18, 29, 46],
multi_byte_chars: vec![],
non_narrow_chars: vec![],
);
Expand Down
99 changes: 49 additions & 50 deletions crates/swc_ecma_codegen/src/text_writer/basic_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ impl<'a, W: Write> JsWriter<'a, W> {
for _ in 0..self.indent {
self.raw_write(INDENT)?;
}
if self.srcmap.is_some() {
self.line_pos += INDENT.len() * self.indent;
}

Ok(())
}
Expand All @@ -59,11 +62,7 @@ impl<'a, W: Write> JsWriter<'a, W> {
fn raw_write(&mut self, data: &str) -> Result {
// #[cfg(debug_assertions)]
// tracing::trace!("Write: `{}`", data);

self.wr.write_all(data.as_bytes())?;
if self.srcmap.is_some() {
self.line_pos += data.chars().count();
}

Ok(())
}
Expand All @@ -86,6 +85,7 @@ impl<'a, W: Write> JsWriter<'a, W> {
}

self.raw_write(data)?;
self.update_pos(data);

if let Some(span) = span {
self.srcmap(span.hi());
Expand All @@ -95,6 +95,21 @@ impl<'a, W: Write> JsWriter<'a, W> {
Ok(())
}

#[inline]
fn update_pos(&mut self, s: &str) {
if self.srcmap.is_some() {
let line_start_of_s = compute_line_starts(s);
self.line_count += line_start_of_s.line_count;

let chars = s[line_start_of_s.byte_pos..].encode_utf16().count();
if line_start_of_s.line_count > 0 {
self.line_pos = chars;
} else {
self.line_pos += chars;
}
}
}

#[inline]
fn srcmap(&mut self, byte_pos: BytePos) {
if byte_pos.is_dummy() && byte_pos != BytePos(u32::MAX) {
Expand Down Expand Up @@ -183,8 +198,10 @@ impl<'a, W: Write> WriteJs for JsWriter<'a, W> {
let pending = self.pending_srcmap.take();
if !self.line_start {
self.raw_write(self.new_line)?;
self.line_count += 1;
self.line_pos = 0;
if self.srcmap.is_some() {
self.line_count += 1;
self.line_pos = 0;
}
self.line_start = true;

if let Some(pending) = pending {
Expand All @@ -200,18 +217,7 @@ impl<'a, W: Write> WriteJs for JsWriter<'a, W> {
fn write_lit(&mut self, span: Span, s: &str) -> Result {
if !s.is_empty() {
self.srcmap(span.lo());

self.write(None, s)?;

if self.srcmap.is_some() {
let line_start_of_s = compute_line_starts(s);
if line_start_of_s.len() > 1 {
self.line_count = self.line_count + line_start_of_s.len() - 1;
let last_line_byte_index = line_start_of_s.last().cloned().unwrap_or(0);
self.line_pos = s[last_line_byte_index..].chars().count();
}
}

self.srcmap(span.hi());
}

Expand All @@ -222,14 +228,6 @@ impl<'a, W: Write> WriteJs for JsWriter<'a, W> {
#[cfg_attr(debug_assertions, tracing::instrument(skip_all))]
fn write_comment(&mut self, s: &str) -> Result {
self.write(None, s)?;
if self.srcmap.is_some() {
let line_start_of_s = compute_line_starts(s);
if line_start_of_s.len() > 1 {
self.line_count = self.line_count + line_start_of_s.len() - 1;
let last_line_byte_index = line_start_of_s.last().cloned().unwrap_or(0);
self.line_pos = s[last_line_byte_index..].chars().count();
}
}
Ok(())
}

Expand All @@ -239,16 +237,6 @@ impl<'a, W: Write> WriteJs for JsWriter<'a, W> {
if !s.is_empty() {
self.srcmap(span.lo());
self.write(None, s)?;

if self.srcmap.is_some() {
let line_start_of_s = compute_line_starts(s);
if line_start_of_s.len() > 1 {
self.line_count = self.line_count + line_start_of_s.len() - 1;
let last_line_byte_index = line_start_of_s.last().cloned().unwrap_or(0);
self.line_pos = s[last_line_byte_index..].chars().count();
}
}

self.srcmap(span.hi());
}

Expand Down Expand Up @@ -285,10 +273,12 @@ impl<'a, W: Write> WriteJs for JsWriter<'a, W> {
#[inline]
#[cfg_attr(debug_assertions, tracing::instrument(skip_all))]
fn add_srcmap(&mut self, pos: BytePos) -> Result {
if self.line_start {
self.pending_srcmap = Some(pos);
} else {
self.srcmap(pos);
if self.srcmap.is_some() {
if self.line_start {
self.pending_srcmap = Some(pos);
} else {
self.srcmap(pos);
}
}
Ok(())
}
Expand All @@ -300,31 +290,40 @@ impl<'a, W: Write> WriteJs for JsWriter<'a, W> {
}
}

fn compute_line_starts(s: &str) -> Vec<usize> {
let mut res = vec![];

#[derive(Debug)]
struct LineStart {
line_count: usize,
byte_pos: usize,
}
fn compute_line_starts(s: &str) -> LineStart {
let mut count = 0;
let mut line_start = 0;

let mut chars = s.char_indices().peekable();
let mut chars = s.as_bytes().iter().enumerate().peekable();

while let Some((pos, c)) = chars.next() {
match c {
'\r' => {
if let Some(&(_, '\n')) = chars.peek() {
b'\r' => {
count += 1;
if let Some(&(_, b'\n')) = chars.peek() {
let _ = chars.next();
line_start = pos + 2
} else {
line_start = pos + 1
}
}

'\n' => {
res.push(line_start);
b'\n' => {
count += 1;
line_start = pos + 1;
}

_ => {}
}
}

// Last line.
res.push(line_start);
res
LineStart {
line_count: count,
byte_pos: line_start,
}
}