pub struct Spanned<T> {
pub span: Span,
pub value: T,
}Expand description
A value together with the source Span it was parsed from.
Spanned<T> is the wrapper a parser puts around every token and AST node so
the value carries its location without the value type itself knowing anything
about positions. It is a transparent pair — both fields are public — and it is
Copy whenever T is, so wrapping a small token in a span costs nothing.
Spans order before values, so a slice of Spanned<T> sorts into source order
when T: Ord.
§Examples
use span_lang::{Span, Spanned};
// A token: the identifier `width` at bytes 4..9.
let ident = Spanned::new(Span::new(4, 9), "width");
assert_eq!(ident.value, "width");
assert_eq!(ident.span, Span::new(4, 9));
// Transform the value, keeping the span.
let len = ident.map(|s| s.len());
assert_eq!(len.value, 5);
assert_eq!(len.span, Span::new(4, 9));Fields§
§span: SpanThe source span the value was read from.
value: TThe wrapped value.
Implementations§
Source§impl<T> Spanned<T>
impl<T> Spanned<T>
Sourcepub const fn new(span: Span, value: T) -> Self
pub const fn new(span: Span, value: T) -> Self
Pairs a value with its span.
§Examples
use span_lang::{Span, Spanned};
let node = Spanned::new(Span::new(0, 3), 42);
assert_eq!(node.value, 42);Sourcepub fn map<U>(self, f: impl FnOnce(T) -> U) -> Spanned<U>
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Spanned<U>
Applies f to the value, keeping the span unchanged.
This is how a parser lifts a raw token into a typed node without losing
where it came from — for example, turning a Spanned<&str> lexeme into a
Spanned<Ident>.
§Examples
use span_lang::{Span, Spanned};
let raw = Spanned::new(Span::new(2, 5), "10");
let parsed = raw.map(|s| s.parse::<u32>().unwrap());
assert_eq!(parsed.value, 10);
assert_eq!(parsed.span, Span::new(2, 5));Sourcepub fn as_ref(&self) -> Spanned<&T>
pub fn as_ref(&self) -> Spanned<&T>
Borrows the value, yielding a Spanned<&T> with the same span.
Mirrors Option::as_ref: it lets you inspect or map the value without
consuming the original Spanned.
§Examples
use span_lang::{Span, Spanned};
let owned = Spanned::new(Span::new(0, 4), String::from("name"));
let borrowed = owned.as_ref().map(|s| s.len());
assert_eq!(borrowed.value, 4);
// `owned` is still usable.
assert_eq!(owned.value, "name");