oak-rust 0.0.11

High-performance incremental Rust parser for the oak ecosystem with flexible configuration, emphasizing memory safety and zero-cost abstractions.
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
429
430
431
432
433
434
435
436
437
438
439
440
use crate::{RustLanguage, lexer::RustLexer};
use oak_core::{
    GreenNode, OakError, TokenType,
    parser::{Associativity, ParseCache, ParseOutput, Parser, ParserState, Pratt, PrattParser, binary, parse_with_lexer, unary},
    source::{Source, TextEdit},
};

/// Rust element type definitions.
pub mod element_type;
pub use self::element_type::RustElementType;

/// A parser for the Rust programming language.
#[derive(Clone)]
pub struct RustParser<'config> {
    /// Reference to the Rust language configuration
    #[allow(dead_code)]
    config: &'config RustLanguage,
}

impl<'config> RustParser<'config> {
    /// Creates a new Rust parser with the given language configuration.
    pub fn new(config: &'config RustLanguage) -> Self {
        Self { config }
    }
}

impl<'config> Pratt<RustLanguage> for RustParser<'config> {
    fn primary<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> &'a GreenNode<'a, RustLanguage> {
        let cp = state.checkpoint();
        match state.peek_kind() {
            Some(crate::lexer::RustTokenType::Identifier) => {
                state.bump();
                state.finish_at(cp, crate::parser::element_type::RustElementType::IdentifierExpression)
            }
            Some(k) if k.is_literal() => {
                state.bump();
                state.finish_at(cp, crate::parser::element_type::RustElementType::LiteralExpression)
            }
            Some(crate::lexer::RustTokenType::LeftParen) => {
                state.bump();
                PrattParser::parse(state, 0, self);
                state.expect(crate::lexer::RustTokenType::RightParen).ok();
                state.finish_at(cp, crate::parser::element_type::RustElementType::ParenthesizedExpression)
            }
            _ => {
                state.bump();
                state.finish_at(cp, crate::parser::element_type::RustElementType::Error)
            }
        }
    }

    fn prefix<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> &'a GreenNode<'a, RustLanguage> {
        use crate::{lexer::RustTokenType::*, parser::RustElementType as RE};
        let kind = match state.peek_kind() {
            Some(k) => k,
            None => return self.primary(state),
        };

        match kind {
            Minus | Bang | Ampersand | Star => unary(state, kind, 13, RE::UnaryExpression.into(), |s, p| PrattParser::parse(s, p, self)),
            _ => self.primary(state),
        }
    }

    fn infix<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>, left: &'a GreenNode<'a, RustLanguage>, min_precedence: u8) -> Option<&'a GreenNode<'a, RustLanguage>> {
        use crate::{lexer::RustTokenType::*, parser::RustElementType as RE};
        let kind = state.peek_kind()?;

        let (prec, assoc) = match kind {
            Eq | PlusEq | MinusEq | StarEq | SlashEq | PercentEq | AndEq | OrEq | CaretEq | ShlEq | ShrEq => (1, Associativity::Right),
            DotDot | DotDotEq => (2, Associativity::Left),
            OrOr => (3, Associativity::Left),
            AndAnd => (4, Associativity::Left),
            EqEq | Ne => (5, Associativity::Left),
            Lt | Le | Gt | Ge => (6, Associativity::Left),
            Pipe => (7, Associativity::Left),
            Caret => (8, Associativity::Left),
            Ampersand => (9, Associativity::Left),
            Shl | Shr => (10, Associativity::Left),
            Plus | Minus => (11, Associativity::Left),
            Star | Slash | Percent => (12, Associativity::Left),
            LeftParen | LeftBracket | Dot => (14, Associativity::Left),
            _ => return None,
        };

        if prec < min_precedence {
            return None;
        }

        match kind {
            LeftParen => {
                let cp = state.checkpoint();
                state.push_child(left);
                state.expect(LeftParen).ok();
                if !state.at(RightParen) {
                    loop {
                        PrattParser::parse(state, 0, self);
                        if !state.eat(Comma) {
                            break;
                        }
                    }
                }
                state.expect(RightParen).ok();
                Some(state.finish_at(cp, RE::CallExpression))
            }
            LeftBracket => {
                let cp = state.checkpoint();
                state.push_child(left);
                state.expect(LeftBracket).ok();
                PrattParser::parse(state, 0, self);
                state.expect(RightBracket).ok();
                Some(state.finish_at(cp, RE::IndexExpression))
            }
            Dot => {
                let cp = state.checkpoint();
                state.push_child(left);
                state.expect(Dot).ok();
                state.expect(Identifier).ok();
                Some(state.finish_at(cp, RE::MemberExpression))
            }
            _ => Some(binary(state, left, kind, prec, assoc, RE::BinaryExpression.into(), |s, p| PrattParser::parse(s, p, self))),
        }
    }
}

