Skip to content

Commit

Permalink
Merge pull request #409 from dtolnay/sourcetext
Browse files Browse the repository at this point in the history
Account for multibyte chars in source_text() computation
  • Loading branch information
dtolnay committed Oct 6, 2023
2 parents 07bb590 + 7f5533d commit 299d8ff
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/fallback.rs
Expand Up @@ -364,8 +364,13 @@ impl FileInfo {

fn source_text(&self, span: Span) -> String {
let lo = (span.lo - self.span.lo) as usize;
let hi = (span.hi - self.span.lo) as usize;
self.source_text[lo..hi].to_owned()
let trunc_lo = &self.source_text[lo..];
let char_len = (span.hi - span.lo) as usize;
let source_text = match trunc_lo.char_indices().nth(char_len) {
Some((offset, _ch)) => &trunc_lo[..offset],
None => trunc_lo,
};
source_text.to_owned()
}
}

Expand Down
9 changes: 9 additions & 0 deletions tests/test.rs
Expand Up @@ -325,6 +325,15 @@ fn literal_span() {
assert!(positive.subspan(1..4).is_none());
}

#[cfg(span_locations)]
#[test]
fn source_text() {
let input = " 𓀕 ";
let tokens = input.parse::<proc_macro2::TokenStream>().unwrap();
let ident = tokens.into_iter().next().unwrap();
assert_eq!("𓀕", ident.span().source_text().unwrap());
}

#[test]
fn roundtrip() {
fn roundtrip(p: &str) {
Expand Down

0 comments on commit 299d8ff

Please sign in to comment.