rspack_location 0.102.6

rspack location
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use std::fmt::{self, Debug};

pub use itoa::Buffer;
use rspack_cacheable::cacheable;

/// Represents a position within a source file (line and column).
/// Semantics match V8 Error stack positions:
/// - Both line and column are 1-based.
/// - Column counts UTF-16 code units (not Unicode scalar values or UTF-8 bytes).
#[cacheable]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct SourcePosition {
  pub line: u32,
  pub column: u32,
}

impl From<(u32, u32)> for SourcePosition {
  fn from(range: (u32, u32)) -> Self {
    Self {
      line: range.0,
      column: range.1,
    }
  }
}

/// Represents the real location of a dependency in a source file, including both start and optional end positions.
/// These positions are described in terms of lines and columns in the source code.
#[cacheable]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct RealDependencyLocation {
  pub start: SourcePosition,
  pub end: Option<SourcePosition>,
}

impl RealDependencyLocation {
  pub fn new(start: SourcePosition, end: Option<SourcePosition>) -> Self {
    Self { start, end }
  }

  /// Convert byte line, column, length to js style location
  /// - line is 1-based in bytes
  /// - column is 0-based in bytes
  /// - length in bytes
  pub fn from_byte_location(
    source: &str,
    line: u32,
    column: u32,
    length: Option<u32>,
  ) -> Option<Self> {
    if line == 0 {
      return None;
    }

    let bytes = source.as_bytes();
    let target_line_idx = (line - 1) as usize;

    // 1. Quickly locate the byte index of the line start.
    // If it's the first line, the offset is 0; otherwise, search for the (line-1)th newline.
    let line_start_offset = if target_line_idx == 0 {
      0
    } else {
      let mut iter = memchr::memchr_iter(b'\n', bytes);
      match iter.nth(target_line_idx - 1) {
        Some(idx) => idx + 1,
        None => return None, // Line number exceeds file lines
      }
    };

    // 2. Validate start position.
    let start_byte = line_start_offset + column as usize;
    if start_byte > bytes.len() {
      return None;
    }

    // Ensure start_byte doesn't cross into the next line (find the next newline of the current line).
    let current_line_end = memchr::memchr(b'\n', &bytes[line_start_offset..])
      .map_or(bytes.len(), |rel| line_start_offset + rel);
    if start_byte > current_line_end {
      return None;
    }

    // 3. Calculate the UTF-16 length of the start column.
    // This avoids the overhead of constructing the surrogate pair iterator and only performs numerical accumulation.
    let start_line_slice = source.get(line_start_offset..start_byte)?;
    let start_utf16_col = start_line_slice.encode_utf16().count() + 1; // 1-based

    let start = SourcePosition {
      line,
      column: start_utf16_col as u32,
    };

    // 4. Calculate end position (if length is present).
    let end = if let Some(len) = length {
      let end_byte = start_byte + len as usize;

      if end_byte > bytes.len() {
        // If it exceeds the file range, keep start and discard end (matching original logic).
        return Some(Self { start, end: None });
      }

      let Some(span_slice) = source.get(start_byte..end_byte) else {
        return Some(Self { start, end: None });
      };
      let newlines_in_span = memchr::memchr_iter(b'\n', span_slice.as_bytes()).count();

      let end_line = line.checked_add(newlines_in_span as u32)?;

      let end_column = if newlines_in_span == 0 {
        start_utf16_col + span_slice.encode_utf16().count()
      } else {
        #[allow(clippy::unwrap_used)]
        let last_newline_pos = span_slice.rfind('\n').unwrap();
        let text_after_last_newline = &span_slice[last_newline_pos + 1..];
        text_after_last_newline.encode_utf16().count() + 1 // 1-based
      };

      Some(SourcePosition {
        line: end_line,
        column: end_column as u32,
      })
    } else {
      None
    };

    Some(Self { start, end })
  }
}

