Skip to main content

Token

Struct Token 

Source
pub struct Token<K> {
    pub span: Span,
    pub kind: K,
}
Expand description

A single lexical token: a kind paired with the Span of source it covers.

Token<K> is the shared seam between a lexer and a parser. The lexer produces a stream of Token<K>; the parser consumes it. Neither needs to know the other’s internals — they agree only on this pair. The kind K is the language’s own classification (an enum of keywords, punctuation, literals, and so on); token-lang stays language-agnostic by leaving K to the language and owning only the pairing with a span.

A token is a classified span: K says what was lexed, the Span says where. The type is Copy whenever K is, so a token whose kind is a plain enum (a discriminant plus an eight-byte span) is cheap to pass by value.

Token<K> mirrors Spanned<K> but carries token semantics: it orders by span first, so a slice of tokens sorts into source order; its Display reads as kind @ start..end; and when K: TokenKind it forwards the classification queries — is_trivia, is_eof, and symbol — to the kind. Convert between the two with the From impls when a layer wants the plain pair.

§Examples

use token_lang::{Span, Token, TokenKind};

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Kind {
    Ident,
    Plus,
    Eof,
}
impl TokenKind for Kind {
    fn is_eof(&self) -> bool {
        matches!(self, Kind::Eof)
    }
}

// `a + b` lexed into tokens, then the end marker.
let a = Token::new(Kind::Ident, Span::new(0, 1));
let plus = Token::new(Kind::Plus, Span::new(2, 3));
let eof = Token::new(Kind::Eof, Span::new(5, 5));

assert_eq!(*a.kind(), Kind::Ident);
assert_eq!(plus.span(), Span::new(2, 3));
assert!(eof.is_eof());

// Tokens are `Copy` and sort into source order.
let mut stream = [eof, a, plus];
stream.sort();
assert_eq!(stream, [a, plus, eof]);

Fields§

§span: Span

The half-open source range this token covers.

Declared before kind so the derived ordering compares the span first, sorting a slice of tokens into source order.

§kind: K

The language-specific kind of this token.

Implementations§

Source§

impl<K> Token<K>

Source

pub const fn new(kind: K, span: Span) -> Self

Pairs a kind with the span it was lexed from.

const, so a token can initialise a const or static table — useful for the fixed marker tokens (an end-of-input, a synthetic delimiter) a lexer hands out.

§Examples
use token_lang::{Span, Token};

let tok = Token::new("ident", Span::new(0, 5));
assert_eq!(*tok.kind(), "ident");
assert_eq!(tok.span(), Span::new(0, 5));
Source

pub const fn kind(&self) -> &K

Borrows this token’s kind.

§Examples
use token_lang::{Span, Token};

let tok = Token::new(42u8, Span::new(0, 1));
assert_eq!(*tok.kind(), 42);
Source

pub const fn span(&self) -> Span

Returns this token’s span.

Span is Copy, so this hands back the range by value rather than borrowing it.

§Examples
use token_lang::{Span, Token};

let tok = Token::new((), Span::new(3, 7));
assert_eq!(tok.span(), Span::new(3, 7));
Source

pub fn into_kind(self) -> K

Consumes the token, returning just its kind and dropping the span.

§Examples
use token_lang::{Span, Token};

let tok = Token::new(String::from("if"), Span::new(0, 2));
assert_eq!(tok.into_kind(), "if");
Source

pub fn map<U>(self, f: impl FnOnce(K) -> U) -> Token<U>

Transforms the kind with f, keeping the span unchanged.

This is how a layer lifts a token from one kind to another without losing where it came from — for example, mapping a raw lexer kind onto a coarser parser kind, or wrapping the kind in a richer type.

§Examples
use token_lang::{Span, Token};

let raw = Token::new("123", Span::new(4, 7));
let parsed = raw.map(|s| s.parse::<u32>().unwrap());
assert_eq!(*parsed.kind(), 123);
assert_eq!(parsed.span(), Span::new(4, 7));
Source

pub fn as_ref(&self) -> Token<&K>

Borrows the kind, yielding a Token<&K> with the same span.

Mirrors Option::as_ref: it lets you inspect or map the kind without consuming the original token.

§Examples
use token_lang::{Span, Token};

let owned = Token::new(String::from("name"), Span::new(0, 4));
let len = owned.as_ref().map(|s| s.len());
assert_eq!(*len.kind(), 4);
// `owned` is still usable.
assert_eq!(owned.kind(), "name");
Source§

