Skip to main content

Span

Struct Span 

Source
pub struct Span { /* private fields */ }
Expand description

Where syntax originated and, when available, the source buffer it indexes.

Source-derived tokens retain only this value. Their spelling is recovered by slicing the shared source buffer; it is never copied into token or syntax node storage. Spans constructed only from offsets remain useful for diagnostics and synthetic trees, but naturally cannot yield source text.

Implementations§

Source§

impl Span

Source

pub const Detached: Self

A detached span without source text.

Source

pub fn detached() -> Self

Creates a span with no source location.

Examples found in repository?
examples/parse_emit_walkthrough.rs (line 14)
10    fn parse(input: &mut ParseStream) -> Result<Self, TokenParseError> {
11        let Some(token) = input.next_token() else {
12            return Err(TokenParseError::UnexpectedEnd {
13                expected: "identifier",
14                span: Span::detached(),
15            });
16        };
17
18        let span = token.span();
19        match token {
20            TokenTree::Ident(identifier) => Ok(Self(identifier)),
21            token => Err(TokenParseError::UnexpectedToken {
22                expected: "identifier",
23                found: token.spelling().unwrap_or("group or trivia").to_owned(),
24                span,
25            }),
26        }
27    }
Source

pub fn new(start: Offset, end: Offset) -> Self

Builds a span covering start..end, where end is the offset past the last byte.

An inverted pair collapses to Detached rather than fabricating a range.

Source

pub fn from_offset(offset: Offset) -> Self

A zero-width span at one boundary, for syntax that occupies no bytes.

Source

pub fn with_text(self, text: impl Into<Arc<str>>) -> Self

Attaches the complete source fragment covered by this span.

Existing source backing is retained. For an offset-only span, text must have the same byte width as the span; its first byte is associated with the span’s opening offset. Detached syntax may also carry a source fragment, which is useful for programmatically constructed syntax.

§Panics

Panics when an offset-only span and text have different byte widths.

Source

pub fn replaced_text(&self, text: impl Into<Arc<str>>) -> Self

Replaces this span’s source fragment while retaining its opening location and updating its width.

Source

pub fn source(text: impl Into<Arc<str>>) -> Self

Creates a source-backed span covering an entire source buffer.

Source

pub fn subspan(&self, start: Offset, end: Offset) -> Self

Returns a subspan at byte offsets relative to this span’s opening.

The returned span shares the same source buffer. Invalid or detached ranges become detached spans.

Source

pub fn text(&self) -> Option<&str>

Returns the exact source text covered by this span when source backing is available.

Source

pub fn shares_source(&self, other: &Self) -> bool

Reports whether both spans slice the same shared source buffer.

Source

pub fn start(&self) -> Option<Offset>

The boundary this span opens at, or None when it is detached.

Source

pub fn end(&self) -> Option<Offset>

The boundary this span closes at, past its last byte.

Source

pub fn bounds(&self) -> Option<(Offset, Offset)>

The boundaries this span lies between.

Examples found in repository?
examples/live_parser.rs (line 41)
39fn write_diagnostic(output: &mut String, diagnostic: &LexError) {
40    let span = diagnostic.span();
41    output.push_str(&format!("- {diagnostic} at {:?}\n", span.bounds()));
42}
Source

pub fn len(&self) -> Option<usize>

How many bytes this span covers, or None when it is detached.

Source

pub fn is_empty(&self) -> bool

Reports whether this span covers no bytes, as the virtual marker tokens do. Detached syntax covers no bytes either.

Source

pub fn contains(&self, offset: Offset) -> bool

Returns whether offset lies inside this span, excluding its closing boundary.

Boundaries sit between bytes, so the closing one belongs to whatever follows: in a+b the boundary after a is contained by +, not by a. This is the predicate to use when exactly one span must own a position. A zero-width span contains nothing, having no interior.

Source

pub fn touches(&self, offset: Offset) -> bool

Returns whether offset lies inside this span or on either boundary.

Adjacent spans both touch the boundary between them, so this answers “which syntax is the cursor at” rather than “which syntax owns this position” — a cursor just past an identifier still touches it, and a zero-width marker is touched at its own position.

Source

pub fn shifted(&self, edit: &TextEdit) -> Self

Returns this span’s position in the buffer produced by edit.

Both boundaries move under the same rule, so nothing here decides which side of an insertion a boundary belongs to. Because that rule is monotone the pair can never invert, and a zero-width span needs no special case: its two equal boundaries stay equal.

Text inserted at a span’s closing boundary therefore extends the span, which is what an unclosed group wants — it keeps reaching whatever now follows it. A span wholly removed by a deletion collapses to a zero-width span at the deletion point rather than becoming Self::Detached, because it still records where the syntax used to be.

Source

pub fn join(&self, other: Self) -> Self

The smallest span covering both, ignoring detached operands.

Source

pub fn meet(&self, other: Self) -> Self

The overlap of both, or Detached when they do not overlap.

Source

pub fn join_all(spans: impl IntoIterator<Item = Span>) -> Self

Joins every span in an iterator, ignoring detached spans.

Trait Implementations§

Source§

impl Clone for Span

Source§

fn clone(&self) -> Span

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Span

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Span

Source§

fn default() -> Span

Returns the “default value” for a type. Read more
Source§

impl Eq for Span

Source§

impl Hash for Span

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Index<&Span> for str

Source§

type Output = str

The returned type after indexing.
Source§

fn index(&self, span: &Span) -> &str

Performs the indexing (container[index]) operation. Read more
Source§

impl Index<&Span> for String

Source§

type Output = str

The returned type after indexing.
Source§

fn index(&self, span: &Span) -> &str

Performs the indexing (container[index]) operation. Read more
Source§

impl Index<Span> for str

Indexes the buffer, panicking when the span does not name text in it.

This is legal despite Index and str both being foreign because Span is local, and it cannot overlap str’s own impl<I: SliceIndex<str>> Index<I> for str because Span does not implement SliceIndex.

Source§

type Output = str

The returned type after indexing.
Source§

fn index(&self, span: Span) -> &str

Performs the indexing (container[index]) operation. Read more
Source§

impl Index<Span> for String

String needs its own implementation rather than reaching str’s through deref: it already has an Index impl of its own, so operator resolution stops there instead of falling through.

Source§

type Output = str

The returned type after indexing.
Source§

fn index(&self, span: Span) -> &str

Performs the indexing (container[index]) operation. Read more
Source§

impl PartialEq for Span

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Spanned for Span

Source§

fn span(&self) -> Span

Returns the smallest span covering this value.

Auto Trait Implementations§

§

impl Freeze for Span

§

impl RefUnwindSafe for Span

§

impl Send for Span

§

impl Sync for Span

§

impl Unpin for Span

§

impl UnsafeUnpin for Span

§

impl UnwindSafe for Span

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.