cairo_lang_parser/
parser.rs

1use std::mem;
2use std::sync::Arc;
3
4use cairo_lang_diagnostics::DiagnosticsBuilder;
5use cairo_lang_filesystem::db::FilesGroup;
6use cairo_lang_filesystem::ids::{FileId, SmolStrId};
7use cairo_lang_filesystem::span::{TextOffset, TextSpan, TextWidth};
8use cairo_lang_primitive_token::{PrimitiveToken, ToPrimitiveTokenStream};
9use cairo_lang_syntax as syntax;
10use cairo_lang_syntax::node::ast::*;
11use cairo_lang_syntax::node::helpers::GetIdentifier;
12use cairo_lang_syntax::node::kind::SyntaxKind;
13use cairo_lang_syntax::node::{SyntaxNode, Token, TypedSyntaxNode};
14use cairo_lang_utils::deque::Deque;
15use cairo_lang_utils::{extract_matches, require};
16use salsa::Database;
17use syntax::node::green::{GreenNode, GreenNodeDetails};
18use syntax::node::ids::GreenId;
19
20use crate::ParserDiagnostic;
21use crate::diagnostic::ParserDiagnosticKind;
22use crate::lexer::{LexerTerminal, tokenize_all};
23use crate::operators::{get_post_operator_precedence, get_unary_operator_precedence};
24use crate::recovery::is_of_kind;
25use crate::utils::primitive_token_stream_content_and_offset;
26use crate::validation::{
27    ValidationError, ValidationLocation, validate_literal_number, validate_short_string,
28    validate_string,
29};
30
31#[cfg(test)]
32#[path = "parser_test.rs"]
33mod test;
34
35#[derive(PartialEq)]
36enum MacroParsingContext {
37    /// The code being parsed is a part of a macro rule.
38    MacroRule,
39    /// The code being parsed is a part of a macro expansion.
40    MacroExpansion,
41    /// The code being parsed was generated by a macro expansion.
42    ExpandedMacro,
43    /// None of the above.
44    None,
45}
46
47pub struct Parser<'a, 'mt> {
48    db: &'a dyn Database,
49    file_id: FileId<'a>,
50    /// A queue of lexed tokens to be parsed.
51    terminals: Deque<LexerTerminal<'a>>,
52    /// A vector of pending trivia to be added as leading trivia to the next valid terminal.
53    pending_trivia: Vec<TriviumGreen<'a>>,
54    /// The current offset, excluding the current terminal.
55    offset: TextOffset,
56    /// The width of the current terminal being handled (excluding the trivia length of this
57    /// terminal).
58    current_width: TextWidth,
59    /// The length of the trailing trivia following the last read token.
60    last_trivia_length: TextWidth,
61    diagnostics: &'mt mut DiagnosticsBuilder<'a, ParserDiagnostic<'a>>,
62    /// An accumulating vector of pending skipped tokens diagnostics.
63    pending_skipped_token_diagnostics: Vec<PendingParserDiagnostic>,
64    /// An indicator if we are inside a macro rule expansion.
65    macro_parsing_context: MacroParsingContext,
66}
67
68impl<'a> Parser<'a, '_> {
69    fn next_terminal(&self) -> &LexerTerminal<'a> {
70        &self.terminals[0]
71    }
72
73    fn next_next_terminal(&self) -> &LexerTerminal<'a> {
74        &self.terminals[1]
75    }
76
77    fn advance(&mut self) -> LexerTerminal<'a> {
78        self.terminals.pop_front().unwrap()
79    }
80
81    fn next_terminal_mut(&mut self) -> &mut LexerTerminal<'a> {
82        &mut self.terminals[0]
83    }
84}
85
86/// The possible results of a try_parse_* function failing to parse.
87#[derive(PartialEq, Debug)]
88pub enum TryParseFailure {
89    /// The parsing failed, and no token was consumed, the current token is the token which caused
90    /// the failure and thus should be skipped by the caller.
91    SkipToken,
92    /// The parsing failed, some tokens were consumed, and the current token is yet to be
93    /// processed. Should be used when the failure cannot be
94    /// determined by the first token alone, and thus the tokens until the token which
95    /// determines the failure should be consumed.
96    DoNothing,
97}
98/// The result of a try_parse_* functions.
99pub type TryParseResult<GreenElement> = Result<GreenElement, TryParseFailure>;
100
101// ====================================== Naming of items ======================================
102// To avoid confusion, there is a naming convention for the language items.
103// An item is called <item_scope>Item<item_kind>, where item_scope is in {Module, Trait, Impl}, and
104// item_kind is in {Const, Enum, ExternFunction, ExternType, Function, Impl, InlineMacro, Module,
105// Struct, Trait, Type, TypeAlias, Use} (note not all combinations are supported).
106// For example, ModuleItemFunction is a function item in a module, TraitItemConst is a const item in
107// a trait.
108
109// ================================ Naming of parsing functions ================================
110// try_parse_<something>: returns a TryParseElementResult. A `Ok` with green ID with a kind
111// that represents 'something' or a `Err` if 'something' can't be parsed.
112// If the error kind is Failure, the current token is not consumed, otherwise (Success or
113// error of kind FailureAndSkipped) it is (taken or skipped). Used when something may or may not be
114// there and we can act differently according to each case.
115//
116// parse_option_<something>: returns a green ID with a kind that represents 'something'. If
117// 'something' can't be parsed, returns a green ID with the relevant empty kind. Used for an
118// optional child. Always returns some green ID.
119//
120// parse_<something>: returns a green ID with a kind that represents 'something'. If
121// 'something' can't be parsed, returns a green ID with the relevant missing kind. Used when we
122// expect 'something' to be there. Always returns some green ID.
123//
124// expect_<something>: similar to parse_<something>, but assumes the current token is as expected.
125// Therefore, it always returns a GreenId of a node with a kind that represents 'something' and
126// never a missing kind.
127// Should only be called after checking the current token.
128
129const MAX_PRECEDENCE: usize = 1000;
130const MODULE_ITEM_DESCRIPTION: &str = "Const/Enum/ExternFunction/ExternType/Function/Impl/\
131                                       InlineMacro/Module/Struct/Trait/TypeAlias/Use";
132const TRAIT_ITEM_DESCRIPTION: &str = "Const/Function/Impl/Type";
133const IMPL_ITEM_DESCRIPTION: &str = "Const/Function/Impl/Type";
134
135// A macro adding "or an attribute" to the end of a string.
136macro_rules! or_an_attribute {
137    ($string:expr) => {
138        format!("{} or an attribute", $string)
139    };
140}
141
142impl<'a, 'mt> Parser<'a, 'mt> {
143    /// Creates a new parser.
144    pub fn new(
145        db: &'a dyn Database,
146        file_id: FileId<'a>,
147        text: &'a str,
148        diagnostics: &'mt mut DiagnosticsBuilder<'a, ParserDiagnostic<'a>>,
149    ) -> Self {
150        let tokens: Deque<LexerTerminal<'a>> = tokenize_all(db, (), Arc::from(text));
151        Parser {
152            db,
153            file_id,
154            terminals: tokens,
155            pending_trivia: Vec::new(),
156            offset: Default::default(),
157            current_width: Default::default(),
158            last_trivia_length: Default::default(),
159            diagnostics,
160            pending_skipped_token_diagnostics: Vec::new(),
161            macro_parsing_context: MacroParsingContext::None,
162        }
163    }
164
165    /// Adds a diagnostic to the parser diagnostics collection.
166    pub fn add_diagnostic(&mut self, kind: ParserDiagnosticKind, span: TextSpan) {
167        self.diagnostics.add(ParserDiagnostic { file_id: self.file_id, kind, span });
168    }
169
170    /// Parses a file.
171    pub fn parse_file(
172        db: &'a dyn Database,
173        diagnostics: &'mt mut DiagnosticsBuilder<'a, ParserDiagnostic<'a>>,
174        file_id: FileId<'a>,
175        text: &'a str,
176    ) -> SyntaxFile<'a> {
177        let parser = Parser::new(db, file_id, text, diagnostics);
178        let green = parser.parse_syntax_file();
179        SyntaxFile::from_syntax_node(db, SyntaxNode::new_root(db, file_id, green.0))
180    }
181
182    /// Parses a file expr.
183    pub fn parse_file_expr(
184        db: &'a dyn Database,
185        diagnostics: &'mt mut DiagnosticsBuilder<'a, ParserDiagnostic<'a>>,
186        file_id: FileId<'a>,
187        text: &'a str,
188    ) -> Expr<'a> {
189        let mut parser = Parser::new(db, file_id, text, diagnostics);
190        parser.macro_parsing_context = MacroParsingContext::ExpandedMacro;
191        let green = parser.parse_expr();
192        if let Err(SkippedError(span)) = parser.skip_until(is_of_kind!()) {
193            parser.add_diagnostic(
194                ParserDiagnosticKind::SkippedElement { element_name: "end of expr".into() },
195                span,
196            );
197        }
198        Expr::from_syntax_node(db, SyntaxNode::new_root(db, file_id, green.0))
199    }
200
201    /// Parses a file as a list of statements.
202    pub fn parse_file_statement_list(
203        db: &'a dyn Database,
204        diagnostics: &'mt mut DiagnosticsBuilder<'a, ParserDiagnostic<'a>>,
205        file_id: FileId<'a>,
206        text: &'a str,
207    ) -> StatementList<'a> {
208        let mut parser = Parser::new(db, file_id, text, diagnostics);
209        parser.macro_parsing_context = MacroParsingContext::ExpandedMacro;
210        let statements = StatementList::new_green(
211            db,
212            &parser.parse_list(Self::try_parse_statement, Self::is_eof, "statement"),
213        );
214        StatementList::from_syntax_node(db, SyntaxNode::new_root(db, file_id, statements.0))
215    }
216
217    /// Checks if the given kind is an end of file token.
218    pub fn is_eof(kind: SyntaxKind) -> bool {
219        kind == SyntaxKind::TerminalEndOfFile
220    }
221
222    /// Parses a token stream.
223    pub fn parse_token_stream(
224        db: &'a dyn Database,
225        diagnostics: &'mt mut DiagnosticsBuilder<'a, ParserDiagnostic<'a>>,
226        file_id: FileId<'a>,
227        token_stream: &dyn ToPrimitiveTokenStream<Iter = impl Iterator<Item = PrimitiveToken>>,
228    ) -> SyntaxFile<'a> {
229        let (content, offset) = primitive_token_stream_content_and_offset(token_stream);
230        let file_content = db.file_content(file_id).unwrap();
231        let file_content_at_offset = offset.unwrap_or_default().take_from(file_content);
232        assert!(
233            file_content_at_offset.starts_with(&content),
234            "The content of the file at the offset is not the same as the content of the token \
235             stream"
236        );
237        let content = &file_content_at_offset[..content.len()];
238        let parser = Parser::new(db, file_id, content, diagnostics);
239        let green = parser.parse_syntax_file();
240        SyntaxFile::from_syntax_node(
241            db,
242            SyntaxNode::new_root_with_offset(db, file_id, green.0, offset),
243        )
244    }
245
246    /// Parses a token stream expression.
247    pub fn parse_token_stream_expr(
248        db: &'a dyn Database,
249        diagnostics: &'mt mut DiagnosticsBuilder<'a, ParserDiagnostic<'a>>,
250        file_id: FileId<'a>,
251        offset: Option<TextOffset>,
252    ) -> Expr<'a> {
253        let content = db.file_content(file_id).unwrap();
254        let mut parser = Parser::new(db, file_id, content, diagnostics);
255        let green = parser.parse_expr();
256        if let Err(SkippedError(span)) = parser.skip_until(is_of_kind!()) {
257            parser.diagnostics.add(ParserDiagnostic {
258                file_id: parser.file_id,
259                kind: ParserDiagnosticKind::SkippedElement { element_name: "end of expr".into() },
260                span,
261            });
262        }
263        Expr::from_syntax_node(db, SyntaxNode::new_root_with_offset(db, file_id, green.0, offset))
264    }
265
266    /// Returns a GreenId of an ExprMissing and adds a diagnostic describing it.
267    fn create_and_report_missing<T: TypedSyntaxNode<'a>>(
268        &mut self,
269        missing_kind: ParserDiagnosticKind,
270    ) -> T::Green {
271        let next_offset = self.offset.add_width(self.current_width - self.last_trivia_length);
272        self.add_diagnostic(missing_kind, TextSpan::cursor(next_offset));
273        T::missing(self.db)
274    }
275
276    /// Returns the missing terminal and adds the corresponding missing token
277    /// diagnostic report.
278    fn create_and_report_missing_terminal<Terminal: syntax::node::Terminal<'a>>(
279        &mut self,
280    ) -> Terminal::Green {
281        self.create_and_report_missing::<Terminal>(ParserDiagnosticKind::MissingToken(
282            Terminal::KIND,
283        ))
284    }
285
286    pub fn parse_syntax_file(mut self) -> SyntaxFileGreen<'a> {
287        let mut module_items = vec![];
288        if let Some(doc_item) = self.take_doc() {
289            module_items.push(doc_item.into());
290        }
291        module_items.extend(self.parse_attributed_list(
292            Self::try_parse_module_item,
293            is_of_kind!(),
294            MODULE_ITEM_DESCRIPTION,
295        ));
296        // Create a new vec with the doc item as the children.
297        let items = ModuleItemList::new_green(self.db, &module_items);
298        // This will not panic since the above parsing only stops when reaches EOF.
299        assert_eq!(self.peek().kind, SyntaxKind::TerminalEndOfFile);
300
301        // Fix offset in case there are skipped tokens before EOF. This is usually done in
302        // self.take_raw() but here we don't call self.take_raw as it tries to read the next
303        // token, which doesn't exist.
304        self.offset = self.offset.add_width(self.current_width);
305
306        let eof =
307            self.add_trivia_to_terminal::<TerminalEndOfFile<'_>>(self.next_terminal().clone());
308        SyntaxFile::new_green(self.db, items, eof)
309    }
310
311    // ------------------------------- Module items -------------------------------
312
313    /// Returns a GreenId of a node with an Item.* kind (see [syntax::node::ast::ModuleItem]), or
314    /// TryParseFailure if a module item can't be parsed.
315    /// In case of an identifier not followed by a `!`, it is skipped inside the function and thus a
316    /// TryParseFailure::DoNothing is returned.
317    pub fn try_parse_module_item(&mut self) -> TryParseResult<ModuleItemGreen<'a>> {
318        let maybe_attributes = self.try_parse_attribute_list(MODULE_ITEM_DESCRIPTION);
319        let (has_attrs, attributes) = match maybe_attributes {
320            Ok(attributes) => (true, attributes),
321            Err(_) => (false, AttributeList::new_green(self.db, &[])),
322        };
323        let post_attributes_offset = self.offset.add_width(self.current_width);
324
325        let visibility_pub = self.try_parse_visibility_pub();
326        let visibility = match visibility_pub {
327            Some(visibility) => visibility.into(),
328            None => VisibilityDefault::new_green(self.db).into(),
329        };
330        let post_visibility_offset = self.offset.add_width(self.current_width);
331
332        match self.peek().kind {
333            SyntaxKind::TerminalConst => {
334                let const_kw = self.take::<TerminalConst<'_>>();
335                Ok(if self.peek().kind == SyntaxKind::TerminalFunction {
336                    self.expect_item_function_with_body(attributes, visibility, const_kw.into())
337                        .into()
338                } else {
339                    self.expect_item_const(attributes, visibility, const_kw).into()
340                })
341            }
342            SyntaxKind::TerminalModule => {
343                Ok(self.expect_item_module(attributes, visibility).into())
344            }
345            SyntaxKind::TerminalStruct => {
346                Ok(self.expect_item_struct(attributes, visibility).into())
347            }
348            SyntaxKind::TerminalEnum => Ok(self.expect_item_enum(attributes, visibility).into()),
349            SyntaxKind::TerminalType => {
350                Ok(self.expect_item_type_alias(attributes, visibility).into())
351            }
352            SyntaxKind::TerminalExtern => Ok(self.expect_item_extern(attributes, visibility)),
353            SyntaxKind::TerminalFunction => Ok(self
354                .expect_item_function_with_body(
355                    attributes,
356                    visibility,
357                    OptionTerminalConstEmpty::new_green(self.db).into(),
358                )
359                .into()),
360            SyntaxKind::TerminalUse => Ok(self.expect_item_use(attributes, visibility).into()),
361            SyntaxKind::TerminalTrait => Ok(self.expect_item_trait(attributes, visibility).into()),
362            SyntaxKind::TerminalImpl => Ok(self.expect_module_item_impl(attributes, visibility)),
363            SyntaxKind::TerminalMacro => {
364                Ok(self.expect_item_macro_declaration(attributes, visibility).into())
365            }
366            SyntaxKind::TerminalIdentifier | SyntaxKind::TerminalDollar => {
367                // We take the identifier to check if the next token is a `!`. If it is, we assume
368                // that a macro is following and handle it similarly to any other module item. If
369                // not we skip the identifier. 'take_raw' is used here since it is not yet known if
370                // the identifier would be taken as a part of a macro, or skipped.
371                let path = self.parse_path();
372                let post_path_offset = self.offset.add_width(self.current_width);
373                match self.peek().kind {
374                    SyntaxKind::TerminalLParen
375                    | SyntaxKind::TerminalLBrace
376                    | SyntaxKind::TerminalLBrack => {
377                        // This case is treated as an item inline macro with a missing bang ('!').
378                        self.add_diagnostic(
379                            ParserDiagnosticKind::ItemInlineMacroWithoutBang {
380                                identifier: path.identifier(self.db).long(self.db).to_string(),
381                                bracket_type: self.peek().kind,
382                            },
383                            TextSpan::new(self.offset, self.offset.add_width(self.current_width)),
384                        );
385                        Ok(self
386                            .parse_item_inline_macro_given_bang(
387                                attributes,
388                                path,
389                                TerminalNot::missing(self.db),
390                            )
391                            .into())
392                    }
393                    SyntaxKind::TerminalNot => {
394                        Ok(self.expect_item_inline_macro(attributes, path).into())
395                    }
396                    _ => {
397                        if has_attrs {
398                            self.skip_taken_node_with_offset(
399                                attributes,
400                                ParserDiagnosticKind::SkippedElement {
401                                    element_name: or_an_attribute!(MODULE_ITEM_DESCRIPTION),
402                                },
403                                post_attributes_offset,
404                            );
405                        }
406                        if let Some(visibility_pub) = visibility_pub {
407                            self.skip_taken_node_with_offset(
408                                visibility_pub,
409                                ParserDiagnosticKind::SkippedElement {
410                                    element_name: or_an_attribute!(MODULE_ITEM_DESCRIPTION),
411                                },
412                                post_visibility_offset,
413                            );
414                        }
415                        // TODO(Dean): This produce a slightly worse diagnostic than before.
416                        self.skip_taken_node_with_offset(
417                            path,
418                            ParserDiagnosticKind::SkippedElement {
419                                element_name: or_an_attribute!(MODULE_ITEM_DESCRIPTION),
420                            },
421                            post_path_offset,
422                        );
423                        // The token is already skipped, so it should not be skipped in the caller.
424                        Err(TryParseFailure::DoNothing)
425                    }
426                }
427            }
428            _ => {
429                let mut result = Err(TryParseFailure::SkipToken);
430                if has_attrs {
431                    self.skip_taken_node_with_offset(
432                        attributes,
433                        ParserDiagnosticKind::AttributesWithoutItem,
434                        post_attributes_offset,
435                    );
436                    result = Ok(ModuleItem::missing(self.db));
437                }
438                if let Some(visibility_pub) = visibility_pub {
439                    self.skip_taken_node_with_offset(
440                        visibility_pub,
441                        ParserDiagnosticKind::VisibilityWithoutItem,
442                        post_visibility_offset,
443                    );
444                    result = Ok(ModuleItem::missing(self.db));
445                }
446                result
447            }
448        }
449    }
450
451    /// Assumes the current token is Module.
452    /// Expected pattern: `mod <Identifier> \{<ItemList>\}` or `mod <Identifier>;`.
453    fn expect_item_module(
454        &mut self,
455        attributes: AttributeListGreen<'a>,
456        visibility: VisibilityGreen<'a>,
457    ) -> ItemModuleGreen<'a> {
458        let module_kw = self.take::<TerminalModule<'_>>();
459        let name = self.parse_identifier();
460
461        let body = match self.peek().kind {
462            SyntaxKind::TerminalLBrace => {
463                let lbrace = self.take::<TerminalLBrace<'_>>();
464                let mut module_items = vec![];
465                if let Some(doc_item) = self.take_doc() {
466                    module_items.push(doc_item.into());
467                }
468                module_items.extend(self.parse_attributed_list(
469                    Self::try_parse_module_item,
470                    is_of_kind!(rbrace),
471                    MODULE_ITEM_DESCRIPTION,
472                ));
473                let items = ModuleItemList::new_green(self.db, &module_items);
474                let rbrace = self.parse_token::<TerminalRBrace<'_>>();
475                ModuleBody::new_green(self.db, lbrace, items, rbrace).into()
476            }
477            SyntaxKind::TerminalSemicolon => self.take::<TerminalSemicolon<'_>>().into(),
478            _ => self
479                .create_and_report_missing::<TerminalSemicolon<'_>>(
480                    ParserDiagnosticKind::ExpectedSemicolonOrBody,
481                )
482                .into(),
483        };
484
485        ItemModule::new_green(self.db, attributes, visibility, module_kw, name, body)
486    }
487
488    /// Assumes the current token is Struct.
489    /// Expected pattern: `struct<Identifier>{<ParamList>}`
490    fn expect_item_struct(
491        &mut self,
492        attributes: AttributeListGreen<'a>,
493        visibility: VisibilityGreen<'a>,
494    ) -> ItemStructGreen<'a> {
495        let struct_kw = self.take::<TerminalStruct<'_>>();
496        let name = self.parse_identifier();
497        let generic_params = self.parse_optional_generic_params();
498        let lbrace = self.parse_token::<TerminalLBrace<'_>>();
499        let members = self.parse_member_list();
500        let rbrace = self.parse_token::<TerminalRBrace<'_>>();
501        ItemStruct::new_green(
502            self.db,
503            attributes,
504            visibility,
505            struct_kw,
506            name,
507            generic_params,
508            lbrace,
509            members,
510            rbrace,
511        )
512    }
513
514    /// Assumes the current token is Enum.
515    /// Expected pattern: `enum<Identifier>{<ParamList>}`
516    fn expect_item_enum(
517        &mut self,
518        attributes: AttributeListGreen<'a>,
519        visibility: VisibilityGreen<'a>,
520    ) -> ItemEnumGreen<'a> {
521        let enum_kw = self.take::<TerminalEnum<'_>>();
522        let name = self.parse_identifier();
523        let generic_params = self.parse_optional_generic_params();
524        let lbrace = self.parse_token::<TerminalLBrace<'_>>();
525        let variants = self.parse_variant_list();
526        let rbrace = self.parse_token::<TerminalRBrace<'_>>();
527        ItemEnum::new_green(
528            self.db,
529            attributes,
530            visibility,
531            enum_kw,
532            name,
533            generic_params,
534            lbrace,
535            variants,
536            rbrace,
537        )
538    }
539
540    /// Assumes the current token is type.
541    /// Expected pattern: `type <Identifier>{<ParamList>} = <TypeExpression>`
542    fn expect_item_type_alias(
543        &mut self,
544        attributes: AttributeListGreen<'a>,
545        visibility: VisibilityGreen<'a>,
546    ) -> ItemTypeAliasGreen<'a> {
547        let type_kw = self.take::<TerminalType<'_>>();
548        let name = self.parse_identifier();
549        let generic_params = self.parse_optional_generic_params();
550        let eq = self.parse_token::<TerminalEq<'_>>();
551        let ty = self.parse_type_expr();
552        let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
553        ItemTypeAlias::new_green(
554            self.db,
555            attributes,
556            visibility,
557            type_kw,
558            name,
559            generic_params,
560            eq,
561            ty,
562            semicolon,
563        )
564    }
565
566    /// Expected pattern: `<ParenthesizedParamList><ReturnTypeClause>`
567    fn expect_function_signature(&mut self) -> FunctionSignatureGreen<'a> {
568        let lparen = self.parse_token::<TerminalLParen<'_>>();
569        let params = self.parse_param_list();
570        let rparen = self.parse_token::<TerminalRParen<'_>>();
571        let return_type_clause = self.parse_option_return_type_clause();
572        let implicits_clause = self.parse_option_implicits_clause();
573        let optional_no_panic = if self.peek().kind == SyntaxKind::TerminalNoPanic {
574            self.take::<TerminalNoPanic<'_>>().into()
575        } else {
576            OptionTerminalNoPanicEmpty::new_green(self.db).into()
577        };
578
579        FunctionSignature::new_green(
580            self.db,
581            lparen,
582            params,
583            rparen,
584            return_type_clause,
585            implicits_clause,
586            optional_no_panic,
587        )
588    }
589
590    /// Assumes the current token is [TerminalConst].
591    /// Expected pattern: `const <Identifier> = <Expr>;`
592    fn expect_item_const(
593        &mut self,
594        attributes: AttributeListGreen<'a>,
595        visibility: VisibilityGreen<'a>,
596        const_kw: TerminalConstGreen<'a>,
597    ) -> ItemConstantGreen<'a> {
598        let name = self.parse_identifier();
599        let type_clause = self.parse_type_clause(ErrorRecovery {
600            should_stop: is_of_kind!(eq, semicolon, module_item_kw),
601        });
602        let eq = self.parse_token::<TerminalEq<'_>>();
603        let expr = self.parse_expr();
604        let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
605
606        ItemConstant::new_green(
607            self.db,
608            attributes,
609            visibility,
610            const_kw,
611            name,
612            type_clause,
613            eq,
614            expr,
615            semicolon,
616        )
617    }
618
619    /// Assumes the current token is Extern.
620    /// Expected pattern: `extern(<FunctionDeclaration>|type<Identifier>);`
621    fn expect_item_extern<T: From<ItemExternFunctionGreen<'a>> + From<ItemExternTypeGreen<'a>>>(
622        &mut self,
623        attributes: AttributeListGreen<'a>,
624        visibility: VisibilityGreen<'a>,
625    ) -> T {
626        match self.expect_item_extern_inner(attributes, visibility) {
627            ExternItem::Function(x) => x.into(),
628            ExternItem::Type(x) => x.into(),
629        }
630    }
631
632    /// Assumes the current token is Extern.
633    /// Expected pattern: `extern(<FunctionDeclaration>|type<Identifier>);`
634    fn expect_item_extern_inner(
635        &mut self,
636        attributes: AttributeListGreen<'a>,
637        visibility: VisibilityGreen<'a>,
638    ) -> ExternItem<'a> {
639        let extern_kw = self.take::<TerminalExtern<'_>>();
640        match self.peek().kind {
641            kind @ (SyntaxKind::TerminalFunction | SyntaxKind::TerminalConst) => {
642                let (optional_const, function_kw) = if kind == SyntaxKind::TerminalConst {
643                    (
644                        self.take::<TerminalConst<'_>>().into(),
645                        self.parse_token::<TerminalFunction<'_>>(),
646                    )
647                } else {
648                    (
649                        OptionTerminalConstEmpty::new_green(self.db).into(),
650                        self.take::<TerminalFunction<'_>>(),
651                    )
652                };
653                let declaration = self.expect_function_declaration_ex(optional_const, function_kw);
654                let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
655                ExternItem::Function(ItemExternFunction::new_green(
656                    self.db,
657                    attributes,
658                    visibility,
659                    extern_kw,
660                    declaration,
661                    semicolon,
662                ))
663            }
664            _ => {
665                // TODO(spapini): Don't return ItemExternType if we don't see a type.
666                let type_kw = self.parse_token::<TerminalType<'_>>();
667
668                let name = self.parse_identifier();
669                let generic_params = self.parse_optional_generic_params();
670                let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
671                // If the next token is not type, assume it is missing.
672                ExternItem::Type(ItemExternType::new_green(
673                    self.db,
674                    attributes,
675                    visibility,
676                    extern_kw,
677                    type_kw,
678                    name,
679                    generic_params,
680                    semicolon,
681                ))
682            }
683        }
684    }
685
686    /// Assumes the current token is Use.
687    /// Expected pattern: `use<Path>;`
688    fn expect_item_use(
689        &mut self,
690        attributes: AttributeListGreen<'a>,
691        visibility: VisibilityGreen<'a>,
692    ) -> ItemUseGreen<'a> {
693        let use_kw = self.take::<TerminalUse<'_>>();
694        let dollar = match self.peek().kind {
695            SyntaxKind::TerminalDollar => self.take::<TerminalDollar<'_>>().into(),
696            _ => OptionTerminalDollarEmpty::new_green(self.db).into(),
697        };
698        let use_path = self.parse_use_path();
699        let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
700        ItemUse::new_green(self.db, attributes, visibility, use_kw, dollar, use_path, semicolon)
701    }
702
703    /// Assumes the current token is Macro.
704    /// Expected pattern: `macro<Identifier>{<MacroRulesList>}`
705    fn expect_item_macro_declaration(
706        &mut self,
707        attributes: AttributeListGreen<'a>,
708        visibility: VisibilityGreen<'a>,
709    ) -> ItemMacroDeclarationGreen<'a> {
710        let macro_kw = self.take::<TerminalMacro<'_>>();
711        let name = self.parse_identifier();
712        let lbrace = self.parse_token::<TerminalLBrace<'_>>();
713        let macro_rules = MacroRulesList::new_green(
714            self.db,
715            &self.parse_list(Self::try_parse_macro_rule, is_of_kind!(rbrace), "macro rule"),
716        );
717        let rbrace = self.parse_token::<TerminalRBrace<'_>>();
718        ItemMacroDeclaration::new_green(
719            self.db,
720            attributes,
721            visibility,
722            macro_kw,
723            name,
724            lbrace,
725            macro_rules,
726            rbrace,
727        )
728    }
729
730    /// Returns a GreenId of a node with a MacroRule kind or TryParseFailure if a macro rule can't
731    /// be parsed.
732    fn try_parse_macro_rule(&mut self) -> TryParseResult<MacroRuleGreen<'a>> {
733        let previous_macro_parsing_context =
734            mem::replace(&mut self.macro_parsing_context, MacroParsingContext::MacroRule);
735        let wrapped_macro = match self.peek().kind {
736            SyntaxKind::TerminalLParen => self
737                .wrap_macro::<TerminalLParen<'_>, TerminalRParen<'_>, _, _>(
738                    ParenthesizedMacro::new_green,
739                )
740                .into(),
741            SyntaxKind::TerminalLBrace => self
742                .wrap_macro::<TerminalLBrace<'_>, TerminalRBrace<'_>, _, _>(BracedMacro::new_green)
743                .into(),
744            SyntaxKind::TerminalLBrack => self
745                .wrap_macro::<TerminalLBrack<'_>, TerminalRBrack<'_>, _, _>(
746                    BracketedMacro::new_green,
747                )
748                .into(),
749            _ => {
750                self.macro_parsing_context = previous_macro_parsing_context;
751                return Err(TryParseFailure::SkipToken);
752            }
753        };
754        let arrow = self.parse_token::<TerminalMatchArrow<'_>>();
755        if let Err(SkippedError(span)) = self.skip_until(is_of_kind!(rbrace, lbrace)) {
756            self.add_diagnostic(
757                ParserDiagnosticKind::SkippedElement { element_name: "'{'".into() },
758                span,
759            );
760        }
761        let macro_body = if self.peek().kind == SyntaxKind::TerminalLBrace {
762            self.macro_parsing_context = MacroParsingContext::MacroExpansion;
763            self.wrap_macro::<TerminalLBrace<'_>, TerminalRBrace<'_>, _, _>(BracedMacro::new_green)
764        } else {
765            BracedMacro::new_green(
766                self.db,
767                self.create_and_report_missing_terminal::<TerminalLBrace<'_>>(),
768                MacroElements::new_green(self.db, &[]),
769                self.create_and_report_missing_terminal::<TerminalRBrace<'_>>(),
770            )
771        };
772        let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
773        self.macro_parsing_context = previous_macro_parsing_context;
774        Ok(MacroRule::new_green(self.db, wrapped_macro, arrow, macro_body, semicolon))
775    }
776    /// Returns a GreenId of a node with a MacroRuleElement kind or TryParseFailure if a macro rule
777    /// element can't be parsed.
778    /// Expected pattern: Either any token or a matcher of the pattern $ident:kind.
779    fn try_parse_macro_element(&mut self) -> TryParseResult<MacroElementGreen<'a>> {
780        match self.peek().kind {
781            SyntaxKind::TerminalDollar => {
782                let dollar: TerminalDollarGreen<'_> = self.take::<TerminalDollar<'_>>();
783                match self.peek().kind {
784                    SyntaxKind::TerminalLParen => {
785                        let lparen = self.take::<TerminalLParen<'_>>();
786                        let elements = self.expect_wrapped_macro();
787                        let rparen = self.parse_token::<TerminalRParen<'_>>();
788                        let separator: OptionTerminalCommaGreen<'_> = match self.peek().kind {
789                            SyntaxKind::TerminalComma => self.take::<TerminalComma<'_>>().into(),
790                            _ => OptionTerminalCommaEmpty::new_green(self.db).into(),
791                        };
792                        let operator = match self.peek().kind {
793                            SyntaxKind::TerminalQuestionMark => {
794                                self.take::<TerminalQuestionMark<'_>>().into()
795                            }
796                            SyntaxKind::TerminalPlus => self.take::<TerminalPlus<'_>>().into(),
797                            SyntaxKind::TerminalMul => self.take::<TerminalMul<'_>>().into(),
798                            _ => MacroRepetitionOperator::missing(self.db),
799                        };
800                        Ok(MacroRepetition::new_green(
801                            self.db, dollar, lparen, elements, rparen, separator, operator,
802                        )
803                        .into())
804                    }
805                    _ => {
806                        let ident = self.parse_identifier();
807                        let param_kind: OptionParamKindGreen<'_> = if self.peek().kind
808                            == SyntaxKind::TerminalColon
809                        {
810                            let colon = self.parse_token::<TerminalColon<'_>>();
811                            let kind = self.parse_macro_rule_param_kind();
812                            let result = ParamKind::new_green(self.db, colon, kind).into();
813                            if let MacroParsingContext::MacroExpansion = self.macro_parsing_context
814                            {
815                                self.add_diagnostic(
816                                    ParserDiagnosticKind::InvalidParamKindInMacroExpansion,
817                                    TextSpan::new_with_width(self.offset, self.current_width),
818                                );
819                            }
820                            result
821                        } else {
822                            if let MacroParsingContext::MacroRule = self.macro_parsing_context {
823                                self.add_diagnostic(
824                                    ParserDiagnosticKind::InvalidParamKindInMacroRule,
825                                    TextSpan::new_with_width(self.offset, self.current_width),
826                                );
827                            }
828                            OptionParamKindEmpty::new_green(self.db).into()
829                        };
830                        self.macro_parsing_context = MacroParsingContext::None;
831                        Ok(MacroParam::new_green(self.db, dollar, ident, param_kind).into())
832                    }
833                }
834            }
835            SyntaxKind::TerminalLParen
836            | SyntaxKind::TerminalLBrace
837            | SyntaxKind::TerminalLBrack => {
838                let subtree = self.parse_macro_elements();
839                Ok(MacroWrapper::new_green(self.db, subtree).into())
840            }
841            _ => {
842                let token = self.parse_token_tree_leaf();
843                Ok(token.into())
844            }
845        }
846    }
847
848    fn parse_macro_elements(&mut self) -> WrappedMacroGreen<'a> {
849        match self.peek().kind {
850            SyntaxKind::TerminalLParen => self
851                .wrap_macro::<TerminalLParen<'_>, TerminalRParen<'_>, _, _>(
852                    ParenthesizedMacro::new_green,
853                )
854                .into(),
855            SyntaxKind::TerminalLBrace => self
856                .wrap_macro::<TerminalLBrace<'_>, TerminalRBrace<'_>, _, _>(BracedMacro::new_green)
857                .into(),
858            SyntaxKind::TerminalLBrack => self
859                .wrap_macro::<TerminalLBrack<'_>, TerminalRBrack<'_>, _, _>(
860                    BracketedMacro::new_green,
861                )
862                .into(),
863            _ => unreachable!("parse_macro_elements called on non-delimiter token"),
864        }
865    }
866
867    fn expect_wrapped_macro(&mut self) -> MacroElementsGreen<'a> {
868        let mut elements: Vec<MacroElementGreen<'a>> = vec![];
869        while !matches!(
870            self.peek().kind,
871            SyntaxKind::TerminalRParen
872                | SyntaxKind::TerminalRBrace
873                | SyntaxKind::TerminalRBrack
874                | SyntaxKind::TerminalEndOfFile
875        ) {
876            let element = self.try_parse_macro_element();
877            match element {
878                Ok(element) => elements.push(element),
879                Err(TryParseFailure::SkipToken) => {
880                    let _ = self.skip_until(is_of_kind!(rparen, rbrace, rbrack));
881                    break;
882                }
883                Err(TryParseFailure::DoNothing) => break,
884            }
885        }
886        MacroElements::new_green(self.db, &elements)
887    }
888
889    fn wrap_macro<
890        LTerminal: syntax::node::Terminal<'a>,
891        RTerminal: syntax::node::Terminal<'a>,
892        ListGreen,
893        NewGreen: Fn(
894            &'a dyn Database,
895            LTerminal::Green,
896            MacroElementsGreen<'a>,
897            RTerminal::Green,
898        ) -> ListGreen,
899    >(
900        &mut self,
901        new_green: NewGreen,
902    ) -> ListGreen {
903        let l_term = self.take::<LTerminal>();
904        let elements = self.expect_wrapped_macro();
905        let r_term = self.parse_token::<RTerminal>();
906        new_green(self.db, l_term, elements, r_term)
907    }
908
909    /// Returns a GreenId of a node with a MacroRuleParamKind kind.
910    fn parse_macro_rule_param_kind(&mut self) -> MacroParamKindGreen<'a> {
911        let peeked = self.peek();
912        match (peeked.kind, peeked.text.long(self.db).as_str()) {
913            (SyntaxKind::TerminalIdentifier, "ident") => {
914                ParamIdent::new_green(self.db, self.parse_token::<TerminalIdentifier<'_>>()).into()
915            }
916            (SyntaxKind::TerminalIdentifier, "expr") => {
917                ParamExpr::new_green(self.db, self.parse_token::<TerminalIdentifier<'_>>()).into()
918            }
919            _ => self.create_and_report_missing::<MacroParamKind<'_>>(
920                ParserDiagnosticKind::MissingMacroRuleParamKind,
921            ),
922        }
923    }
924
925    /// Returns a GreenId of a node with a UsePath kind or TryParseFailure if can't parse a UsePath.
926    fn try_parse_use_path(&mut self) -> TryParseResult<UsePathGreen<'a>> {
927        if !matches!(
928            self.peek().kind,
929            SyntaxKind::TerminalLBrace | SyntaxKind::TerminalIdentifier | SyntaxKind::TerminalMul
930        ) {
931            return Err(TryParseFailure::SkipToken);
932        }
933        Ok(self.parse_use_path())
934    }
935
936    /// Returns a GreenId of a node with a UsePath kind.
937    fn parse_use_path(&mut self) -> UsePathGreen<'a> {
938        match self.peek().kind {
939            SyntaxKind::TerminalLBrace => {
940                let lbrace = self.parse_token::<TerminalLBrace<'_>>();
941                let items = UsePathList::new_green(self.db,
942                    &self.parse_separated_list::<
943                        UsePath<'_>, TerminalComma<'_>, UsePathListElementOrSeparatorGreen<'_>
944                    >(
945                        Self::try_parse_use_path,
946                        is_of_kind!(rbrace, module_item_kw),
947                        "path segment",
948                    ));
949                let rbrace = self.parse_token::<TerminalRBrace<'_>>();
950                UsePathMulti::new_green(self.db, lbrace, items, rbrace).into()
951            }
952            SyntaxKind::TerminalMul => {
953                let star = self.parse_token::<TerminalMul<'_>>();
954                UsePathStar::new_green(self.db, star).into()
955            }
956            _ => {
957                if let Ok(ident) = self.try_parse_identifier() {
958                    let ident = PathSegmentSimple::new_green(self.db, ident).into();
959                    match self.peek().kind {
960                        SyntaxKind::TerminalColonColon => {
961                            let colon_colon = self.parse_token::<TerminalColonColon<'_>>();
962                            let use_path = self.parse_use_path();
963                            UsePathSingle::new_green(self.db, ident, colon_colon, use_path).into()
964                        }
965                        SyntaxKind::TerminalAs => {
966                            let as_kw = self.take::<TerminalAs<'_>>();
967                            let alias = self.parse_identifier();
968                            let alias_clause = AliasClause::new_green(self.db, as_kw, alias).into();
969                            UsePathLeaf::new_green(self.db, ident, alias_clause).into()
970                        }
971                        _ => {
972                            let alias_clause = OptionAliasClauseEmpty::new_green(self.db).into();
973                            UsePathLeaf::new_green(self.db, ident, alias_clause).into()
974                        }
975                    }
976                } else {
977                    let missing = self.create_and_report_missing::<TerminalIdentifier<'_>>(
978                        ParserDiagnosticKind::MissingPathSegment,
979                    );
980                    let ident = PathSegmentSimple::new_green(self.db, missing).into();
981                    UsePathLeaf::new_green(
982                        self.db,
983                        ident,
984                        OptionAliasClauseEmpty::new_green(self.db).into(),
985                    )
986                    .into()
987                }
988            }
989        }
990    }
991
992    /// Returns a GreenId of a node with an identifier kind or TryParseFailure if an identifier
993    /// can't be parsed.
994    /// Note that if the terminal is a keyword or an underscore, it is skipped, and
995    /// Some(missing-identifier) is returned.
996    fn try_parse_identifier(&mut self) -> TryParseResult<TerminalIdentifierGreen<'a>> {
997        let peeked = self.peek();
998        if peeked.kind.is_keyword_terminal() {
999            // TODO(spapini): don't skip every keyword. Instead, pass a recovery set.
1000            Ok(self.skip_token_and_return_missing::<TerminalIdentifier<'_>>(
1001                ParserDiagnosticKind::ReservedIdentifier {
1002                    identifier: peeked.text.long(self.db).to_string(),
1003                },
1004            ))
1005        } else if peeked.kind == SyntaxKind::TerminalUnderscore {
1006            Ok(self.skip_token_and_return_missing::<TerminalIdentifier<'_>>(
1007                ParserDiagnosticKind::UnderscoreNotAllowedAsIdentifier,
1008            ))
1009        } else {
1010            self.try_parse_token::<TerminalIdentifier<'_>>()
1011        }
1012    }
1013    /// Returns whether the current token is an identifier, a keyword or an underscore ('_'),
1014    /// without consuming it. This should be used mostly, instead of checking whether the current
1015    /// token is an identifier, because in many cases we'd want to consume the keyword/underscore as
1016    /// the identifier and raise a relevant diagnostic
1017    /// (ReservedIdentifier/UnderscoreNotAllowedAsIdentifier).
1018    fn is_peek_identifier_like(&self) -> bool {
1019        let kind = self.peek().kind;
1020        kind.is_keyword_terminal()
1021            || matches!(
1022                kind,
1023                SyntaxKind::TerminalUnderscore
1024                    | SyntaxKind::TerminalIdentifier
1025                    | SyntaxKind::TerminalDollar
1026            )
1027    }
1028
1029    /// Returns a GreenId of a node with an identifier kind.
1030    fn parse_identifier(&mut self) -> TerminalIdentifierGreen<'a> {
1031        match self.try_parse_identifier() {
1032            Ok(identifier) => identifier,
1033            Err(_) => self.create_and_report_missing_terminal::<TerminalIdentifier<'_>>(),
1034        }
1035    }
1036
1037    /// Returns a GreenId of node visibility.
1038    fn parse_visibility(&mut self) -> VisibilityGreen<'a> {
1039        match self.try_parse_visibility_pub() {
1040            Some(visibility) => visibility.into(),
1041            None => VisibilityDefault::new_green(self.db).into(),
1042        }
1043    }
1044
1045    /// Returns a GreenId of node with pub visibility or None if not starting with "pub".
1046    fn try_parse_visibility_pub(&mut self) -> Option<VisibilityPubGreen<'a>> {
1047        require(self.peek().kind == SyntaxKind::TerminalPub)?;
1048        let pub_kw = self.take::<TerminalPub<'_>>();
1049        let argument_clause = if self.peek().kind != SyntaxKind::TerminalLParen {
1050            OptionVisibilityPubArgumentClauseEmpty::new_green(self.db).into()
1051        } else {
1052            let lparen = self.parse_token::<TerminalLParen<'_>>();
1053            let argument = self.parse_token::<TerminalIdentifier<'_>>();
1054            let rparen = self.parse_token::<TerminalRParen<'_>>();
1055            VisibilityPubArgumentClause::new_green(self.db, lparen, argument, rparen).into()
1056        };
1057        Some(VisibilityPub::new_green(self.db, pub_kw, argument_clause))
1058    }
1059
1060    /// Returns a GreenId of a node with an attribute list kind or TryParseFailure if an attribute
1061    /// list can't be parsed.
1062    /// `expected_elements_str` are the expected elements that these attributes are parsed for.
1063    /// Note: it should not include "attribute".
1064    fn try_parse_attribute_list(
1065        &mut self,
1066        expected_elements_str: &str,
1067    ) -> TryParseResult<AttributeListGreen<'a>> {
1068        if self.peek().kind == SyntaxKind::TerminalHash {
1069            Ok(self.parse_attribute_list(expected_elements_str))
1070        } else {
1071            Err(TryParseFailure::SkipToken)
1072        }
1073    }
1074
1075    /// Parses an attribute list.
1076    /// `expected_elements_str` are the expected elements that these attributes are parsed for.
1077    /// Note: it should not include "attribute".
1078    fn parse_attribute_list(&mut self, expected_elements_str: &str) -> AttributeListGreen<'a> {
1079        AttributeList::new_green(
1080            self.db,
1081            &self.parse_list(
1082                Self::try_parse_attribute,
1083                |x| x != SyntaxKind::TerminalHash,
1084                &or_an_attribute!(expected_elements_str),
1085            ),
1086        )
1087    }
1088
1089    /// Returns a GreenId of a node with an attribute kind or TryParseFailure if an attribute can't
1090    /// be parsed.
1091    fn try_parse_attribute(&mut self) -> TryParseResult<AttributeGreen<'a>> {
1092        match self.peek().kind {
1093            SyntaxKind::TerminalHash => {
1094                let hash = self.take::<TerminalHash<'_>>();
1095                let lbrack = self.parse_token::<TerminalLBrack<'_>>();
1096                let attr = self.parse_path();
1097                let arguments = self.try_parse_parenthesized_argument_list();
1098                let rbrack = self.parse_token::<TerminalRBrack<'_>>();
1099
1100                Ok(Attribute::new_green(self.db, hash, lbrack, attr, arguments, rbrack))
1101            }
1102            _ => Err(TryParseFailure::SkipToken),
1103        }
1104    }
1105
1106    /// Assumes the current token is Function.
1107    /// Expected pattern: `<FunctionDeclaration>`
1108    fn expect_function_declaration(
1109        &mut self,
1110        optional_const: OptionTerminalConstGreen<'a>,
1111    ) -> FunctionDeclarationGreen<'a> {
1112        let function_kw = self.take::<TerminalFunction<'_>>();
1113        self.expect_function_declaration_ex(optional_const, function_kw)
1114    }
1115
1116    /// Assumes the current token is Function.
1117    /// Expected pattern: `<FunctionDeclaration>`
1118    fn expect_function_declaration_ex(
1119        &mut self,
1120        optional_const: OptionTerminalConstGreen<'a>,
1121        function_kw: TerminalFunctionGreen<'a>,
1122    ) -> FunctionDeclarationGreen<'a> {
1123        let name = self.parse_identifier();
1124        let generic_params = self.parse_optional_generic_params();
1125        let signature = self.expect_function_signature();
1126
1127        FunctionDeclaration::new_green(
1128            self.db,
1129            optional_const,
1130            function_kw,
1131            name,
1132            generic_params,
1133            signature,
1134        )
1135    }
1136
1137    /// Assumes the current token is Function.
1138    /// Expected pattern: `<FunctionDeclaration><Block>`
1139    fn expect_item_function_with_body(
1140        &mut self,
1141        attributes: AttributeListGreen<'a>,
1142        visibility: VisibilityGreen<'a>,
1143        optional_const: OptionTerminalConstGreen<'a>,
1144    ) -> FunctionWithBodyGreen<'a> {
1145        let declaration = self.expect_function_declaration(optional_const);
1146        let function_body = self.parse_block();
1147        FunctionWithBody::new_green(self.db, attributes, visibility, declaration, function_body)
1148    }
1149
1150    /// Assumes the current token is Trait.
1151    fn expect_item_trait(
1152        &mut self,
1153        attributes: AttributeListGreen<'a>,
1154        visibility: VisibilityGreen<'a>,
1155    ) -> ItemTraitGreen<'a> {
1156        let trait_kw = self.take::<TerminalTrait<'_>>();
1157        let name = self.parse_identifier();
1158        let generic_params = self.parse_optional_generic_params();
1159        let body = if self.peek().kind == SyntaxKind::TerminalLBrace {
1160            let lbrace = self.take::<TerminalLBrace<'_>>();
1161            let items = TraitItemList::new_green(
1162                self.db,
1163                &self.parse_attributed_list(
1164                    Self::try_parse_trait_item,
1165                    is_of_kind!(rbrace, module_item_kw),
1166                    TRAIT_ITEM_DESCRIPTION,
1167                ),
1168            );
1169            let rbrace = self.parse_token::<TerminalRBrace<'_>>();
1170            TraitBody::new_green(self.db, lbrace, items, rbrace).into()
1171        } else {
1172            self.parse_token::<TerminalSemicolon<'_>>().into()
1173        };
1174
1175        ItemTrait::new_green(self.db, attributes, visibility, trait_kw, name, generic_params, body)
1176    }
1177
1178    /// Returns a GreenId of a node with a TraitItem.* kind (see
1179    /// [syntax::node::ast::TraitItem]), or TryParseFailure if a trait item can't be parsed.
1180    pub fn try_parse_trait_item(&mut self) -> TryParseResult<TraitItemGreen<'a>> {
1181        let maybe_attributes = self.try_parse_attribute_list(TRAIT_ITEM_DESCRIPTION);
1182
1183        let (has_attrs, attributes) = match maybe_attributes {
1184            Ok(attributes) => (true, attributes),
1185            Err(_) => (false, AttributeList::new_green(self.db, &[])),
1186        };
1187
1188        match self.peek().kind {
1189            SyntaxKind::TerminalFunction => Ok(self
1190                .expect_trait_item_function(
1191                    attributes,
1192                    OptionTerminalConstEmpty::new_green(self.db).into(),
1193                )
1194                .into()),
1195            SyntaxKind::TerminalType => Ok(self.expect_trait_item_type(attributes).into()),
1196            SyntaxKind::TerminalConst => {
1197                let const_kw = self.take::<TerminalConst<'_>>();
1198                Ok(if self.peek().kind == SyntaxKind::TerminalFunction {
1199                    self.expect_trait_item_function(attributes, const_kw.into()).into()
1200                } else {
1201                    self.expect_trait_item_const(attributes, const_kw).into()
1202                })
1203            }
1204            SyntaxKind::TerminalImpl => Ok(self.expect_trait_item_impl(attributes).into()),
1205            _ => {
1206                if has_attrs {
1207                    Ok(self.skip_taken_node_and_return_missing::<TraitItem<'_>>(
1208                        attributes,
1209                        ParserDiagnosticKind::AttributesWithoutTraitItem,
1210                    ))
1211                } else {
1212                    Err(TryParseFailure::SkipToken)
1213                }
1214            }
1215        }
1216    }
1217
1218    /// Assumes the current token is Function.
1219    /// Expected pattern: `<FunctionDeclaration><SemiColon>`
1220    fn expect_trait_item_function(
1221        &mut self,
1222        attributes: AttributeListGreen<'a>,
1223        optional_const: OptionTerminalConstGreen<'a>,
1224    ) -> TraitItemFunctionGreen<'a> {
1225        let declaration = self.expect_function_declaration(optional_const);
1226        let body = if self.peek().kind == SyntaxKind::TerminalLBrace {
1227            self.parse_block().into()
1228        } else {
1229            self.parse_token::<TerminalSemicolon<'_>>().into()
1230        };
1231        TraitItemFunction::new_green(self.db, attributes, declaration, body)
1232    }
1233
1234    /// Assumes the current token is Type.
1235    /// Expected pattern: `type <name>;`
1236    fn expect_trait_item_type(
1237        &mut self,
1238        attributes: AttributeListGreen<'a>,
1239    ) -> TraitItemTypeGreen<'a> {
1240        let type_kw = self.take::<TerminalType<'_>>();
1241        let name = self.parse_identifier();
1242        let generic_params = self.parse_optional_generic_params();
1243        let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
1244        TraitItemType::new_green(self.db, attributes, type_kw, name, generic_params, semicolon)
1245    }
1246
1247    /// Assumes the current token is Const.
1248    /// Expected pattern: `const <name>: <type>;`
1249    fn expect_trait_item_const(
1250        &mut self,
1251        attributes: AttributeListGreen<'a>,
1252        const_kw: TerminalConstGreen<'a>,
1253    ) -> TraitItemConstantGreen<'a> {
1254        let name = self.parse_identifier();
1255        let type_clause = self.parse_type_clause(ErrorRecovery {
1256            should_stop: is_of_kind!(eq, semicolon, module_item_kw),
1257        });
1258        let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
1259
1260        TraitItemConstant::new_green(self.db, attributes, const_kw, name, type_clause, semicolon)
1261    }
1262
1263    /// Assumes the current token is Impl.
1264    /// Expected pattern: `impl <name>: <trait_path>;`
1265    fn expect_trait_item_impl(
1266        &mut self,
1267        attributes: AttributeListGreen<'a>,
1268    ) -> TraitItemImplGreen<'a> {
1269        let impl_kw = self.take::<TerminalImpl<'_>>();
1270        let name = self.parse_identifier();
1271        let colon = self.parse_token::<TerminalColon<'_>>();
1272        let trait_path = self.parse_type_path();
1273        let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
1274        TraitItemImpl::new_green(self.db, attributes, impl_kw, name, colon, trait_path, semicolon)
1275    }
1276
1277    /// Assumes the current token is Impl.
1278    fn expect_module_item_impl(
1279        &mut self,
1280        attributes: AttributeListGreen<'a>,
1281        visibility: VisibilityGreen<'a>,
1282    ) -> ModuleItemGreen<'a> {
1283        match self.expect_item_impl_inner(attributes, visibility, false) {
1284            ImplItemOrAlias::Item(green) => green.into(),
1285            ImplItemOrAlias::Alias(green) => green.into(),
1286        }
1287    }
1288
1289    /// Assumes the current token is Impl.
1290    /// Expects an impl impl-item (impl alias syntax): `impl <name> = <path>;`.
1291    fn expect_impl_item_impl(
1292        &mut self,
1293        attributes: AttributeListGreen<'a>,
1294        visibility: VisibilityGreen<'a>,
1295    ) -> ItemImplAliasGreen<'a> {
1296        extract_matches!(
1297            self.expect_item_impl_inner(attributes, visibility, true),
1298            ImplItemOrAlias::Alias
1299        )
1300    }
1301
1302    /// Assumes the current token is Impl.
1303    /// Expects either an impl item (`impl <name> of <trait_path> {<impl_body>}`) or and impl alias
1304    /// `impl <name> = <path>;`.
1305    /// If `only_allow_alias` is true, always returns a ImplItemOrAlias::Alias.
1306    fn expect_item_impl_inner(
1307        &mut self,
1308        attributes: AttributeListGreen<'a>,
1309        visibility: VisibilityGreen<'a>,
1310        only_allow_alias: bool,
1311    ) -> ImplItemOrAlias<'a> {
1312        let impl_kw = self.take::<TerminalImpl<'_>>();
1313        let name = self.parse_identifier();
1314        let generic_params = self.parse_optional_generic_params();
1315
1316        if self.peek().kind == SyntaxKind::TerminalEq || only_allow_alias {
1317            let eq = self.parse_token::<TerminalEq<'_>>();
1318            let impl_path = self.parse_type_path();
1319            let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
1320
1321            return ImplItemOrAlias::Alias(ItemImplAlias::new_green(
1322                self.db,
1323                attributes,
1324                visibility,
1325                impl_kw,
1326                name,
1327                generic_params,
1328                eq,
1329                impl_path,
1330                semicolon,
1331            ));
1332        }
1333
1334        let of_kw = self.parse_token::<TerminalOf<'_>>();
1335        let trait_path = self.parse_type_path();
1336        let body = if self.peek().kind == SyntaxKind::TerminalLBrace {
1337            let lbrace = self.take::<TerminalLBrace<'_>>();
1338            let items = ImplItemList::new_green(
1339                self.db,
1340                &self.parse_attributed_list(
1341                    Self::try_parse_impl_item,
1342                    is_of_kind!(rbrace),
1343                    IMPL_ITEM_DESCRIPTION,
1344                ),
1345            );
1346            let rbrace = self.parse_token::<TerminalRBrace<'_>>();
1347            ImplBody::new_green(self.db, lbrace, items, rbrace).into()
1348        } else {
1349            self.parse_token::<TerminalSemicolon<'_>>().into()
1350        };
1351
1352        ImplItemOrAlias::Item(ItemImpl::new_green(
1353            self.db,
1354            attributes,
1355            visibility,
1356            impl_kw,
1357            name,
1358            generic_params,
1359            of_kw,
1360            trait_path,
1361            body,
1362        ))
1363    }
1364
1365    /// Returns a GreenId of a node with a ImplItem.* kind (see
1366    /// [syntax::node::ast::ImplItem]), or TryParseFailure if an impl item can't be parsed.
1367    pub fn try_parse_impl_item(&mut self) -> TryParseResult<ImplItemGreen<'a>> {
1368        let maybe_attributes = self.try_parse_attribute_list(IMPL_ITEM_DESCRIPTION);
1369
1370        let (has_attrs, attributes) = match maybe_attributes {
1371            Ok(attributes) => (true, attributes),
1372            Err(_) => (false, AttributeList::new_green(self.db, &[])),
1373        };
1374
1375        // No visibility in impls, as these just implements the options of a trait, which is always
1376        // pub.
1377        let visibility = VisibilityDefault::new_green(self.db).into();
1378
1379        match self.peek().kind {
1380            SyntaxKind::TerminalFunction => Ok(self
1381                .expect_item_function_with_body(
1382                    attributes,
1383                    visibility,
1384                    OptionTerminalConstEmpty::new_green(self.db).into(),
1385                )
1386                .into()),
1387            SyntaxKind::TerminalType => {
1388                Ok(self.expect_item_type_alias(attributes, visibility).into())
1389            }
1390            SyntaxKind::TerminalConst => {
1391                let const_kw = self.take::<TerminalConst<'_>>();
1392                Ok(if self.peek().kind == SyntaxKind::TerminalFunction {
1393                    self.expect_item_function_with_body(attributes, visibility, const_kw.into())
1394                        .into()
1395                } else {
1396                    self.expect_item_const(attributes, visibility, const_kw).into()
1397                })
1398            }
1399            SyntaxKind::TerminalImpl => {
1400                Ok(self.expect_impl_item_impl(attributes, visibility).into())
1401            }
1402            // These are not supported semantically.
1403            SyntaxKind::TerminalModule => {
1404                Ok(self.expect_item_module(attributes, visibility).into())
1405            }
1406            SyntaxKind::TerminalStruct => {
1407                Ok(self.expect_item_struct(attributes, visibility).into())
1408            }
1409            SyntaxKind::TerminalEnum => Ok(self.expect_item_enum(attributes, visibility).into()),
1410            SyntaxKind::TerminalExtern => Ok(self.expect_item_extern(attributes, visibility)),
1411            SyntaxKind::TerminalUse => Ok(self.expect_item_use(attributes, visibility).into()),
1412            SyntaxKind::TerminalTrait => Ok(self.expect_item_trait(attributes, visibility).into()),
1413            _ => {
1414                if has_attrs {
1415                    Ok(self.skip_taken_node_and_return_missing::<ImplItem<'_>>(
1416                        attributes,
1417                        ParserDiagnosticKind::AttributesWithoutImplItem,
1418                    ))
1419                } else {
1420                    Err(TryParseFailure::SkipToken)
1421                }
1422            }
1423        }
1424    }
1425
1426    /// Assumes the current token is TerminalNot.
1427    fn expect_item_inline_macro(
1428        &mut self,
1429        attributes: AttributeListGreen<'a>,
1430        path: ExprPathGreen<'a>,
1431    ) -> ItemInlineMacroGreen<'a> {
1432        let bang = self.parse_token::<TerminalNot<'_>>();
1433        self.parse_item_inline_macro_given_bang(attributes, path, bang)
1434    }
1435
1436    /// Returns a GreenId of a node with an ItemInlineMacro kind, given the bang ('!') token.
1437    fn parse_item_inline_macro_given_bang(
1438        &mut self,
1439        attributes: AttributeListGreen<'a>,
1440        path: ExprPathGreen<'a>,
1441        bang: TerminalNotGreen<'a>,
1442    ) -> ItemInlineMacroGreen<'a> {
1443        let token_tree_node = self.parse_token_tree_node();
1444        let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
1445        ItemInlineMacro::new_green(self.db, attributes, path, bang, token_tree_node, semicolon)
1446    }
1447
1448    // ------------------------------- Expressions -------------------------------
1449
1450    /// Returns a GreenId of a node with an Expr.* kind (see [syntax::node::ast::Expr])
1451    /// or TryParseFailure if an expression can't be parsed.
1452    pub fn try_parse_expr(&mut self) -> TryParseResult<ExprGreen<'a>> {
1453        self.try_parse_expr_limited(MAX_PRECEDENCE, LbraceAllowed::Allow, AndLetBehavior::Simple)
1454    }
1455    /// Returns a GreenId of a node with an Expr.* kind (see [syntax::node::ast::Expr])
1456    /// or a node with kind ExprMissing if an expression can't be parsed.
1457    pub fn parse_expr(&mut self) -> ExprGreen<'a> {
1458        match self.try_parse_expr() {
1459            Ok(green) => green,
1460            Err(_) => {
1461                self.create_and_report_missing::<Expr<'_>>(ParserDiagnosticKind::MissingExpression)
1462            }
1463        }
1464    }
1465
1466    /// Assumes the current token is a binary operator. Otherwise it might panic.
1467    ///
1468    /// Returns a GreenId of the operator.
1469    fn parse_binary_operator(&mut self) -> BinaryOperatorGreen<'a> {
1470        // Note that if this code is not reached you might need to add the operator to
1471        // `get_post_operator_precedence`.
1472        match self.peek().kind {
1473            SyntaxKind::TerminalDot => self.take::<TerminalDot<'_>>().into(),
1474            SyntaxKind::TerminalMul => self.take::<TerminalMul<'_>>().into(),
1475            SyntaxKind::TerminalMulEq => self.take::<TerminalMulEq<'_>>().into(),
1476            SyntaxKind::TerminalDiv => self.take::<TerminalDiv<'_>>().into(),
1477            SyntaxKind::TerminalDivEq => self.take::<TerminalDivEq<'_>>().into(),
1478            SyntaxKind::TerminalMod => self.take::<TerminalMod<'_>>().into(),
1479            SyntaxKind::TerminalModEq => self.take::<TerminalModEq<'_>>().into(),
1480            SyntaxKind::TerminalPlus => self.take::<TerminalPlus<'_>>().into(),
1481            SyntaxKind::TerminalPlusEq => self.take::<TerminalPlusEq<'_>>().into(),
1482            SyntaxKind::TerminalMinus => self.take::<TerminalMinus<'_>>().into(),
1483            SyntaxKind::TerminalMinusEq => self.take::<TerminalMinusEq<'_>>().into(),
1484            SyntaxKind::TerminalEq => self.take::<TerminalEq<'_>>().into(),
1485            SyntaxKind::TerminalEqEq => self.take::<TerminalEqEq<'_>>().into(),
1486            SyntaxKind::TerminalNeq => self.take::<TerminalNeq<'_>>().into(),
1487            SyntaxKind::TerminalLT => self.take::<TerminalLT<'_>>().into(),
1488            SyntaxKind::TerminalGT => self.take::<TerminalGT<'_>>().into(),
1489            SyntaxKind::TerminalLE => self.take::<TerminalLE<'_>>().into(),
1490            SyntaxKind::TerminalGE => self.take::<TerminalGE<'_>>().into(),
1491            SyntaxKind::TerminalAnd => self.take::<TerminalAnd<'_>>().into(),
1492            SyntaxKind::TerminalAndAnd => self.take::<TerminalAndAnd<'_>>().into(),
1493            SyntaxKind::TerminalOrOr => self.take::<TerminalOrOr<'_>>().into(),
1494            SyntaxKind::TerminalOr => self.take::<TerminalOr<'_>>().into(),
1495            SyntaxKind::TerminalXor => self.take::<TerminalXor<'_>>().into(),
1496            SyntaxKind::TerminalDotDot => self.take::<TerminalDotDot<'_>>().into(),
1497            SyntaxKind::TerminalDotDotEq => self.take::<TerminalDotDotEq<'_>>().into(),
1498            _ => unreachable!(),
1499        }
1500    }
1501
1502    /// Assumes the current token is a unary operator, and returns a GreenId of the operator.
1503    fn expect_unary_operator(&mut self) -> UnaryOperatorGreen<'a> {
1504        match self.peek().kind {
1505            SyntaxKind::TerminalAt => self.take::<TerminalAt<'_>>().into(),
1506            SyntaxKind::TerminalNot => self.take::<TerminalNot<'_>>().into(),
1507            SyntaxKind::TerminalBitNot => self.take::<TerminalBitNot<'_>>().into(),
1508            SyntaxKind::TerminalMinus => self.take::<TerminalMinus<'_>>().into(),
1509            SyntaxKind::TerminalMul => self.take::<TerminalMul<'_>>().into(),
1510            _ => unreachable!(),
1511        }
1512    }
1513
1514    /// Checks if the current token is a relational or equality operator (`<`, `>`, `<=`, `>=`,
1515    /// `==`, or `!=`).
1516    ///
1517    /// This function is used to determine if the given `SyntaxKind` represents a relational or
1518    /// equality operator, which is commonly used in binary expressions.
1519    ///
1520    /// # Parameters:
1521    /// - `kind`: The `SyntaxKind` of the current token.
1522    ///
1523    /// # Returns:
1524    /// `true` if the token is a relational or equality operator, otherwise `false`.
1525    fn is_comparison_operator(&self, kind: SyntaxKind) -> bool {
1526        matches!(
1527            kind,
1528            SyntaxKind::TerminalLT
1529                | SyntaxKind::TerminalGT
1530                | SyntaxKind::TerminalLE
1531                | SyntaxKind::TerminalGE
1532                | SyntaxKind::TerminalEqEq
1533                | SyntaxKind::TerminalNeq
1534        )
1535    }
1536
1537    /// Returns a GreenId of a node with an Expr.* kind (see [syntax::node::ast::Expr])
1538    /// or TryParseFailure if such an expression can't be parsed.
1539    ///
1540    /// Parsing will be limited by:
1541    /// `parent_precedence` - parsing of binary operators limited to this.
1542    /// `lbrace_allowed` - See [LbraceAllowed].
1543    fn try_parse_expr_limited(
1544        &mut self,
1545        parent_precedence: usize,
1546        lbrace_allowed: LbraceAllowed,
1547        and_let_behavior: AndLetBehavior,
1548    ) -> TryParseResult<ExprGreen<'a>> {
1549        let mut expr = self.try_parse_atom_or_unary(lbrace_allowed)?;
1550        let mut child_op: Option<SyntaxKind> = None;
1551        loop {
1552            let peeked_kind = self.peek().kind;
1553            let Some(precedence) = get_post_operator_precedence(peeked_kind) else {
1554                return Ok(expr);
1555            };
1556            if precedence >= parent_precedence {
1557                return Ok(expr);
1558            }
1559            expr = match peeked_kind {
1560                // If the next two tokens are `&& let` (part of a let-chain), then they should be
1561                // parsed by the caller. Return immediately.
1562                SyntaxKind::TerminalAndAnd
1563                    if and_let_behavior == AndLetBehavior::Stop
1564                        && self.peek_next_next_kind() == SyntaxKind::TerminalLet =>
1565                {
1566                    return Ok(expr);
1567                }
1568                SyntaxKind::TerminalQuestionMark => ExprErrorPropagate::new_green(
1569                    self.db,
1570                    expr,
1571                    self.take::<TerminalQuestionMark<'_>>(),
1572                )
1573                .into(),
1574                SyntaxKind::TerminalLBrack => {
1575                    let lbrack = self.take::<TerminalLBrack<'_>>();
1576                    let index_expr = self.parse_expr();
1577                    let rbrack = self.parse_token::<TerminalRBrack<'_>>();
1578                    ExprIndexed::new_green(self.db, expr, lbrack, index_expr, rbrack).into()
1579                }
1580                current_op => {
1581                    if let Some(child_op_kind) = child_op
1582                        && self.is_comparison_operator(child_op_kind)
1583                        && self.is_comparison_operator(current_op)
1584                    {
1585                        self.add_diagnostic(
1586                            ParserDiagnosticKind::ConsecutiveMathOperators {
1587                                first_op: child_op_kind,
1588                                second_op: current_op,
1589                            },
1590                            TextSpan::cursor(self.offset.add_width(self.current_width)),
1591                        );
1592                    }
1593                    child_op = Some(current_op);
1594                    let op = self.parse_binary_operator();
1595                    let rhs = self.parse_expr_limited(precedence, lbrace_allowed, and_let_behavior);
1596                    ExprBinary::new_green(self.db, expr, op, rhs).into()
1597                }
1598            };
1599        }
1600    }
1601
1602    /// Returns a GreenId of a node with ExprPath, ExprFunctionCall, ExprStructCtorCall,
1603    /// ExprParenthesized, ExprTuple or ExprUnary kind, or TryParseFailure if such an expression
1604    /// can't be parsed.
1605    ///
1606    /// `lbrace_allowed` - See [LbraceAllowed].
1607    fn try_parse_atom_or_unary(
1608        &mut self,
1609        lbrace_allowed: LbraceAllowed,
1610    ) -> TryParseResult<ExprGreen<'a>> {
1611        let Some(precedence) = get_unary_operator_precedence(self.peek().kind) else {
1612            return self.try_parse_atom(lbrace_allowed);
1613        };
1614        let op = self.expect_unary_operator();
1615        let expr = self.parse_expr_limited(precedence, lbrace_allowed, AndLetBehavior::Simple);
1616        Ok(ExprUnary::new_green(self.db, op, expr).into())
1617    }
1618
1619    /// Returns a GreenId of a node with an Expr.* kind (see [syntax::node::ast::Expr]),
1620    /// excluding ExprBlock, or ExprMissing if such an expression can't be parsed.
1621    ///
1622    /// `lbrace_allowed` - See [LbraceAllowed].
1623    fn parse_expr_limited(
1624        &mut self,
1625        parent_precedence: usize,
1626        lbrace_allowed: LbraceAllowed,
1627        and_let_behavior: AndLetBehavior,
1628    ) -> ExprGreen<'a> {
1629        match self.try_parse_expr_limited(parent_precedence, lbrace_allowed, and_let_behavior) {
1630            Ok(green) => green,
1631            Err(_) => {
1632                self.create_and_report_missing::<Expr<'_>>(ParserDiagnosticKind::MissingExpression)
1633            }
1634        }
1635    }
1636
1637    /// Returns a GreenId of a node with an
1638    /// ExprPath|ExprFunctionCall|ExprStructCtorCall|ExprParenthesized|ExprTuple kind, or
1639    /// TryParseFailure if such an expression can't be parsed.
1640    ///
1641    /// `lbrace_allowed` - See [LbraceAllowed].
1642    fn try_parse_atom(&mut self, lbrace_allowed: LbraceAllowed) -> TryParseResult<ExprGreen<'a>> {
1643        // TODO(yuval): support paths starting with "::".
1644        match self.peek().kind {
1645            SyntaxKind::TerminalIdentifier | SyntaxKind::TerminalDollar => {
1646                // Call parse_path() and not expect_path(), because it's cheap.
1647                let path = self.parse_path();
1648                match self.peek().kind {
1649                    SyntaxKind::TerminalLParen => Ok(self.expect_function_call(path).into()),
1650                    SyntaxKind::TerminalLBrace if lbrace_allowed == LbraceAllowed::Allow => {
1651                        Ok(self.expect_constructor_call(path).into())
1652                    }
1653                    SyntaxKind::TerminalNot => Ok(self.expect_macro_call(path).into()),
1654                    _ => Ok(path.into()),
1655                }
1656            }
1657            SyntaxKind::TerminalFalse => Ok(self.take::<TerminalFalse<'_>>().into()),
1658            SyntaxKind::TerminalTrue => Ok(self.take::<TerminalTrue<'_>>().into()),
1659            SyntaxKind::TerminalLiteralNumber => Ok(self.take_terminal_literal_number().into()),
1660            SyntaxKind::TerminalShortString => Ok(self.take_terminal_short_string().into()),
1661            SyntaxKind::TerminalString => Ok(self.take_terminal_string().into()),
1662            SyntaxKind::TerminalLParen => {
1663                // Note that LBrace is allowed inside parenthesis, even if `lbrace_allowed` is
1664                // [LbraceAllowed::Forbid].
1665                Ok(self.expect_parenthesized_expr())
1666            }
1667            SyntaxKind::TerminalLBrack => Ok(self.expect_fixed_size_array_expr().into()),
1668            SyntaxKind::TerminalLBrace if lbrace_allowed == LbraceAllowed::Allow => {
1669                Ok(self.parse_block().into())
1670            }
1671            SyntaxKind::TerminalMatch if lbrace_allowed == LbraceAllowed::Allow => {
1672                Ok(self.expect_match_expr().into())
1673            }
1674            SyntaxKind::TerminalIf if lbrace_allowed == LbraceAllowed::Allow => {
1675                Ok(self.expect_if_expr().into())
1676            }
1677            SyntaxKind::TerminalLoop if lbrace_allowed == LbraceAllowed::Allow => {
1678                Ok(self.expect_loop_expr().into())
1679            }
1680            SyntaxKind::TerminalWhile if lbrace_allowed == LbraceAllowed::Allow => {
1681                Ok(self.expect_while_expr().into())
1682            }
1683            SyntaxKind::TerminalFor if lbrace_allowed == LbraceAllowed::Allow => {
1684                Ok(self.expect_for_expr().into())
1685            }
1686            SyntaxKind::TerminalOr if lbrace_allowed == LbraceAllowed::Allow => {
1687                Ok(self.expect_closure_expr_nary().into())
1688            }
1689            SyntaxKind::TerminalOrOr if lbrace_allowed == LbraceAllowed::Allow => {
1690                Ok(self.expect_closure_expr_nullary().into())
1691            }
1692            _ => {
1693                // TODO(yuval): report to diagnostics.
1694                Err(TryParseFailure::SkipToken)
1695            }
1696        }
1697    }
1698
1699    /// Returns a GreenId of a node with an ExprPath|ExprParenthesized|ExprTuple kind, or
1700    /// TryParseFailure if such an expression can't be parsed.
1701    fn try_parse_type_expr(&mut self) -> TryParseResult<ExprGreen<'a>> {
1702        // TODO(yuval): support paths starting with "::".
1703        match self.peek().kind {
1704            SyntaxKind::TerminalAt => {
1705                let op = self.take::<TerminalAt<'_>>().into();
1706                let expr = self.parse_type_expr();
1707                Ok(ExprUnary::new_green(self.db, op, expr).into())
1708            }
1709            SyntaxKind::TerminalIdentifier | SyntaxKind::TerminalDollar => {
1710                Ok(self.parse_type_path().into())
1711            }
1712            SyntaxKind::TerminalLParen => Ok(self.expect_type_tuple_expr()),
1713            SyntaxKind::TerminalLBrack => Ok(self.expect_type_fixed_size_array_expr()),
1714            _ => {
1715                // TODO(yuval): report to diagnostics.
1716                Err(TryParseFailure::SkipToken)
1717            }
1718        }
1719    }
1720
1721    /// Returns a GreenId of a node with an ExprPath|ExprParenthesized|ExprTuple kind, or
1722    /// ExprMissing if such an expression can't be parsed.
1723    fn parse_type_expr(&mut self) -> ExprGreen<'a> {
1724        match self.try_parse_type_expr() {
1725            Ok(expr) => expr,
1726            Err(_) => self
1727                .create_and_report_missing::<Expr<'_>>(ParserDiagnosticKind::MissingTypeExpression),
1728        }
1729    }
1730
1731    /// Assumes the current token is LBrace.
1732    /// Expected pattern: `\{<StructArgList>\}`
1733    fn expect_struct_ctor_argument_list_braced(&mut self) -> StructArgListBracedGreen<'a> {
1734        let lbrace = self.take::<TerminalLBrace<'_>>();
1735        let arg_list = StructArgList::new_green(
1736            self.db,
1737            &self.parse_separated_list::<StructArg<'_>, TerminalComma<'_>, StructArgListElementOrSeparatorGreen<'_>>(
1738                Self::try_parse_struct_ctor_argument,
1739                is_of_kind!(rparen, block, rbrace, module_item_kw),
1740                "struct constructor argument",
1741            ),
1742        );
1743        let rbrace = self.parse_token::<TerminalRBrace<'_>>();
1744
1745        StructArgListBraced::new_green(self.db, lbrace, arg_list, rbrace)
1746    }
1747
1748    /// Assumes the current token is LParen.
1749    /// Expected pattern: `<ArgListParenthesized>`
1750    fn expect_function_call(&mut self, path: ExprPathGreen<'a>) -> ExprFunctionCallGreen<'a> {
1751        let func_name = path;
1752        let parenthesized_args = self.expect_parenthesized_argument_list();
1753        ExprFunctionCall::new_green(self.db, func_name, parenthesized_args)
1754    }
1755
1756    /// Assumes the current token is TerminalNot.
1757    /// Expected pattern: `!<WrappedArgList>`
1758    fn expect_macro_call(&mut self, path: ExprPathGreen<'a>) -> ExprInlineMacroGreen<'a> {
1759        let bang = self.take::<TerminalNot<'_>>();
1760        let macro_name = path;
1761        let token_tree_node = self.parse_token_tree_node();
1762        ExprInlineMacro::new_green(self.db, macro_name, bang, token_tree_node)
1763    }
1764
1765    /// Either parses a leaf of the tree (i.e. any non-parenthesis token) or an inner node (i.e. a
1766    /// parenthesized stream of tokens).
1767    fn parse_token_tree(&mut self) -> TokenTreeGreen<'a> {
1768        match self.peek().kind {
1769            SyntaxKind::TerminalLBrace
1770            | SyntaxKind::TerminalLParen
1771            | SyntaxKind::TerminalLBrack => self.parse_token_tree_node().into(),
1772            SyntaxKind::TerminalDollar => {
1773                let dollar: TerminalDollarGreen<'_> = self.take::<TerminalDollar<'_>>();
1774                match self.peek().kind {
1775                    SyntaxKind::TerminalLParen => {
1776                        let lparen = self.take::<TerminalLParen<'_>>();
1777                        let elements = TokenList::new_green(self.db, &self.parse_token_list());
1778                        let rparen = self.parse_token::<TerminalRParen<'_>>();
1779                        let separator: OptionTerminalCommaGreen<'_> = match self.peek().kind {
1780                            SyntaxKind::TerminalComma => self.take::<TerminalComma<'_>>().into(),
1781                            _ => OptionTerminalCommaEmpty::new_green(self.db).into(),
1782                        };
1783                        let operator = match self.peek().kind {
1784                            SyntaxKind::TerminalQuestionMark => {
1785                                self.take::<TerminalQuestionMark<'_>>().into()
1786                            }
1787                            SyntaxKind::TerminalPlus => self.take::<TerminalPlus<'_>>().into(),
1788                            SyntaxKind::TerminalMul => self.take::<TerminalMul<'_>>().into(),
1789                            _ => unreachable!(),
1790                        };
1791                        TokenTreeRepetition::new_green(
1792                            self.db, dollar, lparen, elements, rparen, separator, operator,
1793                        )
1794                        .into()
1795                    }
1796                    SyntaxKind::TerminalIdentifier => {
1797                        let identifier = self.take::<TerminalIdentifier<'_>>();
1798                        TokenTreeParam::new_green(self.db, dollar, identifier).into()
1799                    }
1800                    _ => self.parse_token_tree_leaf().into(),
1801                }
1802            }
1803            _ => self.parse_token_tree_leaf().into(),
1804        }
1805    }
1806
1807    fn parse_token_tree_leaf(&mut self) -> TokenTreeLeafGreen<'a> {
1808        let token_node = self.take_token_node();
1809        TokenTreeLeaf::new_green(self.db, token_node)
1810    }
1811
1812    fn parse_token_tree_node(&mut self) -> TokenTreeNodeGreen<'a> {
1813        let wrapped_token_tree = match self.peek().kind {
1814            SyntaxKind::TerminalLBrace => self
1815                .expect_wrapped_token_tree::<TerminalLBrace<'_>, TerminalRBrace<'_>, _, _>(
1816                    BracedTokenTree::new_green,
1817                )
1818                .into(),
1819            SyntaxKind::TerminalLParen => self
1820                .expect_wrapped_token_tree::<TerminalLParen<'_>, TerminalRParen<'_>, _, _>(
1821                    ParenthesizedTokenTree::new_green,
1822                )
1823                .into(),
1824            SyntaxKind::TerminalLBrack => self
1825                .expect_wrapped_token_tree::<TerminalLBrack<'_>, TerminalRBrack<'_>, _, _>(
1826                    BracketedTokenTree::new_green,
1827                )
1828                .into(),
1829            _ => {
1830                return self.create_and_report_missing::<TokenTreeNode<'_>>(
1831                    ParserDiagnosticKind::MissingWrappedArgList,
1832                );
1833            }
1834        };
1835        TokenTreeNode::new_green(self.db, wrapped_token_tree)
1836    }
1837
1838    /// Assumes the current token is LTerminal.
1839    /// Expected pattern: `[LTerminal](<expr>,)*<expr>?[RTerminal]`
1840    /// Gets `new_green` a green id node builder for the list of the requested type, applies it to
1841    /// the parsed list and returns the result.
1842    fn expect_wrapped_token_tree<
1843        LTerminal: syntax::node::Terminal<'a>,
1844        RTerminal: syntax::node::Terminal<'a>,
1845        ListGreen,
1846        NewGreen: Fn(&'a dyn Database, LTerminal::Green, TokenListGreen<'a>, RTerminal::Green) -> ListGreen,
1847    >(
1848        &mut self,
1849        new_green: NewGreen,
1850    ) -> ListGreen {
1851        let l_term = self.take::<LTerminal>();
1852        let tokens = self.parse_token_list();
1853        let r_term: <RTerminal as TypedSyntaxNode<'_>>::Green = self.parse_token::<RTerminal>();
1854        new_green(self.db, l_term, TokenList::new_green(self.db, &tokens), r_term)
1855    }
1856
1857    fn parse_token_list(&mut self) -> Vec<TokenTreeGreen<'a>> {
1858        let mut tokens: Vec<TokenTreeGreen<'_>> = vec![];
1859        while !matches!(
1860            self.peek().kind,
1861            SyntaxKind::TerminalRParen
1862                | SyntaxKind::TerminalRBrace
1863                | SyntaxKind::TerminalRBrack
1864                | SyntaxKind::TerminalEndOfFile
1865        ) {
1866            tokens.push(self.parse_token_tree());
1867        }
1868        tokens
1869    }
1870
1871    /// Takes a TokenNode according to the current SyntaxKind.
1872    fn take_token_node(&mut self) -> TokenNodeGreen<'a> {
1873        match self.peek().kind {
1874            SyntaxKind::TerminalIdentifier => self.take::<TerminalIdentifier<'_>>().into(),
1875            SyntaxKind::TerminalLiteralNumber => self.take::<TerminalLiteralNumber<'_>>().into(),
1876            SyntaxKind::TerminalShortString => self.take::<TerminalShortString<'_>>().into(),
1877            SyntaxKind::TerminalString => self.take::<TerminalString<'_>>().into(),
1878            SyntaxKind::TerminalAs => self.take::<TerminalAs<'_>>().into(),
1879            SyntaxKind::TerminalConst => self.take::<TerminalConst<'_>>().into(),
1880            SyntaxKind::TerminalElse => self.take::<TerminalElse<'_>>().into(),
1881            SyntaxKind::TerminalEnum => self.take::<TerminalEnum<'_>>().into(),
1882            SyntaxKind::TerminalExtern => self.take::<TerminalExtern<'_>>().into(),
1883            SyntaxKind::TerminalFalse => self.take::<TerminalFalse<'_>>().into(),
1884            SyntaxKind::TerminalFunction => self.take::<TerminalFunction<'_>>().into(),
1885            SyntaxKind::TerminalIf => self.take::<TerminalIf<'_>>().into(),
1886            SyntaxKind::TerminalWhile => self.take::<TerminalWhile<'_>>().into(),
1887            SyntaxKind::TerminalFor => self.take::<TerminalFor<'_>>().into(),
1888            SyntaxKind::TerminalLoop => self.take::<TerminalLoop<'_>>().into(),
1889            SyntaxKind::TerminalImpl => self.take::<TerminalImpl<'_>>().into(),
1890            SyntaxKind::TerminalImplicits => self.take::<TerminalImplicits<'_>>().into(),
1891            SyntaxKind::TerminalLet => self.take::<TerminalLet<'_>>().into(),
1892            SyntaxKind::TerminalMatch => self.take::<TerminalMatch<'_>>().into(),
1893            SyntaxKind::TerminalModule => self.take::<TerminalModule<'_>>().into(),
1894            SyntaxKind::TerminalMut => self.take::<TerminalMut<'_>>().into(),
1895            SyntaxKind::TerminalNoPanic => self.take::<TerminalNoPanic<'_>>().into(),
1896            SyntaxKind::TerminalOf => self.take::<TerminalOf<'_>>().into(),
1897            SyntaxKind::TerminalRef => self.take::<TerminalRef<'_>>().into(),
1898            SyntaxKind::TerminalContinue => self.take::<TerminalContinue<'_>>().into(),
1899            SyntaxKind::TerminalReturn => self.take::<TerminalReturn<'_>>().into(),
1900            SyntaxKind::TerminalBreak => self.take::<TerminalBreak<'_>>().into(),
1901            SyntaxKind::TerminalStruct => self.take::<TerminalStruct<'_>>().into(),
1902            SyntaxKind::TerminalTrait => self.take::<TerminalTrait<'_>>().into(),
1903            SyntaxKind::TerminalTrue => self.take::<TerminalTrue<'_>>().into(),
1904            SyntaxKind::TerminalType => self.take::<TerminalType<'_>>().into(),
1905            SyntaxKind::TerminalUse => self.take::<TerminalUse<'_>>().into(),
1906            SyntaxKind::TerminalPub => self.take::<TerminalPub<'_>>().into(),
1907            SyntaxKind::TerminalAnd => self.take::<TerminalAnd<'_>>().into(),
1908            SyntaxKind::TerminalAndAnd => self.take::<TerminalAndAnd<'_>>().into(),
1909            SyntaxKind::TerminalArrow => self.take::<TerminalArrow<'_>>().into(),
1910            SyntaxKind::TerminalAt => self.take::<TerminalAt<'_>>().into(),
1911            SyntaxKind::TerminalBadCharacters => self.take::<TerminalBadCharacters<'_>>().into(),
1912            SyntaxKind::TerminalColon => self.take::<TerminalColon<'_>>().into(),
1913            SyntaxKind::TerminalColonColon => self.take::<TerminalColonColon<'_>>().into(),
1914            SyntaxKind::TerminalComma => self.take::<TerminalComma<'_>>().into(),
1915            SyntaxKind::TerminalDiv => self.take::<TerminalDiv<'_>>().into(),
1916            SyntaxKind::TerminalDivEq => self.take::<TerminalDivEq<'_>>().into(),
1917            SyntaxKind::TerminalDollar => self.take::<TerminalDollar<'_>>().into(),
1918            SyntaxKind::TerminalDot => self.take::<TerminalDot<'_>>().into(),
1919            SyntaxKind::TerminalDotDot => self.take::<TerminalDotDot<'_>>().into(),
1920            SyntaxKind::TerminalDotDotEq => self.take::<TerminalDotDotEq<'_>>().into(),
1921            SyntaxKind::TerminalEndOfFile => self.take::<TerminalEndOfFile<'_>>().into(),
1922            SyntaxKind::TerminalEq => self.take::<TerminalEq<'_>>().into(),
1923            SyntaxKind::TerminalEqEq => self.take::<TerminalEqEq<'_>>().into(),
1924            SyntaxKind::TerminalGE => self.take::<TerminalGE<'_>>().into(),
1925            SyntaxKind::TerminalGT => self.take::<TerminalGT<'_>>().into(),
1926            SyntaxKind::TerminalHash => self.take::<TerminalHash<'_>>().into(),
1927            SyntaxKind::TerminalLBrace => self.take::<TerminalLBrace<'_>>().into(),
1928            SyntaxKind::TerminalLBrack => self.take::<TerminalLBrack<'_>>().into(),
1929            SyntaxKind::TerminalLE => self.take::<TerminalLE<'_>>().into(),
1930            SyntaxKind::TerminalLParen => self.take::<TerminalLParen<'_>>().into(),
1931            SyntaxKind::TerminalLT => self.take::<TerminalLT<'_>>().into(),
1932            SyntaxKind::TerminalMatchArrow => self.take::<TerminalMatchArrow<'_>>().into(),
1933            SyntaxKind::TerminalMinus => self.take::<TerminalMinus<'_>>().into(),
1934            SyntaxKind::TerminalMinusEq => self.take::<TerminalMinusEq<'_>>().into(),
1935            SyntaxKind::TerminalMod => self.take::<TerminalMod<'_>>().into(),
1936            SyntaxKind::TerminalModEq => self.take::<TerminalModEq<'_>>().into(),
1937            SyntaxKind::TerminalMul => self.take::<TerminalMul<'_>>().into(),
1938            SyntaxKind::TerminalMulEq => self.take::<TerminalMulEq<'_>>().into(),
1939            SyntaxKind::TerminalNeq => self.take::<TerminalNeq<'_>>().into(),
1940            SyntaxKind::TerminalNot => self.take::<TerminalNot<'_>>().into(),
1941            SyntaxKind::TerminalBitNot => self.take::<TerminalBitNot<'_>>().into(),
1942            SyntaxKind::TerminalOr => self.take::<TerminalOr<'_>>().into(),
1943            SyntaxKind::TerminalOrOr => self.take::<TerminalOrOr<'_>>().into(),
1944            SyntaxKind::TerminalPlus => self.take::<TerminalPlus<'_>>().into(),
1945            SyntaxKind::TerminalPlusEq => self.take::<TerminalPlusEq<'_>>().into(),
1946            SyntaxKind::TerminalQuestionMark => self.take::<TerminalQuestionMark<'_>>().into(),
1947            SyntaxKind::TerminalRBrace => self.take::<TerminalRBrace<'_>>().into(),
1948            SyntaxKind::TerminalRBrack => self.take::<TerminalRBrack<'_>>().into(),
1949            SyntaxKind::TerminalRParen => self.take::<TerminalRParen<'_>>().into(),
1950            SyntaxKind::TerminalSemicolon => self.take::<TerminalSemicolon<'_>>().into(),
1951            SyntaxKind::TerminalUnderscore => self.take::<TerminalUnderscore<'_>>().into(),
1952            SyntaxKind::TerminalXor => self.take::<TerminalXor<'_>>().into(),
1953            other => unreachable!("Unexpected token kind: {other:?}"),
1954        }
1955    }
1956    /// Returns a GreenId of a node with an ArgListParenthesized|ArgListBracketed|ArgListBraced kind
1957    /// or TryParseFailure if such an argument list can't be parsed.
1958    pub(crate) fn parse_wrapped_arg_list(&mut self) -> WrappedArgListGreen<'a> {
1959        match self.peek().kind {
1960            SyntaxKind::TerminalLParen => self
1961                .expect_wrapped_argument_list::<TerminalLParen<'_>, TerminalRParen<'_>, _, _>(
1962                    ArgListParenthesized::new_green,
1963                )
1964                .into(),
1965            SyntaxKind::TerminalLBrack => self
1966                .expect_wrapped_argument_list::<TerminalLBrack<'_>, TerminalRBrack<'_>, _, _>(
1967                    ArgListBracketed::new_green,
1968                )
1969                .into(),
1970            SyntaxKind::TerminalLBrace => self
1971                .expect_wrapped_argument_list::<TerminalLBrace<'_>, TerminalRBrace<'_>, _, _>(
1972                    ArgListBraced::new_green,
1973                )
1974                .into(),
1975            _ => self.create_and_report_missing::<WrappedArgList<'_>>(
1976                ParserDiagnosticKind::MissingWrappedArgList,
1977            ),
1978        }
1979    }
1980
1981    /// Assumes the current token is LTerminal.
1982    /// Expected pattern: `[LTerminal](<expr>,)*<expr>?[RTerminal]`
1983    /// Gets `new_green` a green id node builder for the list of the requested type, applies it to
1984    /// the parsed list and returns the result.
1985    fn expect_wrapped_argument_list<
1986        LTerminal: syntax::node::Terminal<'a>,
1987        RTerminal: syntax::node::Terminal<'a>,
1988        ListGreen,
1989        NewGreen: Fn(&'a dyn Database, LTerminal::Green, ArgListGreen<'a>, RTerminal::Green) -> ListGreen,
1990    >(
1991        &mut self,
1992        new_green: NewGreen,
1993    ) -> ListGreen {
1994        let l_term = self.take::<LTerminal>();
1995        let exprs: Vec<ArgListElementOrSeparatorGreen<'_>> = self
1996            .parse_separated_list::<Arg<'_>, TerminalComma<'_>, ArgListElementOrSeparatorGreen<'_>>(
1997                Self::try_parse_function_argument,
1998                is_of_kind!(rparen, rbrace, rbrack, block, module_item_kw),
1999                "argument",
2000            );
2001        let r_term: <RTerminal as TypedSyntaxNode<'_>>::Green = self.parse_token::<RTerminal>();
2002        new_green(self.db, l_term, ArgList::new_green(self.db, &exprs), r_term)
2003    }
2004
2005    /// Assumes the current token is LParen.
2006    /// Expected pattern: `\(<ArgList>\)`
2007    fn expect_parenthesized_argument_list(&mut self) -> ArgListParenthesizedGreen<'a> {
2008        self.expect_wrapped_argument_list::<TerminalLParen<'_>, TerminalRParen<'_>, _, _>(
2009            ArgListParenthesized::new_green,
2010        )
2011    }
2012
2013    /// Tries to parse parenthesized argument list.
2014    /// Expected pattern: `\(<ArgList>\)`
2015    fn try_parse_parenthesized_argument_list(&mut self) -> OptionArgListParenthesizedGreen<'a> {
2016        if self.peek().kind == SyntaxKind::TerminalLParen {
2017            self.expect_parenthesized_argument_list().into()
2018        } else {
2019            OptionArgListParenthesizedEmpty::new_green(self.db).into()
2020        }
2021    }
2022
2023    /// Parses a function call's argument, which contains possibly modifiers, and a argument clause.
2024    fn try_parse_function_argument(&mut self) -> TryParseResult<ArgGreen<'a>> {
2025        let modifiers_list = self.parse_modifier_list();
2026        let arg_clause = self.try_parse_argument_clause();
2027        match arg_clause {
2028            Ok(arg_clause) => {
2029                let modifiers = ModifierList::new_green(self.db, &modifiers_list);
2030                Ok(Arg::new_green(self.db, modifiers, arg_clause))
2031            }
2032            Err(_) if !modifiers_list.is_empty() => {
2033                let modifiers = ModifierList::new_green(self.db, &modifiers_list);
2034                let arg_clause = ArgClauseUnnamed::new_green(self.db, self.parse_expr()).into();
2035                Ok(Arg::new_green(self.db, modifiers, arg_clause))
2036            }
2037            Err(err) => Err(err),
2038        }
2039    }
2040
2041    /// Parses a function call's argument, which is an expression with or without the name
2042    /// of the argument.
2043    ///
2044    /// Possible patterns:
2045    /// * `<Expr>` (unnamed).
2046    /// * `<Identifier>: <Expr>` (named).
2047    /// * `:<Identifier>` (Field init shorthand - syntactic sugar for `a: a`).
2048    fn try_parse_argument_clause(&mut self) -> TryParseResult<ArgClauseGreen<'a>> {
2049        if self.peek().kind == SyntaxKind::TerminalColon {
2050            let colon = self.take::<TerminalColon<'_>>();
2051            let name = self.parse_identifier();
2052            return Ok(ArgClauseFieldInitShorthand::new_green(
2053                self.db,
2054                colon,
2055                ExprFieldInitShorthand::new_green(self.db, name),
2056            )
2057            .into());
2058        }
2059
2060        // Read an expression.
2061        let value = self.try_parse_expr()?;
2062        // If the next token is `:` and the expression is an identifier, this is the argument's
2063        // name.
2064        Ok(
2065            if self.peek().kind == SyntaxKind::TerminalColon
2066                && let Some(argname) = self.try_extract_identifier(value)
2067            {
2068                let colon = self.take::<TerminalColon<'_>>();
2069                let expr = self.parse_expr();
2070                ArgClauseNamed::new_green(self.db, argname, colon, expr).into()
2071            } else {
2072                ArgClauseUnnamed::new_green(self.db, value).into()
2073            },
2074        )
2075    }
2076
2077    /// If the given `expr` is a simple identifier, returns the corresponding green node.
2078    /// Otherwise, returns `TryParseFailure`.
2079    fn try_extract_identifier(&self, expr: ExprGreen<'a>) -> Option<TerminalIdentifierGreen<'a>> {
2080        // Check that `expr` is `ExprPath`.
2081        let GreenNode {
2082            kind: SyntaxKind::ExprPath,
2083            details: GreenNodeDetails::Node { children: children0, .. },
2084        } = expr.0.long(self.db)
2085        else {
2086            return None;
2087        };
2088
2089        // Extract ExprPathInner
2090        let [_dollar, path_inner] = children0[..] else {
2091            return None;
2092        };
2093
2094        let GreenNode {
2095            kind: SyntaxKind::ExprPathInner,
2096            details: GreenNodeDetails::Node { children: children1, .. },
2097        } = path_inner.long(self.db)
2098        else {
2099            return None;
2100        };
2101
2102        // Check that it has one child.
2103        let [path_segment] = children1[..] else {
2104            return None;
2105        };
2106
2107        // Check that `path_segment` is `PathSegmentSimple`.
2108        let GreenNode {
2109            kind: SyntaxKind::PathSegmentSimple,
2110            details: GreenNodeDetails::Node { children: children2, .. },
2111        } = path_segment.long(self.db)
2112        else {
2113            return None;
2114        };
2115
2116        // Check that it has one child.
2117        let [ident] = children2[..] else {
2118            return None;
2119        };
2120
2121        // Check that it is indeed `TerminalIdentifier`.
2122        let GreenNode { kind: SyntaxKind::TerminalIdentifier, .. } = ident.long(self.db) else {
2123            return None;
2124        };
2125
2126        Some(TerminalIdentifierGreen(ident))
2127    }
2128
2129    /// Assumes the current token is LBrace.
2130    /// Expected pattern: `<StructArgListBraced>`
2131    fn expect_constructor_call(&mut self, path: ExprPathGreen<'a>) -> ExprStructCtorCallGreen<'a> {
2132        let ctor_name = path;
2133        let args = self.expect_struct_ctor_argument_list_braced();
2134        ExprStructCtorCall::new_green(self.db, ctor_name, args)
2135    }
2136
2137    /// Assumes the current token is LParen.
2138    /// Expected pattern: `\((<expr>,)*<expr>?\)`
2139    /// Returns a GreenId of a node with kind ExprParenthesized|ExprTuple.
2140    fn expect_parenthesized_expr(&mut self) -> ExprGreen<'a> {
2141        let lparen = self.take::<TerminalLParen<'_>>();
2142        let exprs: Vec<ExprListElementOrSeparatorGreen<'_>> = self
2143            .parse_separated_list::<Expr<'_>, TerminalComma<'_>, ExprListElementOrSeparatorGreen<'_>>(
2144                Self::try_parse_expr,
2145                is_of_kind!(rparen, block, rbrace, module_item_kw),
2146                "expression",
2147            );
2148        let rparen = self.parse_token::<TerminalRParen<'_>>();
2149
2150        if let [ExprListElementOrSeparatorGreen::Element(expr)] = &exprs[..] {
2151            // We have exactly one item and no separator --> This is not a tuple.
2152            ExprParenthesized::new_green(self.db, lparen, *expr, rparen).into()
2153        } else {
2154            ExprListParenthesized::new_green(
2155                self.db,
2156                lparen,
2157                ExprList::new_green(self.db, &exprs),
2158                rparen,
2159            )
2160            .into()
2161        }
2162    }
2163
2164    /// Assumes the current token is LParen.
2165    /// Expected pattern: `\((<type_expr>,)*<type_expr>?\)`
2166    /// Returns a GreenId of a node with kind ExprTuple.
2167    fn expect_type_tuple_expr(&mut self) -> ExprGreen<'a> {
2168        let lparen = self.take::<TerminalLParen<'_>>();
2169        let exprs: Vec<ExprListElementOrSeparatorGreen<'_>> = self
2170            .parse_separated_list::<Expr<'_>, TerminalComma<'_>, ExprListElementOrSeparatorGreen<'_>>(
2171                Self::try_parse_type_expr,
2172                is_of_kind!(rparen, block, rbrace, module_item_kw),
2173                "type expression",
2174            );
2175        let rparen = self.parse_token::<TerminalRParen<'_>>();
2176        if let [ExprListElementOrSeparatorGreen::Element(_)] = &exprs[..] {
2177            self.add_diagnostic(
2178                ParserDiagnosticKind::MissingToken(SyntaxKind::TokenComma),
2179                TextSpan::cursor(self.offset),
2180            );
2181        }
2182        ExprListParenthesized::new_green(
2183            self.db,
2184            lparen,
2185            ExprList::new_green(self.db, &exprs),
2186            rparen,
2187        )
2188        .into()
2189    }
2190
2191    /// Assumes the current token is LBrack.
2192    /// Expected pattern: `\[<type_expr>; <expr>\]`.
2193    /// Returns a GreenId of a node with kind ExprFixedSizeArray.
2194    fn expect_type_fixed_size_array_expr(&mut self) -> ExprGreen<'a> {
2195        let lbrack = self.take::<TerminalLBrack<'_>>();
2196        let exprs: Vec<ExprListElementOrSeparatorGreen<'_>> = self
2197            .parse_separated_list::<Expr<'_>, TerminalComma<'_>, ExprListElementOrSeparatorGreen<'_>>(
2198                Self::try_parse_type_expr,
2199                is_of_kind!(rbrack, semicolon),
2200                "type expression",
2201            );
2202        let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
2203        let size_expr = self.parse_expr();
2204        let fixed_size_array_size =
2205            FixedSizeArraySize::new_green(self.db, semicolon, size_expr).into();
2206        let rbrack = self.parse_token::<TerminalRBrack<'_>>();
2207        ExprFixedSizeArray::new_green(
2208            self.db,
2209            lbrack,
2210            ExprList::new_green(self.db, &exprs),
2211            fixed_size_array_size,
2212            rbrack,
2213        )
2214        .into()
2215    }
2216
2217    /// Assumes the current token is DotDot.
2218    /// Expected pattern: `\.\.<Expr>`
2219    fn expect_struct_argument_tail(&mut self) -> StructArgTailGreen<'a> {
2220        let dotdot = self.take::<TerminalDotDot<'_>>(); // ..
2221        // TODO(yuval): consider changing this to SimpleExpr once it exists.
2222        let expr = self.parse_expr();
2223        StructArgTail::new_green(self.db, dotdot, expr)
2224    }
2225
2226    // For the similar syntax in Rust, see
2227    // https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax.
2228    /// Like parse_argument, but also allows a struct-arg-tail, e.g. 'let s2 = S{"s2", ..s1};'
2229    /// Returns a GreenId of a node with kind StructArgSingle|StructArgTail.
2230    fn try_parse_struct_ctor_argument(&mut self) -> TryParseResult<StructArgGreen<'a>> {
2231        match self.peek().kind {
2232            SyntaxKind::TerminalDotDot => Ok(self.expect_struct_argument_tail().into()),
2233            _ => self.try_parse_argument_single().map(|arg| arg.into()),
2234        }
2235    }
2236
2237    /// Returns a GreenId of a node with kind StructArgExpr or OptionStructArgExprEmpty if an
2238    /// argument expression `(":<value>")` can't be parsed.
2239    fn parse_option_struct_arg_expression(&mut self) -> OptionStructArgExprGreen<'a> {
2240        if self.peek().kind == SyntaxKind::TerminalColon {
2241            let colon = self.take::<TerminalColon<'_>>();
2242            let value = self.parse_expr();
2243            StructArgExpr::new_green(self.db, colon, value).into()
2244        } else {
2245            OptionStructArgExprEmpty::new_green(self.db).into()
2246        }
2247    }
2248
2249    /// Returns a GreenId of a node with kind OptionExprClause or OptionExprClauseEmpty if an
2250    /// argument expression `("Expr")` can't be parsed.
2251    fn parse_option_expression_clause(&mut self) -> OptionExprClauseGreen<'a> {
2252        if self.peek().kind == SyntaxKind::TerminalSemicolon {
2253            OptionExprClauseEmpty::new_green(self.db).into()
2254        } else {
2255            let value = self.parse_expr();
2256            ExprClause::new_green(self.db, value).into()
2257        }
2258    }
2259
2260    /// Returns a GreenId of a node with kind StructArgSingle.
2261    fn try_parse_argument_single(&mut self) -> TryParseResult<StructArgSingleGreen<'a>> {
2262        let identifier = self.try_parse_identifier()?;
2263        let struct_arg_expr = self.parse_option_struct_arg_expression(); // :<expr>
2264        Ok(StructArgSingle::new_green(self.db, identifier, struct_arg_expr))
2265    }
2266
2267    /// Returns a GreenId of a node with kind ExprBlock.
2268    fn parse_block(&mut self) -> ExprBlockGreen<'a> {
2269        let skipped_tokens = self.skip_until(is_of_kind!(rbrace, lbrace, module_item_kw, block));
2270
2271        if let Err(SkippedError(span)) = skipped_tokens {
2272            self.add_diagnostic(
2273                ParserDiagnosticKind::SkippedElement { element_name: "'{'".into() },
2274                span,
2275            );
2276        }
2277
2278        let is_rbrace_or_top_level = is_of_kind!(rbrace, module_item_kw);
2279        if is_rbrace_or_top_level(self.peek().kind) {
2280            return ExprBlock::new_green(
2281                self.db,
2282                self.create_and_report_missing_terminal::<TerminalLBrace<'_>>(),
2283                StatementList::new_green(self.db, &[]),
2284                TerminalRBrace::missing(self.db),
2285            );
2286        }
2287        // Don't report diagnostic if one has already been reported.
2288        let lbrace = self.parse_token_ex::<TerminalLBrace<'_>>(skipped_tokens.is_ok());
2289        let statements = StatementList::new_green(
2290            self.db,
2291            &self.parse_list(
2292                Self::try_parse_statement,
2293                is_of_kind!(rbrace, module_item_kw),
2294                "statement",
2295            ),
2296        );
2297        let rbrace = self.parse_token::<TerminalRBrace<'_>>();
2298        ExprBlock::new_green(self.db, lbrace, statements, rbrace)
2299    }
2300
2301    /// Assumes the current token is `Match`.
2302    /// Expected pattern: `match <expr> \{<MatchArm>*\}`
2303    fn expect_match_expr(&mut self) -> ExprMatchGreen<'a> {
2304        let match_kw = self.take::<TerminalMatch<'_>>();
2305        let expr =
2306            self.parse_expr_limited(MAX_PRECEDENCE, LbraceAllowed::Forbid, AndLetBehavior::Simple);
2307        let lbrace = self.parse_token::<TerminalLBrace<'_>>();
2308        let arms = MatchArms::new_green(
2309            self.db,
2310            &self
2311                .parse_separated_list::<MatchArm<'_>, TerminalComma<'_>, MatchArmsElementOrSeparatorGreen<'_>>(
2312                    Self::try_parse_match_arm,
2313                    is_of_kind!(block, rbrace, module_item_kw),
2314                    "match arm",
2315                ),
2316        );
2317        let rbrace = self.parse_token::<TerminalRBrace<'_>>();
2318        ExprMatch::new_green(self.db, match_kw, expr, lbrace, arms, rbrace)
2319    }
2320
2321    /// Assumes the current token is `If`.
2322    fn expect_if_expr(&mut self) -> ExprIfGreen<'a> {
2323        let if_kw = self.take::<TerminalIf<'a>>();
2324
2325        let conditions = self.parse_condition_list();
2326        let if_block = self.parse_block();
2327        let else_clause = if self.peek().kind == SyntaxKind::TerminalElse {
2328            let else_kw = self.take::<TerminalElse<'a>>();
2329            let else_block_or_if = if self.peek().kind == SyntaxKind::TerminalIf {
2330                self.expect_if_expr().into()
2331            } else {
2332                self.parse_block().into()
2333            };
2334            ElseClause::new_green(self.db, else_kw, else_block_or_if).into()
2335        } else {
2336            OptionElseClauseEmpty::new_green(self.db).into()
2337        };
2338        ExprIf::new_green(self.db, if_kw, conditions, if_block, else_clause)
2339    }
2340
2341    /// If `condition` is a [ConditionExpr] of the form `<expr> <op> <expr>`, returns the operator's
2342    /// kind.
2343    /// Otherwise, returns `None`.
2344    fn get_binary_operator(&self, condition: ConditionGreen<'_>) -> Option<SyntaxKind> {
2345        let condition_expr_green = condition.0.long(self.db);
2346        require(condition_expr_green.kind == SyntaxKind::ConditionExpr)?;
2347
2348        let expr_binary_green = condition_expr_green.children()[0].long(self.db);
2349        require(expr_binary_green.kind == SyntaxKind::ExprBinary)?;
2350
2351        Some(expr_binary_green.children()[1].long(self.db).kind)
2352    }
2353
2354    /// Parses a conjunction of conditions of the form `<condition> && <condition> && ...`,
2355    /// where each condition is either `<expr>` or `let <pattern> = <expr>`.
2356    ///
2357    /// Assumes the next expected token (after the condition list) is `{`. This assumption is used
2358    /// in case of an error.
2359    fn parse_condition_list(&mut self) -> ConditionListAndGreen<'a> {
2360        let and_and_precedence = get_post_operator_precedence(SyntaxKind::TerminalAndAnd).unwrap();
2361
2362        let start_offset = self.offset.add_width(self.current_width);
2363        let condition = self.parse_condition_expr(false);
2364        let mut conditions: Vec<ConditionListAndElementOrSeparatorGreen<'_>> =
2365            vec![condition.into()];
2366
2367        // If there is more than one condition, check that the first condition does not have a
2368        // precedence lower than `&&`.
2369        if self.peek().kind == SyntaxKind::TerminalAndAnd
2370            && let Some(op) = self.get_binary_operator(condition)
2371            && let Some(precedence) = get_post_operator_precedence(op)
2372            && precedence > and_and_precedence
2373        {
2374            let offset = self.offset.add_width(self.current_width - self.last_trivia_length);
2375            self.add_diagnostic(
2376                ParserDiagnosticKind::LowPrecedenceOperatorInIfLet { op },
2377                TextSpan::new(start_offset, offset),
2378            );
2379        }
2380
2381        while self.peek().kind == SyntaxKind::TerminalAndAnd {
2382            let and_and = self.take::<TerminalAndAnd<'a>>();
2383            conditions.push(and_and.into());
2384
2385            let condition = self.parse_condition_expr(true);
2386            conditions.push(condition.into());
2387        }
2388
2389        let peek_item = self.peek();
2390        if let Some(op_precedence) = get_post_operator_precedence(peek_item.kind)
2391            && op_precedence > and_and_precedence
2392        {
2393            self.add_diagnostic(
2394                ParserDiagnosticKind::LowPrecedenceOperatorInIfLet { op: peek_item.kind },
2395                TextSpan::cursor(self.offset.add_width(self.current_width)),
2396            );
2397            // Skip the rest of the tokens until `{`. Don't report additional diagnostics.
2398            let _ = self.skip_until(is_of_kind!(rbrace, lbrace, module_item_kw, block));
2399        }
2400        ConditionListAnd::new_green(self.db, &conditions)
2401    }
2402
2403    /// Parses condition exprs of the form `<expr>` or `let <pattern> = <expr>`.
2404    ///
2405    /// In the case of `let <pattern> = <expr>`, the parser will stop at the first `&&` token
2406    /// (which is not inside parenthesis).
2407    /// If `stop_at_and` is true, this will also be the case for `<expr>`.
2408    fn parse_condition_expr(&mut self, stop_at_and: bool) -> ConditionGreen<'a> {
2409        let and_and_precedence = get_post_operator_precedence(SyntaxKind::TerminalAndAnd).unwrap();
2410        if self.peek().kind == SyntaxKind::TerminalLet {
2411            let let_kw = self.take::<TerminalLet<'a>>();
2412            let pattern_list = self
2413            .parse_separated_list_inner::<Pattern<'_>, TerminalOr<'_>, PatternListOrElementOrSeparatorGreen<'_>>(
2414                Self::try_parse_pattern,
2415                is_of_kind!(eq),
2416                "pattern",
2417                Some(ParserDiagnosticKind::DisallowedTrailingSeparatorOr),
2418            );
2419
2420            let pattern_list_green = if pattern_list.is_empty() {
2421                self.create_and_report_missing::<PatternListOr<'_>>(
2422                    ParserDiagnosticKind::MissingPattern,
2423                )
2424            } else {
2425                PatternListOr::new_green(self.db, &pattern_list)
2426            };
2427            let eq = self.parse_token::<TerminalEq<'a>>();
2428            let expr: ExprGreen<'_> = self.parse_expr_limited(
2429                and_and_precedence,
2430                LbraceAllowed::Forbid,
2431                AndLetBehavior::Stop,
2432            );
2433            ConditionLet::new_green(self.db, let_kw, pattern_list_green, eq, expr).into()
2434        } else {
2435            let condition = self.parse_expr_limited(
2436                if stop_at_and { and_and_precedence } else { MAX_PRECEDENCE },
2437                LbraceAllowed::Forbid,
2438                AndLetBehavior::Stop,
2439            );
2440            ConditionExpr::new_green(self.db, condition).into()
2441        }
2442    }
2443
2444    /// Assumes the current token is `Loop`.
2445    /// Expected pattern: `loop <block>`.
2446    fn expect_loop_expr(&mut self) -> ExprLoopGreen<'a> {
2447        let loop_kw = self.take::<TerminalLoop<'a>>();
2448        let body = self.parse_block();
2449
2450        ExprLoop::new_green(self.db, loop_kw, body)
2451    }
2452
2453    /// Assumes the current token is `While`.
2454    /// Expected pattern: `while <condition> <block>`.
2455    fn expect_while_expr(&mut self) -> ExprWhileGreen<'a> {
2456        let while_kw = self.take::<TerminalWhile<'a>>();
2457        let conditions = self.parse_condition_list();
2458        let body = self.parse_block();
2459
2460        ExprWhile::new_green(self.db, while_kw, conditions, body)
2461    }
2462
2463    /// Assumes the current token is `For`.
2464    /// Expected pattern: `for <pattern> <identifier> <expression> <block>`.
2465    /// Identifier will be checked to be 'in' in semantics.
2466    fn expect_for_expr(&mut self) -> ExprForGreen<'a> {
2467        let for_kw = self.take::<TerminalFor<'a>>();
2468        let pattern = self.parse_pattern();
2469        let ident = self.take_raw();
2470        let in_identifier: TerminalIdentifierGreen<'_> = match ident.text.long(self.db).as_str() {
2471            "in" => self.add_trivia_to_terminal::<TerminalIdentifier<'_>>(ident),
2472            _ => {
2473                self.append_skipped_token_to_pending_trivia(
2474                    ident,
2475                    ParserDiagnosticKind::SkippedElement { element_name: "'in'".into() },
2476                );
2477                TerminalIdentifier::missing(self.db)
2478            }
2479        };
2480        let expression =
2481            self.parse_expr_limited(MAX_PRECEDENCE, LbraceAllowed::Forbid, AndLetBehavior::Simple);
2482        let body = self.parse_block();
2483        ExprFor::new_green(self.db, for_kw, pattern, in_identifier, expression, body)
2484    }
2485
2486    /// Assumes the current token is `|`.
2487    /// Expected pattern: `| <params> | <ReturnTypeClause> <expression>`.
2488    fn expect_closure_expr_nary(&mut self) -> ExprClosureGreen<'a> {
2489        let leftor = self.take::<TerminalOr<'a>>();
2490        let params = self.parse_closure_param_list();
2491        let rightor = self.parse_token::<TerminalOr<'a>>();
2492
2493        self.parse_closure_expr_body(
2494            ClosureParamWrapperNAry::new_green(self.db, leftor, params, rightor).into(),
2495        )
2496    }
2497    /// Assumes the current token is `||`.
2498    /// Expected pattern: `|| <ReturnTypeClause> <expression> `.
2499    fn expect_closure_expr_nullary(&mut self) -> ExprClosureGreen<'a> {
2500        let wrapper = self.take::<TerminalOrOr<'a>>().into();
2501        self.parse_closure_expr_body(wrapper)
2502    }
2503    fn parse_closure_expr_body(
2504        &mut self,
2505        wrapper: ClosureParamWrapperGreen<'a>,
2506    ) -> ExprClosureGreen<'a> {
2507        let mut block_required = self.peek().kind == SyntaxKind::TerminalArrow;
2508
2509        let return_type_clause = self.parse_option_return_type_clause();
2510        let optional_no_panic = if self.peek().kind == SyntaxKind::TerminalNoPanic {
2511            block_required = true;
2512            self.take::<TerminalNoPanic<'a>>().into()
2513        } else {
2514            OptionTerminalNoPanicEmpty::new_green(self.db).into()
2515        };
2516        let expr = if block_required { self.parse_block().into() } else { self.parse_expr() };
2517
2518        ExprClosure::new_green(self.db, wrapper, return_type_clause, optional_no_panic, expr)
2519    }
2520
2521    /// Assumes the current token is LBrack.
2522    /// Expected pattern: `\[<expr>; <expr>\]`.
2523    fn expect_fixed_size_array_expr(&mut self) -> ExprFixedSizeArrayGreen<'a> {
2524        let lbrack = self.take::<TerminalLBrack<'_>>();
2525        let exprs: Vec<ExprListElementOrSeparatorGreen<'_>> = self
2526            .parse_separated_list::<Expr<'_>, TerminalComma<'_>, ExprListElementOrSeparatorGreen<'_>>(
2527                Self::try_parse_expr,
2528                is_of_kind!(rbrack, semicolon),
2529                "expression",
2530            );
2531        let size_green = if self.peek().kind == SyntaxKind::TerminalSemicolon {
2532            let semicolon = self.take::<TerminalSemicolon<'_>>();
2533            let size = self.parse_expr();
2534            FixedSizeArraySize::new_green(self.db, semicolon, size).into()
2535        } else {
2536            OptionFixedSizeArraySizeEmpty::new_green(self.db).into()
2537        };
2538        let rbrack = self.parse_token::<TerminalRBrack<'_>>();
2539        ExprFixedSizeArray::new_green(
2540            self.db,
2541            lbrack,
2542            ExprList::new_green(self.db, &exprs),
2543            size_green,
2544            rbrack,
2545        )
2546    }
2547
2548    /// Returns a GreenId of a node with a MatchArm kind or TryParseFailure if a match arm can't be
2549    /// parsed.
2550    pub fn try_parse_match_arm(&mut self) -> TryParseResult<MatchArmGreen<'a>> {
2551        let pattern_list = self
2552            .parse_separated_list_inner::<Pattern<'_>, TerminalOr<'_>, PatternListOrElementOrSeparatorGreen<'_>>(
2553                Self::try_parse_pattern,
2554                is_of_kind!(match_arrow, rparen, block, rbrace, module_item_kw),
2555                "pattern",
2556                Some(ParserDiagnosticKind::DisallowedTrailingSeparatorOr),
2557            );
2558        if pattern_list.is_empty() {
2559            return Err(TryParseFailure::SkipToken);
2560        }
2561
2562        let pattern_list_green = PatternListOr::new_green(self.db, &pattern_list);
2563
2564        let arrow = self.parse_token::<TerminalMatchArrow<'_>>();
2565        let expr = self.parse_expr();
2566        Ok(MatchArm::new_green(self.db, pattern_list_green, arrow, expr))
2567    }
2568
2569    /// Returns a GreenId of a node with some Pattern kind (see
2570    /// [syntax::node::ast::Pattern]) or TryParseFailure if a pattern can't be parsed.
2571    fn try_parse_pattern(&mut self) -> TryParseResult<PatternGreen<'a>> {
2572        let modifier_list = self.parse_modifier_list();
2573        if !modifier_list.is_empty() {
2574            let modifiers = ModifierList::new_green(self.db, &modifier_list);
2575            let name = self.parse_identifier();
2576            return Ok(PatternIdentifier::new_green(self.db, modifiers, name).into());
2577        };
2578
2579        // TODO(yuval): Support "Or" patterns.
2580        Ok(match self.peek().kind {
2581            SyntaxKind::TerminalLiteralNumber => self.take_terminal_literal_number().into(),
2582            SyntaxKind::TerminalShortString => self.take_terminal_short_string().into(),
2583            SyntaxKind::TerminalTrue => self.take::<TerminalTrue<'_>>().into(),
2584            SyntaxKind::TerminalFalse => self.take::<TerminalFalse<'_>>().into(),
2585            SyntaxKind::TerminalUnderscore => self.take::<TerminalUnderscore<'_>>().into(),
2586            SyntaxKind::TerminalIdentifier => {
2587                // TODO(ilya): Consider parsing a single identifier as PatternIdentifier rather
2588                // then ExprPath.
2589                let path = self.parse_path();
2590                match self.peek().kind {
2591                    SyntaxKind::TerminalLBrace => {
2592                        let lbrace = self.take::<TerminalLBrace<'_>>();
2593                        let params = PatternStructParamList::new_green(
2594                            self.db,
2595                            &self.parse_separated_list::<
2596                                PatternStructParam<'_>,
2597                                TerminalComma<'_>,
2598                                PatternStructParamListElementOrSeparatorGreen<'_>>
2599                            (
2600                                Self::try_parse_pattern_struct_param,
2601                                is_of_kind!(rparen, block, rbrace, module_item_kw),
2602                                "struct pattern parameter",
2603                            ),
2604                        );
2605                        let rbrace = self.parse_token::<TerminalRBrace<'_>>();
2606                        PatternStruct::new_green(self.db, path, lbrace, params, rbrace).into()
2607                    }
2608                    SyntaxKind::TerminalLParen => {
2609                        // Enum pattern.
2610                        let lparen = self.take::<TerminalLParen<'_>>();
2611                        let pattern = self.parse_pattern();
2612                        let rparen = self.parse_token::<TerminalRParen<'_>>();
2613                        let inner_pattern =
2614                            PatternEnumInnerPattern::new_green(self.db, lparen, pattern, rparen);
2615                        PatternEnum::new_green(self.db, path, inner_pattern.into()).into()
2616                    }
2617                    _ => {
2618                        // Check that `expr` is `ExprPath`.
2619                        let GreenNode {
2620                            kind: SyntaxKind::ExprPath,
2621                            details: GreenNodeDetails::Node { children: path_children, .. },
2622                        } = path.0.long(self.db)
2623                        else {
2624                            return Err(TryParseFailure::SkipToken);
2625                        };
2626
2627                        // Extract ExprPathInner
2628                        let [_dollar, path_inner] = path_children[..] else {
2629                            return Err(TryParseFailure::SkipToken);
2630                        };
2631
2632                        let GreenNode {
2633                            kind: SyntaxKind::ExprPathInner,
2634                            details: GreenNodeDetails::Node { children: inner_path_children, .. },
2635                        } = path_inner.long(self.db)
2636                        else {
2637                            return Err(TryParseFailure::SkipToken);
2638                        };
2639
2640                        // If the path has more than 1 element assume it's a simplified Enum variant
2641                        // Eg. MyEnum::A(()) ~ MyEnum::A
2642                        // Multi-element path identifiers aren't allowed, for now this mechanism is
2643                        // sufficient.
2644                        match inner_path_children.len() {
2645                            // 0 => return None, - unreachable
2646                            1 => path.into(),
2647                            _ => PatternEnum::new_green(
2648                                self.db,
2649                                path,
2650                                OptionPatternEnumInnerPatternEmpty::new_green(self.db).into(),
2651                            )
2652                            .into(),
2653                        }
2654                    }
2655                }
2656            }
2657            SyntaxKind::TerminalLParen => {
2658                let lparen = self.take::<TerminalLParen<'_>>();
2659                let patterns = PatternList::new_green(self.db,  &self.parse_separated_list::<
2660                    Pattern<'_>,
2661                    TerminalComma<'_>,
2662                    PatternListElementOrSeparatorGreen<'_>>
2663                (
2664                    Self::try_parse_pattern,
2665                    is_of_kind!(rparen, block, rbrace, module_item_kw),
2666                    "pattern",
2667                ));
2668                let rparen = self.parse_token::<TerminalRParen<'_>>();
2669                PatternTuple::new_green(self.db, lparen, patterns, rparen).into()
2670            }
2671            SyntaxKind::TerminalLBrack => {
2672                let lbrack = self.take::<TerminalLBrack<'_>>();
2673                let patterns = PatternList::new_green(self.db,  &self.parse_separated_list::<
2674                    Pattern<'_>,
2675                    TerminalComma<'_>,
2676                    PatternListElementOrSeparatorGreen<'_>>
2677                (
2678                    Self::try_parse_pattern,
2679                    is_of_kind!(rbrack, block, rbrace, module_item_kw),
2680                    "pattern",
2681                ));
2682                let rbrack = self.parse_token::<TerminalRBrack<'_>>();
2683                PatternFixedSizeArray::new_green(self.db, lbrack, patterns, rbrack).into()
2684            }
2685            _ => return Err(TryParseFailure::SkipToken),
2686        })
2687    }
2688    /// Returns a GreenId of a node with some Pattern kind (see
2689    /// [syntax::node::ast::Pattern]).
2690    fn parse_pattern(&mut self) -> PatternGreen<'a> {
2691        // If not found, return a missing underscore pattern.
2692        match self.try_parse_pattern() {
2693            Ok(pattern) => pattern,
2694            Err(_) => self.create_and_report_missing_terminal::<TerminalUnderscore<'_>>().into(),
2695        }
2696    }
2697
2698    /// Returns a GreenId of a syntax inside a struct pattern. Example:
2699    /// `MyStruct { param0, param1: _, .. }`.
2700    fn try_parse_pattern_struct_param(&mut self) -> TryParseResult<PatternStructParamGreen<'a>> {
2701        Ok(match self.peek().kind {
2702            SyntaxKind::TerminalDotDot => self.take::<TerminalDotDot<'_>>().into(),
2703            _ => {
2704                let modifier_list = self.parse_modifier_list();
2705                let name = if modifier_list.is_empty() {
2706                    self.try_parse_identifier()?
2707                } else {
2708                    self.parse_identifier()
2709                };
2710                let modifiers = ModifierList::new_green(self.db, &modifier_list);
2711                if self.peek().kind == SyntaxKind::TerminalColon {
2712                    let colon = self.take::<TerminalColon<'_>>();
2713                    let pattern = self.parse_pattern();
2714                    PatternStructParamWithExpr::new_green(self.db, modifiers, name, colon, pattern)
2715                        .into()
2716                } else {
2717                    PatternIdentifier::new_green(self.db, modifiers, name).into()
2718                }
2719            }
2720        })
2721    }
2722
2723    // ------------------------------- Statements -------------------------------
2724
2725    /// Returns a GreenId of a node with a Statement.* kind (see
2726    /// [syntax::node::ast::Statement]) or TryParseFailure if a statement can't be parsed.
2727    pub fn try_parse_statement(&mut self) -> TryParseResult<StatementGreen<'a>> {
2728        let maybe_attributes = self.try_parse_attribute_list("Statement");
2729        let (has_attrs, attributes) = match maybe_attributes {
2730            Ok(attributes) => (true, attributes),
2731            Err(_) => (false, AttributeList::new_green(self.db, &[])),
2732        };
2733        match self.peek().kind {
2734            SyntaxKind::TerminalLet => {
2735                let let_kw = self.take::<TerminalLet<'_>>();
2736                let pattern = self.parse_pattern();
2737                let type_clause = self.parse_option_type_clause();
2738                let eq = self.parse_token::<TerminalEq<'_>>();
2739                let rhs = self.parse_expr();
2740
2741                // Check if this is a let-else statement.
2742                let let_else_clause: OptionLetElseClauseGreen<'_> =
2743                    if self.peek().kind == SyntaxKind::TerminalElse {
2744                        let else_kw = self.take::<TerminalElse<'_>>();
2745                        let else_block = self.parse_block();
2746                        LetElseClause::new_green(self.db, else_kw, else_block).into()
2747                    } else {
2748                        OptionLetElseClauseEmpty::new_green(self.db).into()
2749                    };
2750
2751                let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
2752                Ok(StatementLet::new_green(
2753                    self.db,
2754                    attributes,
2755                    let_kw,
2756                    pattern,
2757                    type_clause,
2758                    eq,
2759                    rhs,
2760                    let_else_clause,
2761                    semicolon,
2762                )
2763                .into())
2764            }
2765            SyntaxKind::TerminalContinue => {
2766                let continue_kw = self.take::<TerminalContinue<'_>>();
2767                let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
2768                Ok(StatementContinue::new_green(self.db, attributes, continue_kw, semicolon).into())
2769            }
2770            SyntaxKind::TerminalReturn => {
2771                let return_kw = self.take::<TerminalReturn<'_>>();
2772                let expr = self.parse_option_expression_clause();
2773                let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
2774                Ok(StatementReturn::new_green(self.db, attributes, return_kw, expr, semicolon)
2775                    .into())
2776            }
2777            SyntaxKind::TerminalBreak => {
2778                let break_kw = self.take::<TerminalBreak<'_>>();
2779                let expr = self.parse_option_expression_clause();
2780                let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
2781                Ok(StatementBreak::new_green(self.db, attributes, break_kw, expr, semicolon).into())
2782            }
2783            SyntaxKind::TerminalConst => {
2784                let const_kw = self.take::<TerminalConst<'_>>();
2785                Ok(StatementItem::new_green(
2786                    self.db,
2787                    self.expect_item_const(
2788                        attributes,
2789                        VisibilityDefault::new_green(self.db).into(),
2790                        const_kw,
2791                    )
2792                    .into(),
2793                )
2794                .into())
2795            }
2796            SyntaxKind::TerminalUse => Ok(StatementItem::new_green(
2797                self.db,
2798                self.expect_item_use(attributes, VisibilityDefault::new_green(self.db).into())
2799                    .into(),
2800            )
2801            .into()),
2802            SyntaxKind::TerminalType => Ok(StatementItem::new_green(
2803                self.db,
2804                self.expect_item_type_alias(
2805                    attributes,
2806                    VisibilityDefault::new_green(self.db).into(),
2807                )
2808                .into(),
2809            )
2810            .into()),
2811            _ => match self.try_parse_expr() {
2812                Ok(expr) => {
2813                    let optional_semicolon = if self.peek().kind == SyntaxKind::TerminalSemicolon {
2814                        self.take::<TerminalSemicolon<'_>>().into()
2815                    } else {
2816                        OptionTerminalSemicolonEmpty::new_green(self.db).into()
2817                    };
2818                    Ok(StatementExpr::new_green(self.db, attributes, expr, optional_semicolon)
2819                        .into())
2820                }
2821                Err(_) if has_attrs => Ok(self
2822                    .skip_taken_node_and_return_missing::<Statement<'_>>(
2823                        attributes,
2824                        ParserDiagnosticKind::AttributesWithoutStatement,
2825                    )),
2826                Err(err) => Err(err),
2827            },
2828        }
2829    }
2830
2831    /// Returns a GreenId of a node with kind TypeClause or OptionTypeClauseEmpty if a type clause
2832    /// can't be parsed.
2833    fn parse_option_type_clause(&mut self) -> OptionTypeClauseGreen<'a> {
2834        match self.try_parse_type_clause() {
2835            Some(green) => green.into(),
2836            None => OptionTypeClauseEmpty::new_green(self.db).into(),
2837        }
2838    }
2839
2840    /// Parses a type clause of the form: `: <type>`.
2841    fn parse_type_clause(&mut self, error_recovery: ErrorRecovery) -> TypeClauseGreen<'a> {
2842        match self.try_parse_type_clause() {
2843            Some(green) => green,
2844            None => {
2845                let res = self.create_and_report_missing::<TypeClause<'_>>(
2846                    ParserDiagnosticKind::MissingTypeClause,
2847                );
2848                self.skip_until(error_recovery.should_stop).ok();
2849                res
2850            }
2851        }
2852    }
2853    fn try_parse_type_clause(&mut self) -> Option<TypeClauseGreen<'a>> {
2854        if self.peek().kind == SyntaxKind::TerminalColon {
2855            let colon = self.take::<TerminalColon<'_>>();
2856            let ty = self.parse_type_expr();
2857            Some(TypeClause::new_green(self.db, colon, ty))
2858        } else {
2859            None
2860        }
2861    }
2862
2863    /// Returns a GreenId of a node with kind ReturnTypeClause or OptionReturnTypeClauseEmpty if a
2864    /// return type clause can't be parsed.
2865    fn parse_option_return_type_clause(&mut self) -> OptionReturnTypeClauseGreen<'a> {
2866        if self.peek().kind == SyntaxKind::TerminalArrow {
2867            let arrow = self.take::<TerminalArrow<'_>>();
2868            let return_type = self.parse_type_expr();
2869            ReturnTypeClause::new_green(self.db, arrow, return_type).into()
2870        } else {
2871            OptionReturnTypeClauseEmpty::new_green(self.db).into()
2872        }
2873    }
2874
2875    /// Returns a GreenId of a node with kind ImplicitsClause or OptionImplicitsClauseEmpty if a
2876    /// implicits-clause can't be parsed.
2877    fn parse_option_implicits_clause(&mut self) -> OptionImplicitsClauseGreen<'a> {
2878        if self.peek().kind == SyntaxKind::TerminalImplicits {
2879            let implicits_kw = self.take::<TerminalImplicits<'_>>();
2880            let lparen = self.parse_token::<TerminalLParen<'_>>();
2881            let implicits = ImplicitsList::new_green(
2882                self.db,
2883                &self.parse_separated_list::<ExprPath<'_>, TerminalComma<'_>, ImplicitsListElementOrSeparatorGreen<'_>>(
2884                    Self::try_parse_path,
2885                    // Don't stop at keywords as try_parse_path handles keywords inside it. Otherwise the diagnostic is less accurate.
2886                    is_of_kind!(rparen, lbrace, rbrace),
2887                    "implicit type",
2888                ),
2889            );
2890            let rparen = self.parse_token::<TerminalRParen<'_>>();
2891            ImplicitsClause::new_green(self.db, implicits_kw, lparen, implicits, rparen).into()
2892        } else {
2893            OptionImplicitsClauseEmpty::new_green(self.db).into()
2894        }
2895    }
2896
2897    /// Returns a GreenId of a node with kind ParamList.
2898    fn parse_param_list(&mut self) -> ParamListGreen<'a> {
2899        ParamList::new_green(
2900            self.db,
2901            &self.parse_separated_list::<Param<'_>, TerminalComma<'_>, ParamListElementOrSeparatorGreen<'_>>(
2902                Self::try_parse_param,
2903                is_of_kind!(rparen, block, lbrace, rbrace, module_item_kw),
2904                "parameter",
2905            ),
2906        )
2907    }
2908
2909    /// Returns a GreenId of a node with kind ClosureParamList.
2910    fn parse_closure_param_list(&mut self) -> ParamListGreen<'a> {
2911        ParamList::new_green(
2912            self.db,
2913            &self.parse_separated_list::<Param<'_>, TerminalComma<'_>, ParamListElementOrSeparatorGreen<'_>>(
2914                Self::try_parse_closure_param,
2915                is_of_kind!(or, block, lbrace, rbrace, module_item_kw),
2916                "parameter",
2917            ),
2918        )
2919    }
2920
2921    /// Returns a GreenId of a node with kind Modifier or TryParseFailure if a modifier can't be
2922    /// parsed.
2923    fn try_parse_modifier(&mut self) -> Option<ModifierGreen<'a>> {
2924        match self.peek().kind {
2925            SyntaxKind::TerminalRef => Some(self.take::<TerminalRef<'_>>().into()),
2926            SyntaxKind::TerminalMut => Some(self.take::<TerminalMut<'_>>().into()),
2927            _ => None,
2928        }
2929    }
2930
2931    /// Returns a vector of GreenIds with kind Modifier.
2932    fn parse_modifier_list(&mut self) -> Vec<ModifierGreen<'a>> {
2933        let mut modifier_list = vec![];
2934
2935        while let Some(modifier) = self.try_parse_modifier() {
2936            modifier_list.push(modifier);
2937        }
2938        modifier_list
2939    }
2940
2941    /// Returns a GreenId of a node with kind Param or TryParseFailure if a parameter can't be
2942    /// parsed.
2943    fn try_parse_param(&mut self) -> TryParseResult<ParamGreen<'a>> {
2944        let modifier_list = self.parse_modifier_list();
2945        let name = if modifier_list.is_empty() {
2946            self.try_parse_identifier()?
2947        } else {
2948            // If we had modifiers then the identifier is not optional and can't be '_'.
2949            self.parse_identifier()
2950        };
2951
2952        let type_clause = self
2953            .parse_type_clause(ErrorRecovery {
2954                should_stop: is_of_kind!(comma, rparen, module_item_kw),
2955            })
2956            .into();
2957        Ok(Param::new_green(
2958            self.db,
2959            ModifierList::new_green(self.db, &modifier_list),
2960            name,
2961            type_clause,
2962        ))
2963    }
2964
2965    /// Returns a GreenId of a node with kind Param or TryParseFailure if a parameter can't
2966    /// be parsed.
2967    fn try_parse_closure_param(&mut self) -> TryParseResult<ParamGreen<'a>> {
2968        let modifier_list = self.parse_modifier_list();
2969        let name = if modifier_list.is_empty() {
2970            self.try_parse_identifier()?
2971        } else {
2972            // If we had modifiers then the identifier is not optional and can't be '_'.
2973            self.parse_identifier()
2974        };
2975
2976        let type_clause = self.parse_option_type_clause();
2977        Ok(Param::new_green(
2978            self.db,
2979            ModifierList::new_green(self.db, &modifier_list),
2980            name,
2981            type_clause,
2982        ))
2983    }
2984
2985    /// Returns a GreenId of a node with kind MemberList.
2986    fn parse_member_list(&mut self) -> MemberListGreen<'a> {
2987        MemberList::new_green(
2988            self.db,
2989            &self.parse_separated_list::<
2990                Member<'_>,
2991                TerminalComma<'_>,
2992                MemberListElementOrSeparatorGreen<'_>,
2993            >(
2994                Self::try_parse_member,
2995                is_of_kind!(rparen, block, lbrace, rbrace, module_item_kw),
2996                "member or variant",
2997            ),
2998        )
2999    }
3000
3001    /// Returns a GreenId of a node with kind Member or TryParseFailure if a struct member can't be
3002    /// parsed.
3003    fn try_parse_member(&mut self) -> TryParseResult<MemberGreen<'a>> {
3004        let attributes = self.try_parse_attribute_list("Struct member");
3005        let visibility = self.parse_visibility();
3006        let (name, attributes) = match attributes {
3007            Ok(attributes) => (self.parse_identifier(), attributes),
3008            Err(_) => (self.try_parse_identifier()?, AttributeList::new_green(self.db, &[])),
3009        };
3010        let type_clause = self.parse_type_clause(ErrorRecovery {
3011            should_stop: is_of_kind!(comma, rbrace, module_item_kw),
3012        });
3013        Ok(Member::new_green(self.db, attributes, visibility, name, type_clause))
3014    }
3015
3016    /// Returns a GreenId of a node with kind VariantList.
3017    fn parse_variant_list(&mut self) -> VariantListGreen<'a> {
3018        VariantList::new_green(
3019            self.db,
3020            &self
3021                .parse_separated_list::<Variant<'_>, TerminalComma<'_>, VariantListElementOrSeparatorGreen<'_>>(
3022                    Self::try_parse_variant,
3023                    is_of_kind!(rparen, block, lbrace, rbrace, module_item_kw),
3024                    "variant",
3025                ),
3026        )
3027    }
3028
3029    /// Returns a GreenId of a node with kind Variant or TryParseFailure if an enum variant can't be
3030    /// parsed.
3031    fn try_parse_variant(&mut self) -> TryParseResult<VariantGreen<'a>> {
3032        let attributes = self.try_parse_attribute_list("Enum variant");
3033        let (name, attributes) = match attributes {
3034            Ok(attributes) => (self.parse_identifier(), attributes),
3035            Err(_) => (self.try_parse_identifier()?, AttributeList::new_green(self.db, &[])),
3036        };
3037
3038        let type_clause = self.parse_option_type_clause();
3039        Ok(Variant::new_green(self.db, attributes, name, type_clause))
3040    }
3041
3042    /// Expected pattern: `<PathSegment>(::<PathSegment>)*`
3043    /// Returns a GreenId of a node with kind ExprPath.
3044    fn parse_path(&mut self) -> ExprPathGreen<'a> {
3045        let dollar = match self.peek().kind {
3046            SyntaxKind::TerminalDollar => self.take::<TerminalDollar<'_>>().into(),
3047            _ => OptionTerminalDollarEmpty::new_green(self.db).into(),
3048        };
3049
3050        let mut children: Vec<ExprPathInnerElementOrSeparatorGreen<'_>> = vec![];
3051        loop {
3052            let (segment, optional_separator) = self.parse_path_segment();
3053            children.push(segment.into());
3054
3055            if let Some(separator) = optional_separator {
3056                children.push(separator.into());
3057                continue;
3058            }
3059            break;
3060        }
3061
3062        ExprPath::new_green(self.db, dollar, ExprPathInner::new_green(self.db, &children))
3063    }
3064    /// Returns a GreenId of a node with kind ExprPath or TryParseFailure if a path can't be parsed.
3065    fn try_parse_path(&mut self) -> TryParseResult<ExprPathGreen<'a>> {
3066        if self.is_peek_identifier_like() {
3067            Ok(self.parse_path())
3068        } else {
3069            Err(TryParseFailure::SkipToken)
3070        }
3071    }
3072
3073    /// Expected pattern: `(<PathSegment<'_>>::)*<PathSegment<'_>>(::){0,1}<GenericArgs>`.
3074    ///
3075    /// Returns a GreenId of a node with kind ExprPath.
3076    fn parse_type_path(&mut self) -> ExprPathGreen<'a> {
3077        let dollar = match self.peek().kind {
3078            SyntaxKind::TerminalDollar => self.take::<TerminalDollar<'_>>().into(),
3079            _ => OptionTerminalDollarEmpty::new_green(self.db).into(),
3080        };
3081
3082        let mut children: Vec<ExprPathInnerElementOrSeparatorGreen<'_>> = vec![];
3083        loop {
3084            let (segment, optional_separator) = self.parse_type_path_segment();
3085            children.push(segment.into());
3086
3087            if let Some(separator) = optional_separator {
3088                children.push(separator.into());
3089                continue;
3090            }
3091            break;
3092        }
3093
3094        ExprPath::new_green(self.db, dollar, ExprPathInner::new_green(self.db, &children))
3095    }
3096
3097    /// Returns a PathSegment and an optional separator.
3098    fn parse_path_segment(
3099        &mut self,
3100    ) -> (PathSegmentGreen<'a>, Option<TerminalColonColonGreen<'a>>) {
3101        let identifier = match self.try_parse_identifier() {
3102            Ok(identifier) => identifier,
3103            Err(_) => {
3104                return (
3105                    self.create_and_report_missing::<PathSegment<'_>>(
3106                        ParserDiagnosticKind::MissingPathSegment,
3107                    ),
3108                    // TODO(ilya, 10/10/2022): Should we continue parsing the path here?
3109                    None,
3110                );
3111            }
3112        };
3113        match self.try_parse_token::<TerminalColonColon<'_>>() {
3114            Ok(separator) if self.peek().kind == SyntaxKind::TerminalLT => (
3115                PathSegmentWithGenericArgs::new_green(
3116                    self.db,
3117                    identifier,
3118                    separator.into(),
3119                    self.expect_generic_args(),
3120                )
3121                .into(),
3122                self.try_parse_token::<TerminalColonColon<'_>>().ok(),
3123            ),
3124            optional_separator => {
3125                (PathSegmentSimple::new_green(self.db, identifier).into(), optional_separator.ok())
3126            }
3127        }
3128    }
3129
3130    /// Returns a Typed PathSegment or a normal PathSegment.
3131    /// Additionally returns an optional separators.
3132    fn parse_type_path_segment(
3133        &mut self,
3134    ) -> (PathSegmentGreen<'a>, Option<TerminalColonColonGreen<'a>>) {
3135        let identifier = match self.try_parse_identifier() {
3136            Ok(identifier) => identifier,
3137            Err(_) => {
3138                return (
3139                    self.create_and_report_missing::<PathSegment<'_>>(
3140                        ParserDiagnosticKind::MissingPathSegment,
3141                    ),
3142                    // TODO(ilya, 10/10/2022): Should we continue parsing the path here?
3143                    None,
3144                );
3145            }
3146        };
3147        match self.try_parse_token::<TerminalColonColon<'_>>() {
3148            Err(_) if self.peek().kind == SyntaxKind::TerminalLT => (
3149                PathSegmentWithGenericArgs::new_green(
3150                    self.db,
3151                    identifier,
3152                    OptionTerminalColonColonEmpty::new_green(self.db).into(),
3153                    self.expect_generic_args(),
3154                )
3155                .into(),
3156                None,
3157            ),
3158            // This is here to preserve backwards compatibility.
3159            // This allows Option::<T> to still work after this change.
3160            Ok(separator) if self.peek().kind == SyntaxKind::TerminalLT => (
3161                PathSegmentWithGenericArgs::new_green(
3162                    self.db,
3163                    identifier,
3164                    separator.into(),
3165                    self.expect_generic_args(),
3166                )
3167                .into(),
3168                self.try_parse_token::<TerminalColonColon<'_>>().ok(),
3169            ),
3170            optional_separator => {
3171                (PathSegmentSimple::new_green(self.db, identifier).into(), optional_separator.ok())
3172            }
3173        }
3174    }
3175
3176    /// Takes and validates a TerminalLiteralNumber token.
3177    fn take_terminal_literal_number(&mut self) -> TerminalLiteralNumberGreen<'a> {
3178        let diag = validate_literal_number(self.peek().text.long(self.db));
3179        let green = self.take::<TerminalLiteralNumber<'_>>();
3180        self.add_optional_diagnostic(diag);
3181        green
3182    }
3183
3184    /// Takes and validates a TerminalShortString token.
3185    fn take_terminal_short_string(&mut self) -> TerminalShortStringGreen<'a> {
3186        let diag = validate_short_string(self.peek().text.long(self.db));
3187        let green = self.take::<TerminalShortString<'_>>();
3188        self.add_optional_diagnostic(diag);
3189        green
3190    }
3191
3192    /// Takes and validates a TerminalString token.
3193    fn take_terminal_string(&mut self) -> TerminalStringGreen<'a> {
3194        let diag = validate_string(self.peek().text.long(self.db));
3195        let green = self.take::<TerminalString<'_>>();
3196        self.add_optional_diagnostic(diag);
3197        green
3198    }
3199
3200    /// Adds a diagnostic of kind `kind` if provided, at the current offset.
3201    fn add_optional_diagnostic(&mut self, err: Option<ValidationError>) {
3202        if let Some(err) = err {
3203            let span = match err.location {
3204                ValidationLocation::Full => {
3205                    TextSpan::new_with_width(self.offset, self.current_width)
3206                }
3207                ValidationLocation::After => {
3208                    TextSpan::cursor(self.offset.add_width(self.current_width))
3209                }
3210            };
3211            self.add_diagnostic(err.kind, span);
3212        }
3213    }
3214
3215    /// Returns a GreenId of a node with an
3216    /// ExprLiteral|ExprPath|ExprParenthesized|ExprTuple|ExprUnderscore kind, or TryParseFailure if
3217    /// such an expression can't be parsed.
3218    fn try_parse_generic_arg(&mut self) -> TryParseResult<GenericArgGreen<'a>> {
3219        let expr = match self.peek().kind {
3220            SyntaxKind::TerminalUnderscore => {
3221                let underscore = self.take::<TerminalUnderscore<'_>>().into();
3222                return Ok(GenericArgUnnamed::new_green(self.db, underscore).into());
3223            }
3224            SyntaxKind::TerminalLiteralNumber => self.take_terminal_literal_number().into(),
3225            SyntaxKind::TerminalMinus => {
3226                let op = self.take::<TerminalMinus<'_>>().into();
3227                let expr = self.parse_token::<TerminalLiteralNumber<'_>>().into();
3228                ExprUnary::new_green(self.db, op, expr).into()
3229            }
3230            SyntaxKind::TerminalShortString => self.take_terminal_short_string().into(),
3231            SyntaxKind::TerminalTrue => self.take::<TerminalTrue<'_>>().into(),
3232            SyntaxKind::TerminalFalse => self.take::<TerminalFalse<'_>>().into(),
3233            SyntaxKind::TerminalLBrace => self.parse_block().into(),
3234            _ => self.try_parse_type_expr()?,
3235        };
3236
3237        // If the next token is `:` and the expression is an identifier, this is the argument's
3238        // name.
3239        if self.peek().kind == SyntaxKind::TerminalColon
3240            && let Some(argname) = self.try_extract_identifier(expr)
3241        {
3242            let colon = self.take::<TerminalColon<'_>>();
3243            let expr = if self.peek().kind == SyntaxKind::TerminalUnderscore {
3244                self.take::<TerminalUnderscore<'_>>().into()
3245            } else {
3246                let expr = self.parse_type_expr();
3247                GenericArgValueExpr::new_green(self.db, expr).into()
3248            };
3249            return Ok(GenericArgNamed::new_green(self.db, argname, colon, expr).into());
3250        }
3251        Ok(GenericArgUnnamed::new_green(
3252            self.db,
3253            GenericArgValueExpr::new_green(self.db, expr).into(),
3254        )
3255        .into())
3256    }
3257
3258    /// Assumes the current token is LT.
3259    /// Expected pattern: `\< <GenericArgList> \>`
3260    fn expect_generic_args(&mut self) -> GenericArgsGreen<'a> {
3261        let langle = self.take::<TerminalLT<'_>>();
3262        let generic_args = GenericArgList::new_green(
3263            self.db,
3264            &self.parse_separated_list::<GenericArg<'_>, TerminalComma<'_>, GenericArgListElementOrSeparatorGreen<'_>>(
3265                Self::try_parse_generic_arg,
3266                is_of_kind!(rangle, rparen, block, lbrace, rbrace, module_item_kw),
3267                "generic arg",
3268            ),
3269        );
3270        let rangle = self.parse_token::<TerminalGT<'_>>();
3271        GenericArgs::new_green(self.db, langle, generic_args, rangle)
3272    }
3273
3274    /// Assumes the current token is LT.
3275    /// Expected pattern: `\< <GenericParamList> \>`
3276    fn expect_generic_params(&mut self) -> WrappedGenericParamListGreen<'a> {
3277        let langle = self.take::<TerminalLT<'_>>();
3278        let generic_params = GenericParamList::new_green(
3279            self.db,
3280            &self.parse_separated_list::<GenericParam<'_>, TerminalComma<'_>, GenericParamListElementOrSeparatorGreen<'_>>(
3281                Self::try_parse_generic_param,
3282                is_of_kind!(rangle, rparen, block, lbrace, rbrace, module_item_kw),
3283                "generic param",
3284            ),
3285        );
3286        let rangle = self.parse_token::<TerminalGT<'_>>();
3287        WrappedGenericParamList::new_green(self.db, langle, generic_params, rangle)
3288    }
3289
3290    fn parse_optional_generic_params(&mut self) -> OptionWrappedGenericParamListGreen<'a> {
3291        if self.peek().kind != SyntaxKind::TerminalLT {
3292            return OptionWrappedGenericParamListEmpty::new_green(self.db).into();
3293        }
3294        self.expect_generic_params().into()
3295    }
3296
3297    fn try_parse_generic_param(&mut self) -> TryParseResult<GenericParamGreen<'a>> {
3298        match self.peek().kind {
3299            SyntaxKind::TerminalConst => {
3300                let const_kw = self.take::<TerminalConst<'_>>();
3301                let name = self.parse_identifier();
3302                let colon = self.parse_token::<TerminalColon<'_>>();
3303                let ty = self.parse_type_expr();
3304                Ok(GenericParamConst::new_green(self.db, const_kw, name, colon, ty).into())
3305            }
3306            SyntaxKind::TerminalImpl => {
3307                let impl_kw = self.take::<TerminalImpl<'_>>();
3308                let name = self.parse_identifier();
3309                let colon = self.parse_token::<TerminalColon<'_>>();
3310                let trait_path = self.parse_type_path();
3311                let associated_item_constraints = self.parse_optional_associated_item_constraints();
3312                Ok(GenericParamImplNamed::new_green(
3313                    self.db,
3314                    impl_kw,
3315                    name,
3316                    colon,
3317                    trait_path,
3318                    associated_item_constraints,
3319                )
3320                .into())
3321            }
3322            SyntaxKind::TerminalPlus => {
3323                let plus = self.take::<TerminalPlus<'_>>();
3324                let trait_path = self.parse_type_path();
3325                let associated_item_constraints = self.parse_optional_associated_item_constraints();
3326                Ok(GenericParamImplAnonymous::new_green(
3327                    self.db,
3328                    plus,
3329                    trait_path,
3330                    associated_item_constraints,
3331                )
3332                .into())
3333            }
3334            SyntaxKind::TerminalMinus => {
3335                let minus = self.take::<TerminalMinus<'_>>();
3336                let trait_path = self.parse_type_path();
3337                Ok(GenericParamNegativeImpl::new_green(self.db, minus, trait_path).into())
3338            }
3339            _ => Ok(GenericParamType::new_green(self.db, self.try_parse_identifier()?).into()),
3340        }
3341    }
3342
3343    /// Assumes the current token is LBrack.
3344    /// Expected pattern: `[ <associated_item_constraints_list> ]>`
3345    fn expect_associated_item_constraints(&mut self) -> AssociatedItemConstraintsGreen<'a> {
3346        let lbrack = self.take::<TerminalLBrack<'_>>();
3347        let associated_item_constraints_list = AssociatedItemConstraintList::new_green(
3348            self.db,
3349            &self.parse_separated_list::<AssociatedItemConstraint<'_>, TerminalComma<'_>, AssociatedItemConstraintListElementOrSeparatorGreen<'_>>(
3350                Self::try_parse_associated_item_constraint,
3351                is_of_kind!(rbrack,rangle, rparen, block, lbrace, rbrace, module_item_kw),
3352                "associated type argument",
3353            ),
3354        );
3355        let rangle = self.parse_token::<TerminalRBrack<'_>>();
3356        AssociatedItemConstraints::new_green(
3357            self.db,
3358            lbrack,
3359            associated_item_constraints_list,
3360            rangle,
3361        )
3362    }
3363
3364    fn parse_optional_associated_item_constraints(
3365        &mut self,
3366    ) -> OptionAssociatedItemConstraintsGreen<'a> {
3367        if self.peek().kind != SyntaxKind::TerminalLBrack {
3368            return OptionAssociatedItemConstraintsEmpty::new_green(self.db).into();
3369        }
3370        self.expect_associated_item_constraints().into()
3371    }
3372
3373    /// Returns a GreenId of a node with kind AssociatedTypeArg or TryParseFailure if an associated
3374    /// type argument can't be parsed.
3375    fn try_parse_associated_item_constraint(
3376        &mut self,
3377    ) -> TryParseResult<AssociatedItemConstraintGreen<'a>> {
3378        let ident = self.try_parse_identifier()?;
3379        let colon = self.parse_token::<TerminalColon<'_>>();
3380        let ty = self.parse_type_expr();
3381        Ok(AssociatedItemConstraint::new_green(self.db, ident, colon, ty))
3382    }
3383
3384    // ------------------------------- Helpers -------------------------------
3385
3386    /// Parses a list of elements (without separators), where the elements are parsed using
3387    /// `try_parse_list_element`.
3388    /// Returns the list of green ids of the elements.
3389    ///
3390    /// `should_stop` is a predicate to decide how to proceed in case an element can't be parsed,
3391    /// according to the current token. If it returns true, the parsing of the list stops. If it
3392    /// returns false, the current token is skipped and we try to parse an element again.
3393    ///
3394    /// `expected_element` is a description of the expected element.
3395    fn parse_list<ElementGreen>(
3396        &mut self,
3397        try_parse_list_element: fn(&mut Self) -> TryParseResult<ElementGreen>,
3398        should_stop: fn(SyntaxKind) -> bool,
3399        expected_element: &str,
3400    ) -> Vec<ElementGreen> {
3401        let mut children: Vec<ElementGreen> = Vec::new();
3402        loop {
3403            let parse_result = try_parse_list_element(self);
3404            match parse_result {
3405                Ok(element_green) => {
3406                    children.push(element_green);
3407                }
3408                Err(err) => {
3409                    if should_stop(self.peek().kind) {
3410                        break;
3411                    }
3412                    if err == TryParseFailure::SkipToken {
3413                        self.skip_token(ParserDiagnosticKind::SkippedElement {
3414                            element_name: expected_element.into(),
3415                        });
3416                    }
3417                }
3418            }
3419        }
3420        children
3421    }
3422
3423    /// Parses a list of elements (without separators) that can be prefixed with attributes
3424    /// (#[...]), where the elements are parsed using `try_parse_list_element`.
3425    /// Returns the list of green ids of the elements.
3426    ///
3427    /// `should_stop` is a predicate to decide how to proceed in case an element can't be parsed,
3428    /// according to the current token. If it returns true, the parsing of the list stops. If it
3429    /// returns false, the current token is skipped and we try to parse an element again.
3430    ///
3431    /// `expected_element` is a description of the expected element. Note: it should not include
3432    /// "attribute".
3433    fn parse_attributed_list<ElementGreen>(
3434        &mut self,
3435        try_parse_list_element: fn(&mut Self) -> TryParseResult<ElementGreen>,
3436        should_stop: fn(SyntaxKind) -> bool,
3437        expected_element: &'a str,
3438    ) -> Vec<ElementGreen> {
3439        self.parse_list::<ElementGreen>(
3440            try_parse_list_element,
3441            should_stop,
3442            &or_an_attribute!(expected_element),
3443        )
3444    }
3445
3446    /// Parses a list of elements with `separator`s, where the elements are parsed using
3447    /// `try_parse_list_element`. Depending on the value of
3448    /// `forbid_trailing_separator` the separator may or may not appear in
3449    /// the end of the list. Returns the list of elements and separators. This list contains
3450    /// alternating children: [element, separator, element, separator, ...]. Separators may be
3451    /// missing. The length of the list is either 2 * #elements - 1 or 2 * #elements (a
3452    /// separator for each element or for each element but the last one).
3453    ///
3454    /// `should_stop` is a predicate to decide how to proceed in case an element or a separator
3455    /// can't be parsed, according to the current token.
3456    /// When parsing an element:
3457    /// If it returns true, the parsing of the list stops. If it returns false, the current token
3458    /// is skipped and we try to parse an element again.
3459    /// When parsing a separator:
3460    /// If it returns true, the parsing of the list stops. If it returns false, a missing separator
3461    /// is added and we continue to try to parse another element (with the same token).
3462    fn parse_separated_list_inner<
3463        Element: TypedSyntaxNode<'a>,
3464        Separator: syntax::node::Terminal<'a>,
3465        ElementOrSeparatorGreen,
3466    >(
3467        &mut self,
3468        try_parse_list_element: fn(&mut Self) -> TryParseResult<Element::Green>,
3469        should_stop: fn(SyntaxKind) -> bool,
3470        expected_element: &'static str,
3471        forbid_trailing_separator: Option<ParserDiagnosticKind>,
3472    ) -> Vec<ElementOrSeparatorGreen>
3473    where
3474        ElementOrSeparatorGreen: From<Separator::Green> + From<Element::Green>,
3475    {
3476        let mut children: Vec<ElementOrSeparatorGreen> = Vec::new();
3477        loop {
3478            match try_parse_list_element(self) {
3479                Err(_) if should_stop(self.peek().kind) => {
3480                    if let (Some(diagnostic_kind), true) =
3481                        (forbid_trailing_separator, !children.is_empty())
3482                    {
3483                        self.add_diagnostic(diagnostic_kind, TextSpan::cursor(self.offset));
3484                    }
3485                    break;
3486                }
3487                Err(_) => {
3488                    self.skip_token(ParserDiagnosticKind::SkippedElement {
3489                        element_name: expected_element.into(),
3490                    });
3491                    continue;
3492                }
3493                Ok(element) => {
3494                    children.push(element.into());
3495                }
3496            };
3497
3498            let separator = match self.try_parse_token::<Separator>() {
3499                Err(_) if should_stop(self.peek().kind) => {
3500                    break;
3501                }
3502                Err(_) => self.create_and_report_missing::<Separator>(
3503                    ParserDiagnosticKind::MissingToken(Separator::KIND),
3504                ),
3505                Ok(separator) => separator,
3506            };
3507            children.push(separator.into());
3508        }
3509        children
3510    }
3511    /// Calls parse_separated_list_inner with trailing separator enabled.
3512    fn parse_separated_list<
3513        Element: TypedSyntaxNode<'a>,
3514        Separator: syntax::node::Terminal<'a>,
3515        ElementOrSeparatorGreen,
3516    >(
3517        &mut self,
3518        try_parse_list_element: fn(&mut Self) -> TryParseResult<Element::Green>,
3519        should_stop: fn(SyntaxKind) -> bool,
3520        expected_element: &'static str,
3521    ) -> Vec<ElementOrSeparatorGreen>
3522    where
3523        ElementOrSeparatorGreen: From<Separator::Green> + From<Element::Green>,
3524    {
3525        self.parse_separated_list_inner::<Element, Separator, ElementOrSeparatorGreen>(
3526            try_parse_list_element,
3527            should_stop,
3528            expected_element,
3529            None,
3530        )
3531    }
3532
3533    /// Peeks at the next terminal from the Lexer without taking it.
3534    pub fn peek(&self) -> &LexerTerminal<'a> {
3535        self.next_terminal()
3536    }
3537
3538    /// Peeks at the token following the next one.
3539    /// Assumption: the next token is not EOF.
3540    pub fn peek_next_next_kind(&mut self) -> SyntaxKind {
3541        self.next_next_terminal().kind
3542    }
3543
3544    /// Move forward one terminal.
3545    fn take_raw(&mut self) -> LexerTerminal<'a> {
3546        self.offset = self.offset.add_width(self.current_width);
3547        self.current_width = self.next_terminal().width(self.db);
3548        self.last_trivia_length =
3549            trivia_total_width(self.db, &self.next_terminal().trailing_trivia);
3550        self.advance()
3551    }
3552
3553    /// Skips the next, non-taken, token. A skipped token is a token which is not expected where it
3554    /// is found. Skipping this token means reporting an error, appending the token to the
3555    /// current trivia as skipped, and continuing the compilation as if it wasn't there.
3556    fn skip_token(&mut self, diagnostic_kind: ParserDiagnosticKind) {
3557        if self.peek().kind == SyntaxKind::TerminalEndOfFile {
3558            self.add_diagnostic(diagnostic_kind, TextSpan::cursor(self.offset));
3559            return;
3560        }
3561        let terminal = self.take_raw();
3562        self.append_skipped_token_to_pending_trivia(terminal, diagnostic_kind);
3563    }
3564
3565    /// Appends the given terminal to the pending trivia and reports a diagnostic. Used for skipping
3566    /// a taken ('take_raw') token.
3567    fn append_skipped_token_to_pending_trivia(
3568        &mut self,
3569        terminal: LexerTerminal<'a>,
3570        diagnostic_kind: ParserDiagnosticKind,
3571    ) {
3572        let orig_offset = self.offset;
3573        let diag_start =
3574            self.offset.add_width(trivia_total_width(self.db, &terminal.leading_trivia));
3575        let diag_end = diag_start.add_width(TextWidth::from_str(terminal.text.long(self.db)));
3576
3577        // Add to pending trivia.
3578        self.pending_trivia.extend(terminal.leading_trivia);
3579        self.pending_trivia.push(TokenSkipped::new_green(self.db, terminal.text).into());
3580        let trailing_trivia_width = trivia_total_width(self.db, &terminal.trailing_trivia);
3581        self.pending_trivia.extend(terminal.trailing_trivia);
3582        self.pending_skipped_token_diagnostics.push(PendingParserDiagnostic {
3583            kind: diagnostic_kind,
3584            span: TextSpan::new(diag_start, diag_end),
3585            leading_trivia_start: orig_offset,
3586            trailing_trivia_end: diag_end.add_width(trailing_trivia_width),
3587        });
3588    }
3589
3590    /// A wrapper for `skip_taken_node_with_offset` to report the skipped node diagnostic relative
3591    /// to the current offset. Use this when the skipped node is the last node taken.
3592    fn skip_taken_node_from_current_offset(
3593        &mut self,
3594        node_to_skip: impl Into<SkippedNodeGreen<'a>>,
3595        diagnostic_kind: ParserDiagnosticKind,
3596    ) {
3597        self.skip_taken_node_with_offset(
3598            node_to_skip,
3599            diagnostic_kind,
3600            self.offset.add_width(self.current_width),
3601        )
3602    }
3603
3604    /// Skips the given node which is a variant of `SkippedNode` and is already taken. A skipped
3605    /// node is a node which is not expected where it is found. Skipping this node means
3606    /// reporting the given error (pointing to right after the node), appending the node to the
3607    /// current trivia as skipped, and continuing the compilation as if it wasn't there.
3608    /// `end_of_node_offset` is the offset of the end of the skipped node.
3609    fn skip_taken_node_with_offset(
3610        &mut self,
3611        node_to_skip: impl Into<SkippedNodeGreen<'a>>,
3612        diagnostic_kind: ParserDiagnosticKind,
3613        end_of_node_offset: TextOffset,
3614    ) {
3615        let trivium_green = TriviumSkippedNode::new_green(self.db, node_to_skip.into()).into();
3616
3617        // Add to pending trivia.
3618        self.pending_trivia.push(trivium_green);
3619
3620        let start_of_node_offset = end_of_node_offset.sub_width(trivium_green.0.width(self.db));
3621        let diag_pos = end_of_node_offset
3622            .sub_width(trailing_trivia_width(self.db, trivium_green.0).unwrap_or_default());
3623
3624        self.pending_skipped_token_diagnostics.push(PendingParserDiagnostic {
3625            kind: diagnostic_kind,
3626            span: TextSpan::cursor(diag_pos),
3627            leading_trivia_start: start_of_node_offset,
3628            trailing_trivia_end: end_of_node_offset,
3629        });
3630    }
3631
3632    /// Skips the current token, reports the given diagnostic and returns missing kind of the
3633    /// expected terminal.
3634    fn skip_token_and_return_missing<ExpectedTerminal: syntax::node::Terminal<'a>>(
3635        &mut self,
3636        diagnostic: ParserDiagnosticKind,
3637    ) -> ExpectedTerminal::Green {
3638        self.skip_token(diagnostic);
3639        ExpectedTerminal::missing(self.db)
3640    }
3641
3642    /// Skips a given SkippedNode, reports the given diagnostic (pointing to right after the node)
3643    /// and returns missing kind of the expected node.
3644    fn skip_taken_node_and_return_missing<ExpectedNode: TypedSyntaxNode<'a>>(
3645        &mut self,
3646        node_to_skip: impl Into<SkippedNodeGreen<'a>>,
3647        diagnostic_kind: ParserDiagnosticKind,
3648    ) -> ExpectedNode::Green {
3649        self.skip_taken_node_from_current_offset(node_to_skip, diagnostic_kind);
3650        ExpectedNode::missing(self.db)
3651    }
3652
3653    /// Skips terminals until `should_stop` returns `true`.
3654    ///
3655    /// Returns the span of the skipped terminals, if any.
3656    pub(crate) fn skip_until(
3657        &mut self,
3658        should_stop: fn(SyntaxKind) -> bool,
3659    ) -> Result<(), SkippedError> {
3660        let mut diag_start = None;
3661        let mut diag_end = None;
3662        while !should_stop(self.peek().kind) {
3663            let terminal = self.take_raw();
3664            diag_start.get_or_insert(self.offset);
3665            diag_end =
3666                Some(self.offset.add_width(TextWidth::from_str(terminal.text.long(self.db))));
3667
3668            self.pending_trivia.extend(terminal.leading_trivia);
3669            self.pending_trivia.push(TokenSkipped::new_green(self.db, terminal.text).into());
3670            self.pending_trivia.extend(terminal.trailing_trivia);
3671        }
3672        if let (Some(diag_start), Some(diag_end)) = (diag_start, diag_end) {
3673            Err(SkippedError(TextSpan::new(diag_start, diag_end)))
3674        } else {
3675            Ok(())
3676        }
3677    }
3678
3679    /// Builds a new terminal to replace the given terminal by gluing the recently skipped terminals
3680    /// to the given terminal as extra leading trivia.
3681    fn add_trivia_to_terminal<Terminal: syntax::node::Terminal<'a>>(
3682        &mut self,
3683        lexer_terminal: LexerTerminal<'a>,
3684    ) -> Terminal::Green {
3685        let LexerTerminal { text, kind: _, leading_trivia, trailing_trivia } = lexer_terminal;
3686        let token = Terminal::TokenType::new_green(self.db, text);
3687        let mut new_leading_trivia = mem::take(&mut self.pending_trivia);
3688
3689        self.consume_pending_skipped_diagnostics();
3690
3691        new_leading_trivia.extend(leading_trivia);
3692        Terminal::new_green(
3693            self.db,
3694            Trivia::new_green(self.db, &new_leading_trivia),
3695            token,
3696            Trivia::new_green(self.db, &trailing_trivia),
3697        )
3698    }
3699
3700    /// Adds the pending skipped-tokens diagnostics, merging consecutive similar ones, and reset
3701    /// self.pending_skipped_token_diagnostics.
3702    fn consume_pending_skipped_diagnostics(&mut self) {
3703        let mut pending_skipped = self.pending_skipped_token_diagnostics.drain(..);
3704        let Some(first) = pending_skipped.next() else {
3705            return;
3706        };
3707
3708        let mut current_diag = first;
3709
3710        for diag in pending_skipped {
3711            if diag.kind == current_diag.kind
3712                && current_diag.trailing_trivia_end == diag.leading_trivia_start
3713            {
3714                // Aggregate this diagnostic with the previous ones.
3715                current_diag = PendingParserDiagnostic {
3716                    span: TextSpan::new(current_diag.span.start, diag.span.end),
3717                    kind: diag.kind,
3718                    leading_trivia_start: current_diag.leading_trivia_start,
3719                    trailing_trivia_end: diag.trailing_trivia_end,
3720                };
3721            } else {
3722                // Produce a diagnostic from the aggregated ones, and start aggregating a new
3723                // diagnostic.
3724                self.diagnostics.add(ParserDiagnostic {
3725                    file_id: self.file_id,
3726                    span: current_diag.span,
3727                    kind: current_diag.kind,
3728                });
3729                current_diag = diag;
3730            }
3731        }
3732        // Produce a diagnostic from the aggregated ones at the end.
3733        self.add_diagnostic(current_diag.kind, current_diag.span);
3734    }
3735
3736    /// Takes a token from the Lexer and place it in self.current. If tokens were skipped, glue them
3737    /// to this token as leading trivia.
3738    pub fn take<Terminal: syntax::node::Terminal<'a>>(&mut self) -> Terminal::Green {
3739        let token = self.take_raw();
3740        assert_eq!(token.kind, Terminal::KIND);
3741        self.add_trivia_to_terminal::<Terminal>(token)
3742    }
3743
3744    /// If the current leading trivia start with non-doc comments, creates a new `ItemHeaderDoc` and
3745    /// appends the trivia to it. The purpose of this item is to prevent non-doc comments moving
3746    /// from the top of the file formatter.
3747    fn take_doc(&mut self) -> Option<ItemHeaderDocGreen<'a>> {
3748        // Take all the trivia from `self.next_terminal`, until a doc-comment is found. If the
3749        // result does not contain a non-doc comment (i.e. regular comment or inner
3750        // comment), return None and do not change the next terminal leading trivia.
3751        let mut has_header_doc = false;
3752        let mut split_index = 0;
3753        for trivium in &self.next_terminal().leading_trivia {
3754            match trivium.0.long(self.db).kind {
3755                SyntaxKind::TokenSingleLineComment | SyntaxKind::TokenSingleLineInnerComment => {
3756                    has_header_doc = true;
3757                }
3758                SyntaxKind::TokenSingleLineDocComment => {
3759                    break;
3760                }
3761                _ => {}
3762            }
3763            split_index += 1;
3764        }
3765        if !has_header_doc {
3766            return None;
3767        }
3768        // Split the trivia into header doc and the rest.
3769        let header_doc = {
3770            let next_mut = self.next_terminal_mut();
3771            let leading_trivia = next_mut.leading_trivia.split_off(split_index);
3772            std::mem::replace(&mut next_mut.leading_trivia, leading_trivia)
3773        };
3774        let empty_text_id = SmolStrId::from(self.db, "");
3775        let empty_lexer_terminal = LexerTerminal {
3776            text: empty_text_id,
3777            kind: SyntaxKind::TerminalEmpty,
3778            leading_trivia: header_doc,
3779            trailing_trivia: vec![],
3780        };
3781        self.offset = self.offset.add_width(empty_lexer_terminal.width(self.db));
3782
3783        let empty_terminal = self.add_trivia_to_terminal::<TerminalEmpty<'_>>(empty_lexer_terminal);
3784        Some(ItemHeaderDoc::new_green(self.db, empty_terminal))
3785    }
3786
3787    /// If the current terminal is of kind `Terminal`, returns its Green wrapper. Otherwise, returns
3788    /// TryParseFailure.
3789    /// Note that this function should not be called for 'TerminalIdentifier' -
3790    /// try_parse_identifier() should be used instead.
3791    fn try_parse_token<Terminal: syntax::node::Terminal<'a>>(
3792        &mut self,
3793    ) -> TryParseResult<Terminal::Green> {
3794        if Terminal::KIND == self.peek().kind {
3795            Ok(self.take::<Terminal>())
3796        } else {
3797            Err(TryParseFailure::SkipToken)
3798        }
3799    }
3800
3801    /// If the current token is of kind `token_kind`, returns a GreenId of a node with this kind.
3802    /// Otherwise, returns Token::Missing.
3803    ///
3804    /// Note that this function should not be called for 'TerminalIdentifier' - parse_identifier()
3805    /// should be used instead.
3806    fn parse_token<Terminal: syntax::node::Terminal<'a>>(&mut self) -> Terminal::Green {
3807        self.parse_token_ex::<Terminal>(true)
3808    }
3809
3810    /// Same as [Self::parse_token], except that the diagnostic may be omitted.
3811    fn parse_token_ex<Terminal: syntax::node::Terminal<'a>>(
3812        &mut self,
3813        report_diagnostic: bool,
3814    ) -> Terminal::Green {
3815        match self.try_parse_token::<Terminal>() {
3816            Ok(green) => green,
3817            Err(_) => {
3818                if report_diagnostic {
3819                    self.create_and_report_missing_terminal::<Terminal>()
3820                } else {
3821                    Terminal::missing(self.db)
3822                }
3823            }
3824        }
3825    }
3826}
3827
3828/// Controls whether Lbrace (`{`) is allowed in the expression.
3829///
3830/// Lbrace is always allowed in sub-expressions (e.g. in parenthesized expression). For example,
3831/// while `1 + MyStruct { ... }` may not be valid, `1 + (MyStruct { ... })` is always ok.
3832///
3833/// This can be used to parse the argument of a `match` statement,
3834/// so that the `{` that opens the `match` body is not confused with other potential uses of
3835/// `{`.
3836#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3837enum LbraceAllowed {
3838    Forbid,
3839    Allow,
3840}
3841
3842/// Controls the behavior of the parser when encountering `&& let` tokens.
3843#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3844enum AndLetBehavior {
3845    /// Parse without special handling of `&& let`.
3846    Simple,
3847    /// Stop parsing an expression at `&& let` and return the expression so far.
3848    Stop,
3849}
3850
3851/// Indicates that [Parser::skip_until] skipped some terminals.
3852pub(crate) struct SkippedError(pub(crate) TextSpan);
3853
3854/// Defines the parser behavior in the case of a parsing error.
3855struct ErrorRecovery {
3856    /// In the case of a parsing error, tokens will be skipped until `should_stop`
3857    /// returns `true`. For example, one can stop at tokens such as `,` and `}`.
3858    should_stop: fn(SyntaxKind) -> bool,
3859}
3860
3861enum ExternItem<'a> {
3862    Function(ItemExternFunctionGreen<'a>),
3863    Type(ItemExternTypeGreen<'a>),
3864}
3865
3866#[derive(Debug)]
3867enum ImplItemOrAlias<'a> {
3868    Item(ItemImplGreen<'a>),
3869    Alias(ItemImplAliasGreen<'a>),
3870}
3871
3872/// A parser diagnostic that is not yet reported as it is accumulated with similar consecutive
3873/// diagnostics.
3874pub struct PendingParserDiagnostic {
3875    pub span: TextSpan,
3876    pub kind: ParserDiagnosticKind,
3877    pub leading_trivia_start: TextOffset,
3878    pub trailing_trivia_end: TextOffset,
3879}
3880
3881/// Returns the total width of the given trivia list.
3882fn trivia_total_width(db: &dyn Database, trivia: &[TriviumGreen<'_>]) -> TextWidth {
3883    trivia.iter().map(|trivium| trivium.0.width(db)).sum::<TextWidth>()
3884}
3885
3886/// The width of the trailing trivia, traversing the tree to the bottom right node.
3887fn trailing_trivia_width(db: &dyn Database, green_id: GreenId<'_>) -> Option<TextWidth> {
3888    let node = green_id.long(db);
3889    if node.kind == SyntaxKind::Trivia {
3890        return Some(node.width(db));
3891    }
3892    match &node.details {
3893        GreenNodeDetails::Token(_) => Some(TextWidth::default()),
3894        GreenNodeDetails::Node { children, .. } => {
3895            for child in children.iter().rev() {
3896                if let Some(width) = trailing_trivia_width(db, *child) {
3897                    return Some(width);
3898                }
3899            }
3900            None
3901        }
3902    }
3903}