Trait parsel::util::SpannedExt

source ·
pub trait SpannedExt {
    // Required method
    fn span(&self) -> Span;

    // Provided methods
    fn format_span(&self) -> SpanDisplay { ... }
    fn source_substring<'s>(&self, source: &'s str) -> &'s str { ... }
    fn byte_range(&self, source: &str) -> Range<usize> { ... }
    fn char_range(&self, source: &str) -> Range<usize> { ... }
}
Expand description

Extension trait for formatting the span of AST nodes in a human-readable manner, and for (re-)computing byte offsets into the source based on the line/column location, since this information is not exposed by the public API of Span.

This does not impose Spanned as a supertrait so that any type that reasonably implements SpannedExt::span() should be able to implement it, without having to implement ToTokens (directly implementing Spanned is not possible, as it is sealed as of Syn 2.0.)

Required Methods§

source

fn span(&self) -> Span

Provided Methods§

source

fn format_span(&self) -> SpanDisplay

source

fn source_substring<'s>(&self, source: &'s str) -> &'s str

source

fn byte_range(&self, source: &str) -> Range<usize>

TODO(H2CO3): a faster, less naive implementation would be great. We should use the byte offset of start to compute that of end, sparing the double scan of the source up until the start location.

let source = r#"
   -3.667
  1248  "string ű literal"
      "wíőzs"
"#;
let tokens: Many<Lit> = source.parse()?;

assert_eq!(tokens.len(), 4);
assert_eq!(tokens[0].byte_range(source),  4..10);
assert_eq!(tokens[1].byte_range(source), 13..17);
assert_eq!(tokens[2].byte_range(source), 19..38);
assert_eq!(tokens[3].byte_range(source), 45..54);
source

fn char_range(&self, source: &str) -> Range<usize>

TODO(H2CO3): a faster, less naive implementation would be great. We should use the char offset of start to compute that of end, sparing the double scan of the source up until the start location.

let source = r#"
   -3.667
  1248  "string ű literal"
      "wíőzs"
"#;
let tokens: Many<Lit> = source.parse()?;

assert_eq!(tokens.len(), 4);
assert_eq!(tokens[0].char_range(source),  4..10);
assert_eq!(tokens[1].char_range(source), 13..17);
assert_eq!(tokens[2].char_range(source), 19..37);
assert_eq!(tokens[3].char_range(source), 44..51);

Implementors§

source§

impl<T> SpannedExt for T
where T: ?Sized + Spanned,