shiftkit 0.2.0

A Rust library for building parsers and grammars
Documentation
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# ShiftKit

A generic LALR(1) parser generator with a flat, index-based AST representation.

## Design Philosophy

Unlike traditional parser generators that produce recursive AST structures with `Box<AstNode>` references, ShiftKit takes a different approach: **the parser returns a flat `Vec` of AST nodes**, where nodes reference their children by index rather than by pointer.

This design offers several advantages:
- **Memory efficiency**: No pointer overhead, better cache locality
- **Predictable memory layout**: All nodes stored contiguously
- **Easy traversal**: Iterate through the entire AST with a simple loop

## Key Concepts

### Token Types

Tokens require unique IDs for grammar definitions via **`TokenType(u32)`**.
Your custom token type must implement:

```rust
pub trait HasTokenType {
    fn token_type(&self) -> TokenType;
}
```

This lets you define tokens however you want (enums, structs, etc.) while the parser uses `token_type()` to identify them during parsing.

### AST Node Types - Grammar Only

**`AstNodeType(u32)`** is used **only for defining grammar rules**, not for the AST nodes themselves.

**Key insight:** The parser tracks which `AstNodeType` each node has internally based on which grammar rule created it.
Your AST nodes don't need to store or know their type - that's the parser's job.

This means your AST can be extremely simple:

```rust
#[derive(Debug, Clone)]
enum AstNode {
    Number(i64),
    BinOp(AstNodeId, BinOpType, AstNodeId),
}
```

You control precedence through grammar structure (e.g., separate `VALUE`, `PRODUCT`, `SUM` node types in the grammar), but all binary operations map to the same simple `BinOp` variant in your AST.

### Reduction Results: New Nodes vs Pass-Through

Reduction functions receive indices corresponding to the grammar rule symbols and return a `ReductionResult`:

```rust
// Reduction function signature
type ReductionFn<T, A> = fn(indices: &[Index], tokens: &[T], nodes: &[A]) -> ReductionResult<A>;

// Index is either a token position or AST node position
pub enum Index {
    Token(TokenId),
    AstNode(AstNodeId),
}

// Result is either a new node or a forwarded node
pub enum ReductionResult<A> {
    /// Create a new AST node and append it to the Vec
    NewNode(A),
    /// Reuse an existing AST node (for pass-through rules like `Sum -> Product`)
    Forward(AstNodeId),
}
```

This avoids duplicating nodes in the Vec for pass-through grammar rules.

### Putting It Together

The key design insights:

1. **`AstNodeType` for precedence**: The grammar uses types like `NODE_VALUE`, `NODE_PRODUCT`, `NODE_SUM` to encode precedence, but your actual AST is simple (just `Number` and `BinOp` in this example).