impl fmt::Display for RealDependencyLocation {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    if let Some(end) = self.end {
      let mut start_line_buffer = itoa::Buffer::new();
      let start_line = start_line_buffer.format(self.start.line);
      let mut start_col_buffer = itoa::Buffer::new();
      let start_col = start_col_buffer.format(self.start.column);
      if self.start.line == end.line && self.start.column == end.column {
        write!(f, "{start_line}:{start_col}")
      } else if self.start.line == end.line {
        let mut end_col_buffer = itoa::Buffer::new();
        let end_col = end_col_buffer.format(end.column);
        write!(f, "{start_line}:{start_col}-{end_col}")
      } else {
        let mut end_line_buffer = itoa::Buffer::new();
        let end_line = end_line_buffer.format(end.line);
        let mut end_col_buffer = itoa::Buffer::new();
        let end_col = end_col_buffer.format(end.column);
        write!(f, "{start_line}:{start_col}-{end_line}:{end_col}")
      }
    } else {
      let mut start_line_buffer = itoa::Buffer::new();
      let start_line = start_line_buffer.format(self.start.line);
      let mut start_col_buffer = itoa::Buffer::new();
      let start_col = start_col_buffer.format(self.start.column);
      write!(f, "{start_line}:{start_col}")
    }
  }
}

/// Represents a synthetic dependency location, such as a generated dependency.
#[cacheable]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct SyntheticDependencyLocation {
  pub name: String,
}

impl SyntheticDependencyLocation {
  pub fn new(name: &str) -> Self {
    SyntheticDependencyLocation {
      name: name.to_string(),
    }
  }
}

impl fmt::Display for SyntheticDependencyLocation {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "{}", self.name)
  }
}

/// Real source locations sort before synthetic locations. Real locations are
/// ordered by their start position and then their optional end position.
#[cacheable]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum DependencyLocation {
  Real(RealDependencyLocation),
  Synthetic(SyntheticDependencyLocation),
}

impl DependencyLocation {
  pub fn from_byte_location(
    source: &str,
    line: u32,
    column: u32,
    length: Option<u32>,
  ) -> Option<Self> {
    RealDependencyLocation::from_byte_location(source, line, column, length)
      .map(DependencyLocation::Real)
  }
}

impl fmt::Display for DependencyLocation {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    let loc = match self {
      DependencyLocation::Real(real) => real.to_string(),
      DependencyLocation::Synthetic(synthetic) => synthetic.to_string(),
    };
    write!(f, "{loc}")
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn test_from_byte_location_ascii() {
    let source = "hello world\nfoo bar baz";

    // Test basic ASCII string, first line
    let loc = RealDependencyLocation::from_byte_location(source, 1, 6, Some(5));
    assert!(loc.is_some());
    let loc = loc.unwrap();
    assert_eq!(loc.start.line, 1);
    assert_eq!(loc.start.column, 7); // "world" starts at byte 6, UTF-16 column 7 (1-based)
    assert_eq!(loc.end.as_ref().unwrap().line, 1);
    assert_eq!(loc.end.as_ref().unwrap().column, 12); // 7 + 5 = 12
  }

  #[test]
  fn test_from_byte_location_second_line() {
    let source = "hello world\nfoo bar baz";

    // Test second line
    let loc = RealDependencyLocation::from_byte_location(source, 2, 4, Some(3));
    assert!(loc.is_some());
    let loc = loc.unwrap();
    assert_eq!(loc.start.line, 2);
    assert_eq!(loc.start.column, 5); // "bar" starts at byte 4, UTF-16 column 5 (1-based)
    assert_eq!(loc.end.as_ref().unwrap().line, 2);
    assert_eq!(loc.end.as_ref().unwrap().column, 8); // 5 + 3 = 8
  }