impl<'config> Parser<RustLanguage> for RustParser<'config> {
    fn parse<'a, S: Source + ?Sized>(&self, text: &'a S, edits: &[TextEdit], cache: &'a mut impl ParseCache<RustLanguage>) -> ParseOutput<'a, RustLanguage> {
        let lexer = RustLexer::new(self.config);
        parse_with_lexer(&lexer, text, edits, cache, |state| {
            let cp = state.checkpoint();
            while state.not_at_end() {
                if state.current().map(|t| t.kind.is_ignored()).unwrap_or(false) {
                    state.advance();
                    continue;
                }
                self.parse_statement(state)?
            }
            let root = state.finish_at(cp, crate::parser::element_type::RustElementType::SourceFile);
            Ok(root)
        })
    }
}

impl<'config> RustParser<'config> {
    /// Parses a single Rust statement or item.
    ///
    /// This method identifies the type of statement or item at the current position
    /// and dispatches to the appropriate parsing method. If no specific statement
    /// type is recognized, it parses an expression followed by a semicolon.
    ///
    /// # Arguments
    /// * `state` - The current parser state
    ///
    /// # Returns
    /// * `Result<(), OakError>` - Ok if parsing succeeds, Err otherwise
    fn parse_statement<'a, S: Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        use crate::{lexer::RustTokenType, parser::RustElementType::*};

        let kind = match state.peek_kind() {
            Some(RustTokenType::Fn) => Some(Function),
            Some(RustTokenType::Use) => Some(UseItem),
            Some(RustTokenType::Mod) => Some(ModuleItem),
            Some(RustTokenType::Struct) => Some(StructItem),
            Some(RustTokenType::Enum) => Some(EnumItem),
            Some(RustTokenType::Let) => Some(LetStatement),
            Some(RustTokenType::If) => Some(IfExpression),
            Some(RustTokenType::While) => Some(WhileExpression),
            Some(RustTokenType::Loop) => Some(LoopExpression),
            Some(RustTokenType::For) => Some(ForExpression),
            Some(RustTokenType::Return) => Some(ReturnStatement),
            Some(RustTokenType::LeftBrace) => Some(Block),
            _ => None,
        };