2. **Parser tracks types internally**: When a reduction fires, the parser knows which `AstNodeType` it produced (from the grammar rule's left-hand side).
You never need to store or compute this in your AST.

3. **`ReductionResult` enables pass-through**: Rules like `Sum -> Product` just forward the existing node instead of cloning it, keeping the Vec compact.

4. **Simple AST, complex grammar**: Control precedence and parsing behavior through grammar structure, while keeping your AST focused on semantics.

### Index-Based AST Structure

When the parser processes input, it:
1. Takes a slice of tokens as input
2. Returns a `Vec` of AST nodes
3. The last element in the Vec is the root/outermost node
4. Child nodes appear earlier in the Vec

AST nodes reference their children using **`AstNodeId`** (index into the AST Vec) and can optionally reference **`TokenId`** (index into the token slice).

## Usage

### 1. Define Your Token and AST Node Types

**Tokens** need `HasTokenType` implemented.

```rust
use shiftkit::{TokenType, HasTokenType, AstNodeId};

// Token type IDs (for grammar definition)
const TOKEN_NUMBER: TokenType = TokenType(0);
const TOKEN_PLUS: TokenType = TokenType(1);
const TOKEN_MINUS: TokenType = TokenType(2);
const TOKEN_STAR: TokenType = TokenType(3);
const TOKEN_SLASH: TokenType = TokenType(4);
const TOKEN_LPAREN: TokenType = TokenType(5);
const TOKEN_RPAREN: TokenType = TokenType(6);

// Your custom token type
#[derive(Debug, Clone)]
enum Token {
    Number(i64),
    Plus,
    Minus,
    Star,
    Slash,
    LParen,
    RParen,
}

impl HasTokenType for Token {
    fn token_type(&self) -> TokenType {
        match self {
            Self::Number(_) => TOKEN_NUMBER,
            Self::Plus => TOKEN_PLUS,
            Self::Minus => TOKEN_MINUS,
            Self::Star => TOKEN_STAR,
            Self::Slash => TOKEN_SLASH,
            Self::LParen => TOKEN_LPAREN,
            Self::RParen => TOKEN_RPAREN,
        }
    }
}

// Your custom AST node types
#[derive(Debug, Clone)]
enum BinOpType {
    Add,
    Sub,
    Mul,
    Div,
}

#[derive(Debug, Clone)]
enum AstNode {
    Number(i64),
    BinOp(AstNodeId, BinOpType, AstNodeId),
}
```

### 2. Define Production Rules

Control precedence through grammar structure, not AST structure:

```rust
use shiftkit::{Grammar, AstNodeType, ReductionResult, Index};

// AST node types (for grammar only - not stored in actual AST!)
const NODE_VALUE: AstNodeType = AstNodeType(0);    // Atoms: numbers, parenthesized exprs
const NODE_PRODUCT: AstNodeType = AstNodeType(1);  // *, / (higher precedence)
const NODE_SUM: AstNodeType = AstNodeType(2);      // +, - (lower precedence)

let mut grammar = Grammar::new();

// Value -> NUMBER
grammar.add_rule(
    NODE_VALUE,
    &[TOKEN_NUMBER.into()],
    |indices: &[Index], tokens: &[Token], nodes: &[AstNode]| {
        let tok_id = indices[0].as_token_id();
        let Token::Number(num) = tokens[tok_id] else { unreachable!() };
        ReductionResult::NewNode(AstNode::Number(num))
    }
);

// Value -> ( Sum )
grammar.add_rule(
    NODE_VALUE,
    &[TOKEN_LPAREN.into(), NODE_SUM.into(), TOKEN_RPAREN.into()],
    |indices: &[Index], tokens: &[Token], nodes: &[AstNode]| {
        // Just forward the inner expression - don't duplicate it!
        ReductionResult::Forward(indices[1].as_ast_node_id())
    }
);

// Product -> Value (pass-through)
grammar.add_rule(
    NODE_PRODUCT,
    &[NODE_VALUE.into()],
    |indices: &[Index], tokens: &[Token], nodes: &[AstNode]| {
        ReductionResult::Forward(indices[0].as_ast_node_id())
    }
);

// Product -> Product * Value
grammar.add_rule(
    NODE_PRODUCT,
    &[NODE_PRODUCT.into(), TOKEN_STAR.into(), NODE_VALUE.into()],
    |indices: &[Index], tokens: &[Token], nodes: &[AstNode]| {
        let lhs = indices[0].as_ast_node_id();
        let rhs = indices[2].as_ast_node_id();
        ReductionResult::NewNode(AstNode::BinOp(lhs, BinOpType::Mul, rhs))
    }
);

// Sum -> Product (pass-through)
grammar.add_rule(
    NODE_SUM,
    &[NODE_PRODUCT.into()],
    |indices: &[Index], tokens: &[Token], nodes: &[AstNode]| {
        ReductionResult::Forward(indices[0].as_ast_node_id())
    }
);

// Sum -> Sum + Product
grammar.add_rule(
    NODE_SUM,
    &[NODE_SUM.into(), TOKEN_PLUS.into(), NODE_PRODUCT.into()],
    |indices: &[Index], tokens: &[Token], nodes: &[AstNode]| {
        let lhs = indices[0].as_ast_node_id();
        let rhs = indices[2].as_ast_node_id();
        ReductionResult::NewNode(AstNode::BinOp(lhs, BinOpType::Add, rhs))
    }
);
```

**Key points:**
- `AstNodeType` variants (`NODE_VALUE`, `NODE_PRODUCT`, `NODE_SUM`) encode precedence in the grammar
- Your actual `AstNode` enum is simple - just `Number` and `BinOp`
- Use `ReductionResult::Forward()` for pass-through rules to avoid duplicating nodes
- Use `ReductionResult::NewNode()` to create new AST nodes

### 3. Parse Input

Build the parser from your grammar and use it to parse token slices:

```rust
use shiftkit::Parser;

// Build the LALR(1) parser from the grammar
let parser: Parser<Token, AstNode> = Parser::from_grammar(grammar)?;

// Parse your input tokens
let tokens = tokenize("1 + 2 * 3");
let ast_nodes = parser.parse(&tokens)?;

// The root node is at the end of the Vec
let root_id = ast_nodes.len() - 1;

// Traverse the AST using indices
fn evaluate(node_id: AstNodeId, nodes: &[AstNode]) -> i64 {
    match &nodes[node_id] {
        AstNode::Number(n) => *n,
        AstNode::BinOp(lhs, op, rhs) => {
            let left = evaluate(*lhs, nodes);
            let right = evaluate(*rhs, nodes);
            match op {
                BinOpType::Add => left + right,
                BinOpType::Sub => left - right,
                BinOpType::Mul => left * right,
                BinOpType::Div => left / right,
            }
        }
    }
}

let result = evaluate(root_id, &ast_nodes);
```

The parser is generic over **tokens** (requiring `HasTokenType`) and **any AST node type**:

```rust
pub struct Parser<T: HasTokenType, A> {
    // ... parsing tables
}

impl<T: HasTokenType, A> Parser<T, A> {
    pub fn parse(&self, tokens: &[T]) -> Result<Vec<A>, ParseError> {
        // Uses `token.token_type()` for parsing decisions
        // Tracks `AstNodeType` internally based on which grammar rules fire
    }
}
```

## Benefits

### Memory Efficiency
- No `Box` allocations for each node
- Contiguous memory layout improves cache performance
- Smaller memory footprint for large ASTs

### Simplicity
- No lifetime management for AST references
- Easy to implement `Copy` semantics for indices
- Straightforward serialization (just write the Vec)

### Flexibility
- Easy to implement multiple passes over the AST
- Can maintain separate metadata vectors indexed by node ID
- Simple to implement AST transformations (just modify the Vec)

### Debugging
- Print the entire AST as a simple Vec
- Node indices provide stable identifiers across transformations
- Easy to visualize the parsing order (nodes are added in reduction order)

## Example: Complete Calculator Grammar

A full example showing precedence control with a simple AST:

```rust
use shiftkit::{Grammar, TokenType, AstNodeType, ReductionResult, Index, AstNodeId};

// Token type IDs (for grammar)
const TOKEN_NUMBER: TokenType = TokenType(0);
const TOKEN_PLUS: TokenType = TokenType(1);
const TOKEN_MINUS: TokenType = TokenType(2);
const TOKEN_STAR: TokenType = TokenType(3);
const TOKEN_SLASH: TokenType = TokenType(4);
const TOKEN_LPAREN: TokenType = TokenType(5);
const TOKEN_RPAREN: TokenType = TokenType(6);

// AST node type IDs (for grammar only - control precedence)
const NODE_VALUE: AstNodeType = AstNodeType(0);    // Atoms
const NODE_PRODUCT: AstNodeType = AstNodeType(1);  // *, /
const NODE_SUM: AstNodeType = AstNodeType(2);      // +, -

// Your actual AST types (no precedence info needed!)
#[derive(Debug, Clone)]
enum BinOpType { Add, Sub, Mul, Div }

#[derive(Debug, Clone)]
enum AstNode {
    Number(i64),
    BinOp(AstNodeId, BinOpType, AstNodeId),
}

let mut grammar = Grammar::new();

// Value -> NUMBER
grammar.add_rule(NODE_VALUE, &[TOKEN_NUMBER.into()],
    |indices, tokens, nodes| {
        let Token::Number(n) = tokens[indices[0].as_token_id()] else { unreachable!() };
        ReductionResult::NewNode(AstNode::Number(n))
    }
);

// Value -> ( Sum )
grammar.add_rule(NODE_VALUE,
    &[TOKEN_LPAREN.into(), NODE_SUM.into(), TOKEN_RPAREN.into()],
    |indices, tokens, nodes| {
        ReductionResult::Forward(indices[1].as_ast_node_id())
    }
);

// Product -> Value
grammar.add_rule(NODE_PRODUCT, &[NODE_VALUE.into()],
    |indices, tokens, nodes| {
        ReductionResult::Forward(indices[0].as_ast_node_id())
    }
);

// Product -> Product * Value
grammar.add_rule(NODE_PRODUCT,
    &[NODE_PRODUCT.into(), TOKEN_STAR.into(), NODE_VALUE.into()],
    |indices, tokens, nodes| {
        ReductionResult::NewNode(AstNode::BinOp(
            indices[0].as_ast_node_id(),
            BinOpType::Mul,
            indices[2].as_ast_node_id()
        ))
    }
);

// Product -> Product / Value
grammar.add_rule(NODE_PRODUCT,
    &[NODE_PRODUCT.into(), TOKEN_SLASH.into(), NODE_VALUE.into()],
    |indices, tokens, nodes| {
        ReductionResult::NewNode(AstNode::BinOp(
            indices[0].as_ast_node_id(),
            BinOpType::Div,
            indices[2].as_ast_node_id()
        ))
    }
);

// Sum -> Product
grammar.add_rule(NODE_SUM, &[NODE_PRODUCT.into()],
    |indices, tokens, nodes| {
        ReductionResult::Forward(indices[0].as_ast_node_id())
    }
);

// Sum -> Sum + Product
grammar.add_rule(NODE_SUM,
    &[NODE_SUM.into(), TOKEN_PLUS.into(), NODE_PRODUCT.into()],
    |indices, tokens, nodes| {
        ReductionResult::NewNode(AstNode::BinOp(
            indices[0].as_ast_node_id(),
            BinOpType::Add,
            indices[2].as_ast_node_id()
        ))
    }
);

// Sum -> Sum - Product
grammar.add_rule(NODE_SUM,
    &[NODE_SUM.into(), TOKEN_MINUS.into(), NODE_PRODUCT.into()],
    |indices, tokens, nodes| {
        ReductionResult::NewNode(AstNode::BinOp(
            indices[0].as_ast_node_id(),
            BinOpType::Sub,
            indices[2].as_ast_node_id()
        ))
    }
);
```

**Result:** Full precedence control (parentheses, `*`/`/`, `+`/`-`) with a simple two-variant AST!

## License

MIT