impl<K: TokenKind> Token<K>

Source

pub fn is_trivia(&self) -> bool

Whether this token’s kind is trivia. Forwards to TokenKind::is_trivia.

§Examples
use token_lang::{Span, Token, TokenKind};

#[derive(Clone, Copy)]
enum Kind {
    Word,
    Space,
}
impl TokenKind for Kind {
    fn is_trivia(&self) -> bool {
        matches!(self, Kind::Space)
    }
}

assert!(Token::new(Kind::Space, Span::new(0, 1)).is_trivia());
assert!(!Token::new(Kind::Word, Span::new(1, 5)).is_trivia());
Source

pub fn is_eof(&self) -> bool

Whether this token’s kind is the end-of-input marker. Forwards to TokenKind::is_eof.

§Examples
use token_lang::{Span, Token, TokenKind};

#[derive(Clone, Copy)]
enum Kind {
    Word,
    Eof,
}
impl TokenKind for Kind {
    fn is_eof(&self) -> bool {
        matches!(self, Kind::Eof)
    }
}

assert!(Token::new(Kind::Eof, Span::empty(9)).is_eof());
assert!(!Token::new(Kind::Word, Span::new(0, 4)).is_eof());
Source

pub fn symbol(&self) -> Option<Symbol>

The interned lexeme this token carries, if any. Forwards to TokenKind::symbol.

§Examples
use intern_lang::Interner;
use token_lang::{Span, Symbol, Token, TokenKind};

#[derive(Clone, Copy)]
enum Kind {
    Ident(Symbol),
    Plus,
}
impl TokenKind for Kind {
    fn symbol(&self) -> Option<Symbol> {
        match self {
            Kind::Ident(s) => Some(*s),
            Kind::Plus => None,
        }
    }
}

let mut interner = Interner::new();
let tok = Token::new(Kind::Ident(interner.intern("x")), Span::new(0, 1));
assert_eq!(tok.symbol().and_then(|s| interner.resolve(s)), Some("x"));
assert_eq!(Token::new(Kind::Plus, Span::new(1, 2)).symbol(), None);

Trait Implementations§

Source§

impl<K: Clone> Clone for Token<K>

Source§

fn clone(&self) -> Token<K>

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<K: Copy> Copy for Token<K>

Source§

impl<K: Debug> Debug for Token<K>

Source§

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

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

impl<'de, K> Deserialize<'de> for Token<K>
where K: Deserialize<'de>,

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<K: Display> Display for Token<K>

Source§

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

Formats as kind @ start..end.

Source§

impl<K: Eq> Eq for Token<K>

Source§

impl<K> From<(K, Span)> for Token<K>

Source§

fn from((kind, span): (K, Span)) -> Self

Builds a token from a (kind, span) pair, matching the new argument order.

Source§

impl<K> From<Spanned<K>> for Token<K>

Source§

fn from(spanned: Spanned<K>) -> Self

The inverse of the token-to-Spanned conversion: reinterprets a spanned value as a token of that kind, preserving both fields.

Source§

impl<K> From<Token<K>> for Spanned<K>

Source§

fn from(token: Token<K>) -> Self

A token is a spanned kind; this drops the token semantics for the plain Spanned pair, preserving both fields.

Source§

impl<K: Hash> Hash for Token<K>

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<K: Ord> Ord for Token<K>

Source§

fn cmp(&self, other: &Token<K>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<K: PartialEq> PartialEq for Token<K>

Source§

fn eq(&self, other: &Token<K>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<K: PartialOrd> PartialOrd for Token<K>

Source§

fn partial_cmp(&self, other: &Token<K>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<K> Serialize for Token<K>
where K: Serialize,

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<K: PartialEq> StructuralPartialEq for Token<K>

Auto Trait Implementations§

§

impl<K> Freeze for Token<K>
where K: Freeze,

§

impl<K> RefUnwindSafe for Token<K>
where K: RefUnwindSafe,

§

impl<K> Send for Token<K>
where K: Send,

§

impl<K> Sync for Token<K>
where K: Sync,

§

impl<K> Unpin for Token<K>
where K: Unpin,

§

impl<K> UnsafeUnpin for Token<K>
where K: UnsafeUnpin,

§

impl<K> UnwindSafe for Token<K>
where K: UnwindSafe,

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> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

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

Source§

type Error = Infallible

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.