Skip to main content

xgrammar/parser/
parser_state.rs

1//! The state of the Earley parser.
2//!
3//! A live state walks a rule's compiled FSM: `element_id` is the current FSM node,
4//! `rule_start_pos` the input position the rule was predicted at. `Eq`/`Hash` cover all
5//! fields (equality/hash for parsing), which is what the parser's queue de-duplication needs.
6//! The derived `Ord` is lexicographic over the fields in declaration order; it is only used to
7//! sort states for deterministic serialization.
8
9use std::fmt;
10
11use super::parser_state_cache_key::ParserStateCacheKey;
12
13/// One Earley item: a position within a rule's FSM plus the input position it began at.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
15pub struct ParserState {
16    /// The rule's id (`-1` for an IR-path lookahead state).
17    pub rule_id: i32,
18    /// The rule body (or lookahead sequence) expression id.
19    pub sequence_id: i32,
20    /// The current FSM node (or element index in an IR sequence).
21    pub element_id: i32,
22    /// The input position the rule started at, or [`Self::NO_PREV_INPUT_POS`] for the root.
23    pub rule_start_pos: i32,
24    /// The last token index this state's derivation may consume, from the token budget
25    /// (`Rule::max_tokens`) of the rule it is inside; `-1` means unlimited.
26    pub budget_deadline: i32,
27    /// The id of the sub element in the current element of the sequence.
28    pub sub_element_id: i32,
29    /// The number of times the element is repeated (for repeat edges).
30    pub repeat_count: i32,
31    /// Partial codepoint accumulated during UTF-8 decoding for character classes.
32    pub partial_codepoint: i32,
33    /// The innermost active rule that specifies a sampling temperature, or `-1`.
34    pub active_temperature_rule_id: i32,
35    /// The absolute input codepoint position at which the active character budget expires;
36    /// `-1` means unlimited.
37    pub char_budget_deadline: i32,
38}
39
40impl ParserState {
41    /// A `rule_start_pos` meaning the state is the root of the parsing stack.
42    pub const NO_PREV_INPUT_POS: i32 = -1;
43
44    /// Creates a state at `element_id` of `sequence_id` with no budgets, sub element, repeat
45    /// count, partial codepoint, or temperature rule.
46    #[must_use]
47    pub fn new(
48        rule_id: i32,
49        sequence_id: i32,
50        element_id: i32,
51        rule_start_pos: i32,
52    ) -> Self {
53        Self {
54            rule_id,
55            sequence_id,
56            element_id,
57            rule_start_pos,
58            budget_deadline: -1,
59            sub_element_id: 0,
60            repeat_count: 0,
61            partial_codepoint: 0,
62            active_temperature_rule_id: -1,
63            char_budget_deadline: -1,
64        }
65    }
66
67    /// The same occurrence moved to `element_id`, with the sub element, repeat count, and
68    /// partial codepoint reset (budgets and the temperature rule are inherited).
69    #[must_use]
70    pub fn at_element(
71        &self,
72        element_id: i32,
73    ) -> Self {
74        self.at_element_with_repeat(element_id, 0)
75    }
76
77    /// Like [`Self::at_element`], keeping `repeat_count`.
78    #[must_use]
79    pub fn at_element_with_repeat(
80        &self,
81        element_id: i32,
82        repeat_count: i32,
83    ) -> Self {
84        Self {
85            element_id,
86            sub_element_id: 0,
87            repeat_count,
88            partial_codepoint: 0,
89            ..*self
90        }
91    }
92
93    /// The adaptive token-mask cache key of this state.
94    #[must_use]
95    pub fn cache_key(&self) -> ParserStateCacheKey {
96        ParserStateCacheKey {
97            rule_id: self.rule_id,
98            sequence_id: self.sequence_id,
99            element_id: self.element_id,
100            sub_element_id: self.sub_element_id,
101        }
102    }
103
104    /// Serializes as the C++ `XGRAMMAR_MEMBER_ARRAY` order.
105    #[inline]
106    #[must_use]
107    pub fn serialize_member_array(&self) -> [i32; 10] {
108        [
109            self.rule_id,
110            self.sequence_id,
111            self.element_id,
112            self.rule_start_pos,
113            self.budget_deadline,
114            self.sub_element_id,
115            self.repeat_count,
116            self.partial_codepoint,
117            self.active_temperature_rule_id,
118            self.char_budget_deadline,
119        ]
120    }
121
122    /// Deserializes a member array produced by [`Self::serialize_member_array`].
123    ///
124    /// Returns `None` unless `values` contains exactly ten integers.
125    #[must_use]
126    pub fn from_member_array(values: &[i32]) -> Option<Self> {
127        let [
128            rule_id,
129            sequence_id,
130            element_id,
131            rule_start_pos,
132            budget_deadline,
133            sub_element_id,
134            repeat_count,
135            partial_codepoint,
136            active_temperature_rule_id,
137            char_budget_deadline,
138        ] = *values
139        else {
140            return None;
141        };
142        Some(Self {
143            rule_id,
144            sequence_id,
145            element_id,
146            rule_start_pos,
147            budget_deadline,
148            sub_element_id,
149            repeat_count,
150            partial_codepoint,
151            active_temperature_rule_id,
152            char_budget_deadline,
153        })
154    }
155}
156
157impl fmt::Display for ParserState {
158    fn fmt(
159        &self,
160        f: &mut fmt::Formatter<'_>,
161    ) -> fmt::Result {
162        write!(
163            f,
164            "ParserState(rule_id={}, sequence_id={}, element_id={}, rule_start_pos={}, sub_element_id={}",
165            self.rule_id, self.sequence_id, self.element_id, self.rule_start_pos, self.sub_element_id
166        )?;
167        if self.repeat_count != 0 {
168            write!(f, ", repeat_count={}", self.repeat_count)?;
169        }
170        if self.partial_codepoint != 0 {
171            write!(f, ", partial_codepoint={}", self.partial_codepoint)?;
172        }
173        if self.budget_deadline != -1 {
174            write!(f, ", budget_deadline={}", self.budget_deadline)?;
175        }
176        if self.active_temperature_rule_id != -1 {
177            write!(f, ", active_temperature_rule_id={}", self.active_temperature_rule_id)?;
178        }
179        if self.char_budget_deadline != -1 {
180            write!(f, ", char_budget_deadline={}", self.char_budget_deadline)?;
181        }
182        f.write_str(")")
183    }
184}