  #[test]
  fn test_from_byte_location_utf8_multibyte() {
    // Test with multi-byte UTF-8 characters
    // "你好" = 2 chars, 6 bytes, 2 UTF-16 code units
    // "世界" = 2 chars, 6 bytes, 2 UTF-16 code units
    let source = "你好世界abc";

    // Start at byte 0, length 6 (first two characters "你好")
    let loc = RealDependencyLocation::from_byte_location(source, 1, 0, Some(6));
    assert!(loc.is_some());
    let loc = loc.unwrap();
    assert_eq!(loc.start.line, 1);
    assert_eq!(loc.start.column, 1); // 1-based
    assert_eq!(loc.end.as_ref().unwrap().line, 1);
    assert_eq!(loc.end.as_ref().unwrap().column, 3); // 1 + 2 UTF-16 units = 3
  }

  #[test]
  fn test_from_byte_location_utf8_emoji() {
    // Test with emoji (4-byte UTF-8, 2 UTF-16 code units)
    // "😀" = 1 grapheme, 4 bytes, 2 UTF-16 code units
    let source = "hello😀world";

    // Start at "😀", byte offset 5, length 4
    let loc = RealDependencyLocation::from_byte_location(source, 1, 5, Some(4));
    assert!(loc.is_some());
    let loc = loc.unwrap();
    assert_eq!(loc.start.line, 1);
    assert_eq!(loc.start.column, 6); // "hello" = 5 UTF-16 units, so emoji starts at 6 (1-based)
    assert_eq!(loc.end.as_ref().unwrap().line, 1);
    assert_eq!(loc.end.as_ref().unwrap().column, 8); // 6 + 2 UTF-16 units = 8
  }

  #[test]
  fn test_from_byte_location_no_length() {
    let source = "hello world";

    // Test without length (end is None)
    let loc = RealDependencyLocation::from_byte_location(source, 1, 0, None);
    assert!(loc.is_some());
    let loc = loc.unwrap();
    assert_eq!(loc.start.line, 1);
    assert_eq!(loc.start.column, 1);
    assert!(loc.end.is_none());
  }

  #[test]
  fn test_from_byte_location_invalid_line() {
    let source = "hello world";

    // Test with line 0 (invalid)
    let loc = RealDependencyLocation::from_byte_location(source, 0, 0, None);
    assert!(loc.is_none());
  }

  #[test]
  fn test_from_byte_location_line_out_of_bounds() {
    let source = "hello world\nfoo bar";

    // Test with line number that doesn't exist
    let loc = RealDependencyLocation::from_byte_location(source, 10, 0, None);
    assert!(loc.is_none());
  }

  #[test]
  fn test_from_byte_location_column_out_of_bounds() {
    let source = "hello";

    // Test with column beyond line length
    let loc = RealDependencyLocation::from_byte_location(source, 1, 100, None);
    assert!(loc.is_none());
  }

  #[test]
  fn test_from_byte_location_empty_line() {
    let source = "hello\n\nworld";

    // Test empty line (line 2)
    let loc = RealDependencyLocation::from_byte_location(source, 2, 0, None);
    assert!(loc.is_some());
    let loc = loc.unwrap();
    assert_eq!(loc.start.line, 2);
    assert_eq!(loc.start.column, 1);
  }

  #[test]
  fn test_from_byte_location_length_exceeds_line() {
    let source = "hello world";

    // Test with length that exceeds the line
    let loc = RealDependencyLocation::from_byte_location(source, 1, 6, Some(100));
    assert!(loc.is_some());
    let loc = loc.unwrap();
    assert_eq!(loc.start.line, 1);
    assert_eq!(loc.start.column, 7);
    // Should clamp to end of line: "world" = 5 chars
    assert!(loc.end.is_none()); // 7 + 5 = 12
  }

