1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
#![cfg_attr(feature = "strict_docs", allow(missing_docs))]
//! Pure-Rust parser implementation using compressed parse tables.
// Pure-Rust parser implementation using compressed tables
// This implements Tree-sitter's parsing algorithm with GLR support
use crate::abi::*;
/// A parser state consisting of the current state ID and lookahead symbol.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseState {
/// Current parser state index.
pub state: u16,
/// Current lookahead token symbol.
pub lookahead: u16,
}
/// A node in the parse tree produced by the compressed table parser.
#[derive(Debug, Clone)]
pub struct ParseNode {
/// Symbol ID of this node.
pub symbol: u16,
/// Child nodes.
pub children: Vec<ParseNode>,
/// Byte offset where this node starts.
pub start_byte: usize,
/// Byte offset where this node ends.
pub end_byte: usize,
}
/// A parser that drives parsing using compressed parse tables.
pub struct Parser {
language: &'static TSLanguage,
stack: Vec<ParseState>,
nodes: Vec<ParseNode>,
}
impl Parser {
pub fn new(language: &'static TSLanguage) -> Self {
Self {
language,
stack: vec![ParseState {
state: 0,
lookahead: 0,
}],
nodes: Vec::new(),
}
}
/// Parse input text using the compressed tables
pub fn parse(&mut self, input: &str) -> Result<ParseNode, String> {
let tokens = self.tokenize(input)?;
let mut position = 0;
while position < tokens.len() {
let token = tokens[position];
let current_state = self
.stack
.last()
.ok_or_else(|| "parser stack is empty".to_string())?
.state;
// Look up action in compressed table
let action = self.get_action(current_state, token.symbol)?;
match action {
ParseAction::Shift(state) => {
self.stack.push(ParseState {
state,
lookahead: token.symbol,
});
self.nodes.push(ParseNode {
symbol: token.symbol,
children: Vec::new(),
start_byte: token.start,
end_byte: token.end,
});
position += 1;
}
ParseAction::Reduce(rule_id) => {
self.perform_reduction(rule_id)?;
}
ParseAction::Accept => {
if self.nodes.len() == 1 {
return Ok(self.nodes.pop().expect("length checked == 1"));
}
return Err("Accept but multiple nodes remain".to_string());
}
ParseAction::Error => {
return Err(format!("Parse error at position {}", position));
}
}
}
Err("Unexpected end of input".to_string())
}
fn get_action(&self, state: u16, symbol: u16) -> Result<ParseAction, String> {
// Access compressed parse table
let parse_table = unsafe {
// SAFETY: `self.language.parse_table` must be a valid pointer to at least
// `state_count * 2` contiguous `u16` values. This is guaranteed by the
// TSLanguage ABI contract — callers must supply a well-formed language struct.
// TODO(safety): No runtime validation that `parse_table` is non-null; a null
// pointer here is instant UB. Consider adding a null check.
std::slice::from_raw_parts(
self.language.parse_table,
self.language.state_count as usize * 2,
)
};
// Decode compressed action
let table_offset = (state as usize) * 2;
if table_offset + 1 >= parse_table.len() {
return Err("State out of bounds".to_string());
}
let entry_count = parse_table[table_offset];
let data_offset = parse_table[table_offset + 1] as usize;
// Search for symbol in action entries
for i in 0..entry_count {
let entry_offset = data_offset + (i as usize) * 2;
if entry_offset + 1 >= parse_table.len() {
continue;
}
let entry_symbol = parse_table[entry_offset];
if entry_symbol == symbol {
let action_data = parse_table[entry_offset + 1];
return Ok(self.decode_action(action_data));
}
}
// Check default action
if entry_count > 0 {
let default_offset = data_offset + (entry_count as usize - 1) * 2 + 1;
if default_offset < parse_table.len() {
let default_action = parse_table[default_offset];
return Ok(self.decode_action(default_action));
}
}
Ok(ParseAction::Error)
}
fn decode_action(&self, encoded: u16) -> ParseAction {
match encoded {
0xFFFF => ParseAction::Accept,
0xFFFE => ParseAction::Error,
_ if encoded & 0x8000 != 0 => {
let rule_id = (encoded & 0x7FFF) >> 1;
ParseAction::Reduce(rule_id)
}
state => ParseAction::Shift(state),
}
}
fn perform_reduction(&mut self, rule_id: u16) -> Result<(), String> {
// Get rule info from grammar
let production_id_map = unsafe {
// SAFETY: `self.language.production_id_map` must point to at least
// `production_id_count` contiguous `u16` values per the TSLanguage ABI.
// TODO(safety): No null-pointer guard — UB if production_id_map is null.
std::slice::from_raw_parts(
self.language.production_id_map,
self.language.production_id_count as usize,
)
};
if rule_id as usize >= production_id_map.len() {
return Err("Invalid rule ID".to_string());
}
// For now, simplified reduction - real implementation needs rule lengths
// This would come from the grammar IR
let rule_length = 2; // Placeholder
// Pop rule_length items from stack
for _ in 0..rule_length {
self.stack.pop();
}
// Create new node for the reduction
let mut children = Vec::new();
for _ in 0..rule_length {
if let Some(node) = self.nodes.pop() {
children.push(node);
}
}
children.reverse();
let start_byte = children.first().map(|n| n.start_byte).unwrap_or(0);
let end_byte = children.last().map(|n| n.end_byte).unwrap_or(0);
// Get LHS symbol for the rule (would come from grammar)
let lhs_symbol = rule_id + self.language.token_count as u16; // Simplified
self.nodes.push(ParseNode {
symbol: lhs_symbol,
children,
start_byte,
end_byte,
});
// Get goto state
let current_state = self
.stack
.last()
.ok_or_else(|| "parser stack is empty after reduction".to_string())?
.state;
let goto_state = self.get_goto(current_state, lhs_symbol)?;
self.stack.push(ParseState {
state: goto_state,
lookahead: lhs_symbol,
});
Ok(())
}
fn get_goto(&self, state: u16, _symbol: u16) -> Result<u16, String> {
// Access small parse table for gotos
let small_parse_table_map = unsafe {
// SAFETY: `self.language.small_parse_table_map` must point to at least
// `state_count * 4` contiguous `u32` values per the TSLanguage ABI.
// TODO(safety): No null-pointer guard — UB if small_parse_table_map is null.
std::slice::from_raw_parts(
self.language.small_parse_table_map,
self.language.state_count as usize * 4,
)
};
// Simplified goto lookup - real implementation would decode the compressed goto table
let map_offset = (state as usize) * 4;
if map_offset + 3 >= small_parse_table_map.len() {
return Ok(0); // Default to state 0
}
// This is a simplified version - actual implementation needs proper goto decoding
Ok(state + 1)
}
fn tokenize(&self, input: &str) -> Result<Vec<Token>, String> {
// Simplified tokenizer - real implementation would use tree-sitter lexer
let mut tokens = Vec::new();
let _position = 0;
for (i, ch) in input.chars().enumerate() {
if ch.is_whitespace() {
continue;
}
// Map characters to token IDs (simplified)
let symbol = match ch {
'(' => 1,
')' => 2,
'+' => 3,
'-' => 4,
'*' => 5,
'/' => 6,
_ if ch.is_ascii_digit() => 7,
_ => return Err(format!("Unknown character: {}", ch)),
};
tokens.push(Token {
symbol,
start: i,
end: i + 1,
});
}
// Add EOF token
tokens.push(Token {
symbol: 0,
start: input.len(),
end: input.len(),
});
Ok(tokens)
}
}
#[derive(Debug, Clone, Copy)]
struct Token {
symbol: u16,
start: usize,
end: usize,
}
#[derive(Debug, Clone, Copy)]
enum ParseAction {
Shift(u16),
Reduce(u16),
Accept,
Error,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_decode_action() {
// Create a dummy language for testing
let lang = TSLanguage {
version: 0,
symbol_count: 0,
alias_count: 0,
token_count: 0,
external_token_count: 0,
state_count: 0,
large_state_count: 0,
production_id_count: 0,
field_count: 0,
max_alias_sequence_length: 0,
production_id_map: std::ptr::null(),
parse_table: std::ptr::null(),
small_parse_table: std::ptr::null(),
small_parse_table_map: std::ptr::null(),
parse_actions: std::ptr::null(),
symbol_names: std::ptr::null(),
field_names: std::ptr::null(),
field_map_slices: std::ptr::null(),
field_map_entries: std::ptr::null(),
symbol_metadata: std::ptr::null(),
public_symbol_map: std::ptr::null(),
alias_map: std::ptr::null(),
alias_sequences: std::ptr::null(),
lex_modes: std::ptr::null(),
lex_fn: None,
keyword_lex_fn: None,
keyword_capture_token: TSSymbol(0),
external_scanner: ExternalScanner::default(),
primary_state_ids: std::ptr::null(),
production_lhs_index: std::ptr::null(),
production_count: 0,
eof_symbol: 0,
};
// For testing, we'll use unsafe to extend the lifetime
// SAFETY: `lang` is stack-local and lives for the rest of this scope.
// We create a pointer and immediately re-borrow it as `&'static` to
// satisfy `Parser::new`. This is sound only because `parser` does not
// escape this function.
let parser = unsafe {
let lang_ptr = &lang as *const TSLanguage;
Parser::new(&*lang_ptr)
};
// Test shift action
assert!(matches!(parser.decode_action(42), ParseAction::Shift(42)));
// Test reduce action
assert!(matches!(
parser.decode_action(0x8002),
ParseAction::Reduce(1)
));
// Test accept
assert!(matches!(parser.decode_action(0xFFFF), ParseAction::Accept));
// Test error
assert!(matches!(parser.decode_action(0xFFFE), ParseAction::Error));
}
}