        if let Some(k) = kind {
            state.incremental_node(k.into(), |state| match k {
                Function => self.parse_function_body(state),
                UseItem => self.parse_use_item_body(state),
                ModuleItem => self.parse_mod_item_body(state),
                StructItem => self.parse_struct_item_body(state),
                EnumItem => self.parse_enum_item_body(state),
                LetStatement => self.parse_let_statement_body(state),
                IfExpression => self.parse_if_expression_body(state),
                WhileExpression => self.parse_while_expression_body(state),
                LoopExpression => self.parse_loop_expression_body(state),
                ForExpression => self.parse_for_expression_body(state),
                ReturnStatement => self.parse_return_statement_body(state),
                Block => self.parse_block_body(state),
                _ => unreachable!(),
            })
        }
        else {
            PrattParser::parse(state, 0, self);
            state.eat(RustTokenType::Semicolon);
            Ok(())
        }
    }

    fn parse_function_body<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        self.parse_function(state)
    }

    fn parse_use_item_body<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        self.parse_use_item(state)
    }

    fn parse_mod_item_body<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        self.parse_mod_item(state)
    }

    fn parse_struct_item_body<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        self.parse_struct_item(state)
    }

    fn parse_enum_item_body<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        self.parse_enum_item(state)
    }

    fn parse_let_statement_body<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        self.parse_let_statement(state)
    }

    fn parse_if_expression_body<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        self.parse_if_expression(state)
    }

    fn parse_while_expression_body<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        self.parse_while_expression(state)
    }

    fn parse_loop_expression_body<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        self.parse_loop_expression(state)
    }

    fn parse_for_expression_body<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        self.parse_for_expression(state)
    }

    fn parse_return_statement_body<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        self.parse_return_statement(state)
    }

    fn parse_block_body<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        self.parse_block(state)
    }

    /// Parses a function definition.
    ///
    /// This method parses a complete Rust function definition, including the function
    /// keyword, name, parameters, return type (if specified), and body.
    ///
    /// # Arguments
    /// * `state` - The current parser state
    ///
    /// # Returns
    /// * `Result<(), OakError>` - Ok if parsing succeeds, Err otherwise
    fn parse_function<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        use crate::lexer::RustTokenType;
        let cp = state.checkpoint();
        state.expect(RustTokenType::Fn).ok();
        state.expect(RustTokenType::Identifier).ok();
        self.parse_param_list(state)?;
        if state.eat(RustTokenType::Arrow) {
            while state.not_at_end() && !state.at(RustTokenType::LeftBrace) {
                state.advance()
            }
        }
        self.parse_block(state)?;
        state.finish_at(cp, crate::parser::element_type::RustElementType::Function);
        Ok(())
    }

    /// Parses a function parameter list.
    ///
    /// This method parses the parameters of a function definition, enclosed in parentheses.
    ///
    /// # Arguments
    /// * `state` - The current parser state
    ///
    /// # Returns
    /// * `Result<(), OakError>` - Ok if parsing succeeds, Err otherwise
    fn parse_param_list<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        use crate::lexer::RustTokenType::*;
        let cp = state.checkpoint();
        state.expect(LeftParen).ok();
        while state.not_at_end() && !state.at(RightParen) {
            state.advance()
        }
        state.expect(RightParen).ok();
        state.finish_at(cp, crate::parser::element_type::RustElementType::ParameterList);
        Ok(())
    }

    /// Parses a block of statements enclosed in braces.
    ///
    /// This method parses a block of code enclosed in curly braces, which can contain
    /// multiple statements and nested blocks.
    ///
    /// # Arguments
    /// * `state` - The current parser state
    ///
    /// # Returns
    /// * `Result<(), OakError>` - Ok if parsing succeeds, Err otherwise
    fn parse_block<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        use crate::lexer::RustTokenType::*;
        let cp = state.checkpoint();
        state.expect(LeftBrace).ok();
        while state.not_at_end() && !state.at(RightBrace) {
            self.parse_statement(state)?
        }
        state.expect(RightBrace).ok();
        state.finish_at(cp, crate::parser::element_type::RustElementType::BlockExpression);
        Ok(())
    }

    /// Parses a `use` declaration.
    fn parse_use_item<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        let cp = state.checkpoint();
        state.expect(crate::lexer::RustTokenType::Use).ok();
        // Simplified path handling
        while !state.at(crate::lexer::RustTokenType::Semicolon) && state.not_at_end() {
            state.bump()
        }
        state.eat(crate::lexer::RustTokenType::Semicolon);
        state.finish_at(cp, crate::parser::element_type::RustElementType::UseItem);
        Ok(())
    }

    /// Parses a module declaration.
    fn parse_mod_item<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        let cp = state.checkpoint();
        state.bump(); // mod
        state.expect(crate::lexer::RustTokenType::Identifier).ok();
        if state.at(crate::lexer::RustTokenType::LeftBrace) {
            self.parse_block(state)?
        }
        else {
            state.eat(crate::lexer::RustTokenType::Semicolon);
        }
        state.finish_at(cp, crate::parser::element_type::RustElementType::ModuleItem);
        Ok(())
    }

    /// Parses a struct definition.
    fn parse_struct_item<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        let cp = state.checkpoint();
        state.bump(); // struct
        state.expect(crate::lexer::RustTokenType::Identifier).ok();
        while state.not_at_end() && !state.at(crate::lexer::RustTokenType::LeftBrace) && !state.at(crate::lexer::RustTokenType::Semicolon) {
            state.advance()
        }
        if state.at(crate::lexer::RustTokenType::LeftBrace) {
            self.parse_block(state)?
        }
        else {
            state.eat(crate::lexer::RustTokenType::Semicolon);
        }
        state.finish_at(cp, crate::parser::element_type::RustElementType::StructItem);
        Ok(())
    }

    /// Parses an enum definition.
    fn parse_enum_item<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        let cp = state.checkpoint();
        state.bump(); // enum
        state.expect(crate::lexer::RustTokenType::Identifier).ok();
        self.parse_block(state)?;
        state.finish_at(cp, crate::parser::element_type::RustElementType::EnumItem);
        Ok(())
    }

    /// Parses a `let` statement.
    fn parse_let_statement<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        let cp = state.checkpoint();
        state.bump(); // let
        state.expect(crate::lexer::RustTokenType::Identifier).ok();
        if state.eat(crate::lexer::RustTokenType::Eq) {
            PrattParser::parse(state, 0, self);
        }
        state.eat(crate::lexer::RustTokenType::Semicolon);
        state.finish_at(cp, crate::parser::element_type::RustElementType::LetStatement);
        Ok(())
    }

    /// Parses an `if` expression.
    fn parse_if_expression<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        let cp = state.checkpoint();
        state.bump(); // if
        PrattParser::parse(state, 0, self);
        self.parse_block(state)?;
        if state.eat(crate::lexer::RustTokenType::Else) {
            if state.at(crate::lexer::RustTokenType::If) { self.parse_if_expression(state)? } else { self.parse_block(state)? }
        }
        state.finish_at(cp, crate::parser::element_type::RustElementType::IfExpression);
        Ok(())
    }

    /// Parses a `while` loop.
    fn parse_while_expression<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        let cp = state.checkpoint();
        state.bump(); // while
        PrattParser::parse(state, 0, self);
        self.parse_block(state)?;
        state.finish_at(cp, crate::parser::element_type::RustElementType::WhileExpression);
        Ok(())
    }

    /// Parses a `loop` expression.
    fn parse_loop_expression<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        let cp = state.checkpoint();
        state.bump(); // loop
        self.parse_block(state)?;
        state.finish_at(cp, crate::parser::element_type::RustElementType::LoopExpression);
        Ok(())
    }

    /// Parses a `for` loop.
    fn parse_for_expression<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        let cp = state.checkpoint();
        state.bump(); // for
        state.expect(crate::lexer::RustTokenType::Identifier).ok();
        state.expect(crate::lexer::RustTokenType::In).ok();
        PrattParser::parse(state, 0, self);
        self.parse_block(state)?;
        state.finish_at(cp, crate::parser::element_type::RustElementType::ForExpression);
        Ok(())
    }

    /// Parses a `return` statement.
    fn parse_return_statement<'a, S: oak_core::source::Source + ?Sized>(&self, state: &mut ParserState<'a, RustLanguage, S>) -> Result<(), OakError> {
        let cp = state.checkpoint();
        state.bump(); // return
        if !state.at(crate::lexer::RustTokenType::Semicolon) {
            PrattParser::parse(state, 0, self);
        }
        state.eat(crate::lexer::RustTokenType::Semicolon);
        state.finish_at(cp, crate::parser::element_type::RustElementType::ReturnStatement);
        Ok(())
    }
}