  #[test]
  fn test_from_byte_location_mixed_content() {
    // Mix of ASCII, multi-byte UTF-8, and emoji
    let source = "abc你好😀xyz\nline2\nline3";

    // Start at "😀" (byte offset: 3 + 6 = 9), length 4
    let loc = RealDependencyLocation::from_byte_location(source, 1, 9, Some(4));
    assert!(loc.is_some());
    let loc = loc.unwrap();
    assert_eq!(loc.start.line, 1);
    // "abc" = 3, "你好" = 2, so start at UTF-16 position 6 (1-based)
    assert_eq!(loc.start.column, 6);
    assert_eq!(loc.end.as_ref().unwrap().line, 1);
    assert_eq!(loc.end.as_ref().unwrap().column, 8);
  }

  #[test]
  fn test_from_byte_location_multiline() {
    // Test length spanning multiple lines
    let source = "hello world\nfoo bar baz\nend";

    // Start at "world" (byte 6 on line 1), length 18 (to "end" on line 3)
    let loc = RealDependencyLocation::from_byte_location(source, 1, 6, Some(18));
    assert!(loc.is_some());
    let loc = loc.unwrap();
    assert_eq!(loc.start.line, 1);
    assert_eq!(loc.start.column, 7);
    assert_eq!(loc.end.as_ref().unwrap().line, 3);
    assert_eq!(loc.end.as_ref().unwrap().column, 1);
  }

  #[test]
  fn test_from_byte_location_multiline_three_lines() {
    // Test length spanning three lines
    let source = "abc\ndefg\nhij\nklm";

    // Start at byte 2 on line 1 ("c"), length 10
    // "c\ndefg\nhi" = 1 + 1 + 4 + 1 + 2 = 9 bytes, so 10 includes "j"
    let loc = RealDependencyLocation::from_byte_location(source, 1, 2, Some(10));
    assert!(loc.is_some());
    let loc = loc.unwrap();
    assert_eq!(loc.start.line, 1);
    assert_eq!(loc.start.column, 3); // "c" is at column 3 (1-based)
    assert_eq!(loc.end.as_ref().unwrap().line, 3);
    assert_eq!(loc.end.as_ref().unwrap().column, 4); // "j" is at column 3 on line 3
  }

  #[test]
  fn test_from_byte_location_multiline_utf8() {
    // Test multiline with UTF-8 characters
    let source = "你好\n世界abc\n测试";

    // Start at byte 0 on line 1, length 12
    // "你好\n世界" = 6 + 1 + 6 = 13 bytes, so 12 doesn't include the last character
    let loc = RealDependencyLocation::from_byte_location(source, 1, 0, Some(13));
    assert!(loc.is_some());
    let loc = loc.unwrap();
    assert_eq!(loc.start.line, 1);
    assert_eq!(loc.start.column, 1);
    assert_eq!(loc.end.as_ref().unwrap().line, 2);
    assert_eq!(loc.end.as_ref().unwrap().column, 3); // "世界" = 2 UTF-16 units, column 3 (1-based)
  }

  #[test]
  fn test_from_byte_location_multiline_exact_line_end() {
    // Test when length ends exactly at a line boundary
    let source = "hello\nworld";

    // Start at byte 0, length 5 (exactly "hello")
    let loc = RealDependencyLocation::from_byte_location(source, 1, 0, Some(5));
    assert!(loc.is_some());
    let loc = loc.unwrap();
    assert_eq!(loc.start.line, 1);
    assert_eq!(loc.start.column, 1);
    assert_eq!(loc.end.as_ref().unwrap().line, 1);
    assert_eq!(loc.end.as_ref().unwrap().column, 6); // End of "hello"
  }

  #[test]
  fn test_from_byte_location_multiline_including_newline() {
    // Test when length includes the newline character
    let source = "hello\nworld";

    // Start at byte 0, length 6 (includes newline)
    let loc = RealDependencyLocation::from_byte_location(source, 1, 0, Some(6));
    assert!(loc.is_some());
    let loc = loc.unwrap();
    assert_eq!(loc.start.line, 1);
    assert_eq!(loc.start.column, 1);
    assert_eq!(loc.end.as_ref().unwrap().line, 2);
    assert_eq!(loc.end.as_ref().unwrap().column, 1); // First position of line 2
  }
}