Skip to main content

xgrammar/parser/
token.rs

1//! A lexical token and its processed value.
2//! `cpp/grammar_parser.h` (value becomes a typed [`TokenValue`]).
3
4use super::{rule_attributes::RuleAttributes, token_type::TokenType};
5
6/// The processed payload attached to a token .
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum TokenValue {
9    /// No payload (punctuation, EOF, …).
10    None,
11    /// An integer literal value.
12    Int(i64),
13    /// A boolean literal value.
14    Bool(bool),
15    /// A decoded string: the value of a string literal, or an identifier's text.
16    Str(String),
17    /// A codepoint, for a literal character in a character class.
18    Codepoint(i32),
19}
20
21impl TokenValue {
22    /// The integer value, if this is [`TokenValue::Int`].
23    #[must_use]
24    pub fn as_int(&self) -> Option<i64> {
25        match self {
26            TokenValue::Int(v) => Some(*v),
27            _ => None,
28        }
29    }
30
31    /// The boolean value, if this is [`TokenValue::Bool`].
32    #[must_use]
33    pub fn as_bool(&self) -> Option<bool> {
34        match self {
35            TokenValue::Bool(v) => Some(*v),
36            _ => None,
37        }
38    }
39
40    /// The string value, if this is [`TokenValue::Str`].
41    #[must_use]
42    pub fn as_str(&self) -> Option<&str> {
43        match self {
44            TokenValue::Str(s) => Some(s),
45            _ => None,
46        }
47    }
48
49    /// The codepoint value, if this is [`TokenValue::Codepoint`].
50    #[must_use]
51    pub fn as_codepoint(&self) -> Option<i32> {
52        match self {
53            TokenValue::Codepoint(c) => Some(*c),
54            _ => None,
55        }
56    }
57}
58
59/// A single lexical token: its kind, the original source text, a processed value, and the
60/// 1-based source position where it began.
61#[derive(Debug, Clone, PartialEq)]
62pub struct Token {
63    /// The token kind.
64    pub ty: TokenType,
65    /// The original source text of the token.
66    pub lexeme: String,
67    /// The processed value.
68    pub value: TokenValue,
69    /// 1-based line where the token starts.
70    pub line: i32,
71    /// 1-based column where the token starts.
72    pub column: i32,
73    /// The attribute block of a rule-definition identifier, e.g. `name[max_tokens=10] ::= ...`.
74    pub rule_attributes: Option<RuleAttributes>,
75}