Skip to content

Commit 299d8ff

Browse files
authored
Merge pull request #409 from dtolnay/sourcetext
Account for multibyte chars in source_text() computation
2 parents 07bb590 + 7f5533d commit 299d8ff

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/fallback.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -364,8 +364,13 @@ impl FileInfo {
364364

365365
fn source_text(&self, span: Span) -> String {
366366
let lo = (span.lo - self.span.lo) as usize;
367-
let hi = (span.hi - self.span.lo) as usize;
368-
self.source_text[lo..hi].to_owned()
367+
let trunc_lo = &self.source_text[lo..];
368+
let char_len = (span.hi - span.lo) as usize;
369+
let source_text = match trunc_lo.char_indices().nth(char_len) {
370+
Some((offset, _ch)) => &trunc_lo[..offset],
371+
None => trunc_lo,
372+
};
373+
source_text.to_owned()
369374
}
370375
}
371376

tests/test.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,15 @@ fn literal_span() {
325325
assert!(positive.subspan(1..4).is_none());
326326
}
327327

328+
#[cfg(span_locations)]
329+
#[test]
330+
fn source_text() {
331+
let input = " 𓀕 ";
332+
let tokens = input.parse::<proc_macro2::TokenStream>().unwrap();
333+
let ident = tokens.into_iter().next().unwrap();
334+
assert_eq!("𓀕", ident.span().source_text().unwrap());
335+
}
336+
328337
#[test]
329338
fn roundtrip() {
330339
fn roundtrip(p: &str) {

0 commit comments

Comments
 (0)