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 one 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_* function.
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 that 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 TryParseResult. An `Ok` with a green ID with a kind
111// that represents 'something' or an `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 returns 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 produces 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 an 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::TerminalAnd | SyntaxKind::TerminalAndAnd => {
1507                self.unglue_andand_for_unary();
1508                self.take::<TerminalAnd<'_>>().into()
1509            }
1510            SyntaxKind::TerminalNot => self.take::<TerminalNot<'_>>().into(),
1511            SyntaxKind::TerminalBitNot => self.take::<TerminalBitNot<'_>>().into(),
1512            SyntaxKind::TerminalMinus => self.take::<TerminalMinus<'_>>().into(),
1513            SyntaxKind::TerminalMul => self.take::<TerminalMul<'_>>().into(),
1514            _ => unreachable!(),
1515        }
1516    }
1517
1518    /// Checks if the current token is a relational or equality operator (`<`, `>`, `<=`, `>=`,
1519    /// `==`, or `!=`).
1520    ///
1521    /// This function is used to determine if the given `SyntaxKind` represents a relational or
1522    /// equality operator, which is commonly used in binary expressions.
1523    ///
1524    /// # Parameters:
1525    /// - `kind`: The `SyntaxKind` of the current token.
1526    ///
1527    /// # Returns:
1528    /// `true` if the token is a relational or equality operator, otherwise `false`.
1529    fn is_comparison_operator(&self, kind: SyntaxKind) -> bool {
1530        matches!(
1531            kind,
1532            SyntaxKind::TerminalLT
1533                | SyntaxKind::TerminalGT
1534                | SyntaxKind::TerminalLE
1535                | SyntaxKind::TerminalGE
1536                | SyntaxKind::TerminalEqEq
1537                | SyntaxKind::TerminalNeq
1538        )
1539    }
1540
1541    /// Returns a GreenId of a node with an Expr.* kind (see [syntax::node::ast::Expr])
1542    /// or TryParseFailure if such an expression can't be parsed.
1543    ///
1544    /// Parsing will be limited by:
1545    /// `parent_precedence` - parsing of binary operators limited to this.
1546    /// `lbrace_allowed` - See [LbraceAllowed].
1547    fn try_parse_expr_limited(
1548        &mut self,
1549        parent_precedence: usize,
1550        lbrace_allowed: LbraceAllowed,
1551        and_let_behavior: AndLetBehavior,
1552    ) -> TryParseResult<ExprGreen<'a>> {
1553        let mut expr = self.try_parse_atom_or_unary(lbrace_allowed)?;
1554        let mut child_op: Option<SyntaxKind> = None;
1555        loop {
1556            let peeked_kind = self.peek().kind;
1557            let Some(precedence) = get_post_operator_precedence(peeked_kind) else {
1558                return Ok(expr);
1559            };
1560            if precedence >= parent_precedence {
1561                return Ok(expr);
1562            }
1563            expr = match peeked_kind {
1564                // If the next two tokens are `&& let` (part of a let-chain), then they should be
1565                // parsed by the caller. Return immediately.
1566                SyntaxKind::TerminalAndAnd
1567                    if and_let_behavior == AndLetBehavior::Stop
1568                        && self.peek_next_next_kind() == SyntaxKind::TerminalLet =>
1569                {
1570                    return Ok(expr);
1571                }
1572                SyntaxKind::TerminalQuestionMark => ExprErrorPropagate::new_green(
1573                    self.db,
1574                    expr,
1575                    self.take::<TerminalQuestionMark<'_>>(),
1576                )
1577                .into(),
1578                SyntaxKind::TerminalLBrack => {
1579                    let lbrack = self.take::<TerminalLBrack<'_>>();
1580                    let index_expr = self.parse_expr();
1581                    let rbrack = self.parse_token::<TerminalRBrack<'_>>();
1582                    ExprIndexed::new_green(self.db, expr, lbrack, index_expr, rbrack).into()
1583                }
1584                current_op => {
1585                    if let Some(child_op_kind) = child_op
1586                        && self.is_comparison_operator(child_op_kind)
1587                        && self.is_comparison_operator(current_op)
1588                    {
1589                        self.add_diagnostic(
1590                            ParserDiagnosticKind::ConsecutiveMathOperators {
1591                                first_op: child_op_kind,
1592                                second_op: current_op,
1593                            },
1594                            TextSpan::cursor(self.offset.add_width(self.current_width)),
1595                        );
1596                    }
1597                    child_op = Some(current_op);
1598                    let op = self.parse_binary_operator();
1599                    let rhs = self.parse_expr_limited(precedence, lbrace_allowed, and_let_behavior);
1600                    ExprBinary::new_green(self.db, expr, op, rhs).into()
1601                }
1602            };
1603        }
1604    }
1605
1606    /// Returns a GreenId of a node with ExprPath, ExprFunctionCall, ExprStructCtorCall,
1607    /// ExprParenthesized, ExprTuple or ExprUnary kind, or TryParseFailure if such an expression
1608    /// can't be parsed.
1609    ///
1610    /// `lbrace_allowed` - See [LbraceAllowed].
1611    fn try_parse_atom_or_unary(
1612        &mut self,
1613        lbrace_allowed: LbraceAllowed,
1614    ) -> TryParseResult<ExprGreen<'a>> {
1615        let Some(precedence) = get_unary_operator_precedence(self.peek().kind) else {
1616            return self.try_parse_atom(lbrace_allowed);
1617        };
1618        let op = self.expect_unary_operator();
1619        let expr = self.parse_expr_limited(precedence, lbrace_allowed, AndLetBehavior::Simple);
1620        Ok(ExprUnary::new_green(self.db, op, expr).into())
1621    }
1622
1623    /// Returns a GreenId of a node with an Expr.* kind (see [syntax::node::ast::Expr]),
1624    /// excluding ExprBlock, or ExprMissing if such an expression can't be parsed.
1625    ///
1626    /// `lbrace_allowed` - See [LbraceAllowed].
1627    fn parse_expr_limited(
1628        &mut self,
1629        parent_precedence: usize,
1630        lbrace_allowed: LbraceAllowed,
1631        and_let_behavior: AndLetBehavior,
1632    ) -> ExprGreen<'a> {
1633        match self.try_parse_expr_limited(parent_precedence, lbrace_allowed, and_let_behavior) {
1634            Ok(green) => green,
1635            Err(_) => {
1636                self.create_and_report_missing::<Expr<'_>>(ParserDiagnosticKind::MissingExpression)
1637            }
1638        }
1639    }
1640
1641    /// Returns a GreenId of a node with an
1642    /// ExprPath|ExprFunctionCall|ExprStructCtorCall|ExprParenthesized|ExprTuple kind, or
1643    /// TryParseFailure if such an expression can't be parsed.
1644    ///
1645    /// `lbrace_allowed` - See [LbraceAllowed].
1646    fn try_parse_atom(&mut self, lbrace_allowed: LbraceAllowed) -> TryParseResult<ExprGreen<'a>> {
1647        // TODO(yuval): support paths starting with "::".
1648        match self.peek().kind {
1649            SyntaxKind::TerminalIdentifier | SyntaxKind::TerminalDollar => {
1650                // Call parse_path() and not expect_path(), because it's cheap.
1651                let path = self.parse_path();
1652                match self.peek().kind {
1653                    SyntaxKind::TerminalLParen => Ok(self.expect_function_call(path).into()),
1654                    SyntaxKind::TerminalLBrace if lbrace_allowed == LbraceAllowed::Allow => {
1655                        Ok(self.expect_constructor_call(path).into())
1656                    }
1657                    SyntaxKind::TerminalNot => Ok(self.expect_macro_call(path).into()),
1658                    _ => Ok(path.into()),
1659                }
1660            }
1661            SyntaxKind::TerminalFalse => Ok(self.take::<TerminalFalse<'_>>().into()),
1662            SyntaxKind::TerminalTrue => Ok(self.take::<TerminalTrue<'_>>().into()),
1663            SyntaxKind::TerminalLiteralNumber => Ok(self.take_terminal_literal_number().into()),
1664            SyntaxKind::TerminalShortString => Ok(self.take_terminal_short_string().into()),
1665            SyntaxKind::TerminalString => Ok(self.take_terminal_string().into()),
1666            SyntaxKind::TerminalLParen => {
1667                // Note that LBrace is allowed inside parenthesis, even if `lbrace_allowed` is
1668                // [LbraceAllowed::Forbid].
1669                Ok(self.expect_parenthesized_expr())
1670            }
1671            SyntaxKind::TerminalLBrack => Ok(self.expect_fixed_size_array_expr().into()),
1672            SyntaxKind::TerminalLBrace if lbrace_allowed == LbraceAllowed::Allow => {
1673                Ok(self.parse_block().into())
1674            }
1675            SyntaxKind::TerminalMatch if lbrace_allowed == LbraceAllowed::Allow => {
1676                Ok(self.expect_match_expr().into())
1677            }
1678            SyntaxKind::TerminalIf if lbrace_allowed == LbraceAllowed::Allow => {
1679                Ok(self.expect_if_expr().into())
1680            }
1681            SyntaxKind::TerminalLoop if lbrace_allowed == LbraceAllowed::Allow => {
1682                Ok(self.expect_loop_expr().into())
1683            }
1684            SyntaxKind::TerminalWhile if lbrace_allowed == LbraceAllowed::Allow => {
1685                Ok(self.expect_while_expr().into())
1686            }
1687            SyntaxKind::TerminalFor if lbrace_allowed == LbraceAllowed::Allow => {
1688                Ok(self.expect_for_expr().into())
1689            }
1690            SyntaxKind::TerminalOr | SyntaxKind::TerminalOrOr
1691                if lbrace_allowed == LbraceAllowed::Allow =>
1692            {
1693                Ok(self.expect_closure_expr().into())
1694            }
1695            _ => {
1696                // TODO(yuval): report to diagnostics.
1697                Err(TryParseFailure::SkipToken)
1698            }
1699        }
1700    }
1701
1702    /// Returns a GreenId of a node with an ExprPath|ExprParenthesized|ExprTuple kind, or
1703    /// TryParseFailure if such an expression can't be parsed.
1704    fn try_parse_type_expr(&mut self) -> TryParseResult<ExprGreen<'a>> {
1705        // TODO(yuval): support paths starting with "::".
1706        match self.peek().kind {
1707            SyntaxKind::TerminalUnderscore => Ok(self.take::<TerminalUnderscore<'_>>().into()),
1708            SyntaxKind::TerminalAt => {
1709                let op = self.take::<TerminalAt<'_>>().into();
1710                let expr = self.parse_type_expr();
1711                Ok(ExprUnary::new_green(self.db, op, expr).into())
1712            }
1713            SyntaxKind::TerminalAnd | SyntaxKind::TerminalAndAnd => {
1714                self.unglue_andand_for_unary();
1715                let op = self.take::<TerminalAnd<'_>>().into();
1716                let expr = self.parse_type_expr();
1717                Ok(ExprUnary::new_green(self.db, op, expr).into())
1718            }
1719            SyntaxKind::TerminalIdentifier | SyntaxKind::TerminalDollar => {
1720                Ok(self.parse_type_path().into())
1721            }
1722            SyntaxKind::TerminalLParen => Ok(self.expect_type_tuple_expr()),
1723            SyntaxKind::TerminalLBrack => Ok(self.expect_type_fixed_size_array_expr()),
1724            _ => {
1725                // TODO(yuval): report to diagnostics.
1726                Err(TryParseFailure::SkipToken)
1727            }
1728        }
1729    }
1730
1731    /// Returns a GreenId of a node with an ExprPath|ExprParenthesized|ExprTuple kind, or
1732    /// ExprMissing if such an expression can't be parsed.
1733    fn parse_type_expr(&mut self) -> ExprGreen<'a> {
1734        match self.try_parse_type_expr() {
1735            Ok(expr) => expr,
1736            Err(_) => self
1737                .create_and_report_missing::<Expr<'_>>(ParserDiagnosticKind::MissingTypeExpression),
1738        }
1739    }
1740
1741    /// Assumes the current token is LBrace.
1742    /// Expected pattern: `\{<StructArgList>\}`
1743    fn expect_struct_ctor_argument_list_braced(&mut self) -> StructArgListBracedGreen<'a> {
1744        let lbrace = self.take::<TerminalLBrace<'_>>();
1745        let arg_list = StructArgList::new_green(
1746            self.db,
1747            &self.parse_separated_list::<StructArg<'_>, TerminalComma<'_>, StructArgListElementOrSeparatorGreen<'_>>(
1748                Self::try_parse_struct_ctor_argument,
1749                is_of_kind!(rparen, block, rbrace, module_item_kw),
1750                "struct constructor argument",
1751            ),
1752        );
1753        let rbrace = self.parse_token::<TerminalRBrace<'_>>();
1754
1755        StructArgListBraced::new_green(self.db, lbrace, arg_list, rbrace)
1756    }
1757
1758    /// Assumes the current token is LParen.
1759    /// Expected pattern: `<ArgListParenthesized>`
1760    fn expect_function_call(&mut self, path: ExprPathGreen<'a>) -> ExprFunctionCallGreen<'a> {
1761        let func_name = path;
1762        let parenthesized_args = self.expect_parenthesized_argument_list();
1763        ExprFunctionCall::new_green(self.db, func_name, parenthesized_args)
1764    }
1765
1766    /// Assumes the current token is TerminalNot.
1767    /// Expected pattern: `!<WrappedArgList>`
1768    fn expect_macro_call(&mut self, path: ExprPathGreen<'a>) -> ExprInlineMacroGreen<'a> {
1769        let bang = self.take::<TerminalNot<'_>>();
1770        let macro_name = path;
1771        let token_tree_node = self.parse_token_tree_node();
1772        ExprInlineMacro::new_green(self.db, macro_name, bang, token_tree_node)
1773    }
1774
1775    /// Either parses a leaf of the tree (i.e. any non-parenthesis token) or an inner node (i.e. a
1776    /// parenthesized stream of tokens).
1777    fn parse_token_tree(&mut self) -> TokenTreeGreen<'a> {
1778        match self.peek().kind {
1779            SyntaxKind::TerminalLBrace
1780            | SyntaxKind::TerminalLParen
1781            | SyntaxKind::TerminalLBrack => self.parse_token_tree_node().into(),
1782            SyntaxKind::TerminalDollar => {
1783                let dollar: TerminalDollarGreen<'_> = self.take::<TerminalDollar<'_>>();
1784                match self.peek().kind {
1785                    SyntaxKind::TerminalLParen => {
1786                        let lparen = self.take::<TerminalLParen<'_>>();
1787                        let elements = TokenList::new_green(self.db, &self.parse_token_list());
1788                        let rparen = self.parse_token::<TerminalRParen<'_>>();
1789                        let separator: OptionTerminalCommaGreen<'_> = match self.peek().kind {
1790                            SyntaxKind::TerminalComma => self.take::<TerminalComma<'_>>().into(),
1791                            _ => OptionTerminalCommaEmpty::new_green(self.db).into(),
1792                        };
1793                        let operator = match self.peek().kind {
1794                            SyntaxKind::TerminalQuestionMark => {
1795                                self.take::<TerminalQuestionMark<'_>>().into()
1796                            }
1797                            SyntaxKind::TerminalPlus => self.take::<TerminalPlus<'_>>().into(),
1798                            SyntaxKind::TerminalMul => self.take::<TerminalMul<'_>>().into(),
1799                            _ => unreachable!(),
1800                        };
1801                        TokenTreeRepetition::new_green(
1802                            self.db, dollar, lparen, elements, rparen, separator, operator,
1803                        )
1804                        .into()
1805                    }
1806                    SyntaxKind::TerminalIdentifier => {
1807                        let identifier = self.take::<TerminalIdentifier<'_>>();
1808                        TokenTreeParam::new_green(self.db, dollar, identifier).into()
1809                    }
1810                    _ => self.parse_token_tree_leaf().into(),
1811                }
1812            }
1813            _ => self.parse_token_tree_leaf().into(),
1814        }
1815    }
1816
1817    fn parse_token_tree_leaf(&mut self) -> TokenTreeLeafGreen<'a> {
1818        let token_node = self.take_token_node();
1819        TokenTreeLeaf::new_green(self.db, token_node)
1820    }
1821
1822    fn parse_token_tree_node(&mut self) -> TokenTreeNodeGreen<'a> {
1823        let wrapped_token_tree = match self.peek().kind {
1824            SyntaxKind::TerminalLBrace => self
1825                .expect_wrapped_token_tree::<TerminalLBrace<'_>, TerminalRBrace<'_>, _, _>(
1826                    BracedTokenTree::new_green,
1827                )
1828                .into(),
1829            SyntaxKind::TerminalLParen => self
1830                .expect_wrapped_token_tree::<TerminalLParen<'_>, TerminalRParen<'_>, _, _>(
1831                    ParenthesizedTokenTree::new_green,
1832                )
1833                .into(),
1834            SyntaxKind::TerminalLBrack => self
1835                .expect_wrapped_token_tree::<TerminalLBrack<'_>, TerminalRBrack<'_>, _, _>(
1836                    BracketedTokenTree::new_green,
1837                )
1838                .into(),
1839            _ => {
1840                return self.create_and_report_missing::<TokenTreeNode<'_>>(
1841                    ParserDiagnosticKind::MissingWrappedArgList,
1842                );
1843            }
1844        };
1845        TokenTreeNode::new_green(self.db, wrapped_token_tree)
1846    }
1847
1848    /// Assumes the current token is LTerminal.
1849    /// Expected pattern: `[LTerminal](<expr>,)*<expr>?[RTerminal]`
1850    /// Gets `new_green` a green id node builder for the list of the requested type, applies it to
1851    /// the parsed list and returns the result.
1852    fn expect_wrapped_token_tree<
1853        LTerminal: syntax::node::Terminal<'a>,
1854        RTerminal: syntax::node::Terminal<'a>,
1855        ListGreen,
1856        NewGreen: Fn(&'a dyn Database, LTerminal::Green, TokenListGreen<'a>, RTerminal::Green) -> ListGreen,
1857    >(
1858        &mut self,
1859        new_green: NewGreen,
1860    ) -> ListGreen {
1861        let l_term = self.take::<LTerminal>();
1862        let tokens = self.parse_token_list();
1863        let r_term: <RTerminal as TypedSyntaxNode<'_>>::Green = self.parse_token::<RTerminal>();
1864        new_green(self.db, l_term, TokenList::new_green(self.db, &tokens), r_term)
1865    }
1866
1867    fn parse_token_list(&mut self) -> Vec<TokenTreeGreen<'a>> {
1868        let mut tokens: Vec<TokenTreeGreen<'_>> = vec![];
1869        while !matches!(
1870            self.peek().kind,
1871            SyntaxKind::TerminalRParen
1872                | SyntaxKind::TerminalRBrace
1873                | SyntaxKind::TerminalRBrack
1874                | SyntaxKind::TerminalEndOfFile
1875        ) {
1876            tokens.push(self.parse_token_tree());
1877        }
1878        tokens
1879    }
1880
1881    /// Takes a TokenNode according to the current SyntaxKind.
1882    fn take_token_node(&mut self) -> TokenNodeGreen<'a> {
1883        match self.peek().kind {
1884            SyntaxKind::TerminalIdentifier => self.take::<TerminalIdentifier<'_>>().into(),
1885            SyntaxKind::TerminalLiteralNumber => self.take::<TerminalLiteralNumber<'_>>().into(),
1886            SyntaxKind::TerminalShortString => self.take::<TerminalShortString<'_>>().into(),
1887            SyntaxKind::TerminalString => self.take::<TerminalString<'_>>().into(),
1888            SyntaxKind::TerminalAs => self.take::<TerminalAs<'_>>().into(),
1889            SyntaxKind::TerminalConst => self.take::<TerminalConst<'_>>().into(),
1890            SyntaxKind::TerminalElse => self.take::<TerminalElse<'_>>().into(),
1891            SyntaxKind::TerminalEnum => self.take::<TerminalEnum<'_>>().into(),
1892            SyntaxKind::TerminalExtern => self.take::<TerminalExtern<'_>>().into(),
1893            SyntaxKind::TerminalFalse => self.take::<TerminalFalse<'_>>().into(),
1894            SyntaxKind::TerminalFunction => self.take::<TerminalFunction<'_>>().into(),
1895            SyntaxKind::TerminalIf => self.take::<TerminalIf<'_>>().into(),
1896            SyntaxKind::TerminalWhile => self.take::<TerminalWhile<'_>>().into(),
1897            SyntaxKind::TerminalFor => self.take::<TerminalFor<'_>>().into(),
1898            SyntaxKind::TerminalLoop => self.take::<TerminalLoop<'_>>().into(),
1899            SyntaxKind::TerminalImpl => self.take::<TerminalImpl<'_>>().into(),
1900            SyntaxKind::TerminalImplicits => self.take::<TerminalImplicits<'_>>().into(),
1901            SyntaxKind::TerminalLet => self.take::<TerminalLet<'_>>().into(),
1902            SyntaxKind::TerminalMatch => self.take::<TerminalMatch<'_>>().into(),
1903            SyntaxKind::TerminalModule => self.take::<TerminalModule<'_>>().into(),
1904            SyntaxKind::TerminalMut => self.take::<TerminalMut<'_>>().into(),
1905            SyntaxKind::TerminalNoPanic => self.take::<TerminalNoPanic<'_>>().into(),
1906            SyntaxKind::TerminalOf => self.take::<TerminalOf<'_>>().into(),
1907            SyntaxKind::TerminalRef => self.take::<TerminalRef<'_>>().into(),
1908            SyntaxKind::TerminalContinue => self.take::<TerminalContinue<'_>>().into(),
1909            SyntaxKind::TerminalReturn => self.take::<TerminalReturn<'_>>().into(),
1910            SyntaxKind::TerminalBreak => self.take::<TerminalBreak<'_>>().into(),
1911            SyntaxKind::TerminalStruct => self.take::<TerminalStruct<'_>>().into(),
1912            SyntaxKind::TerminalTrait => self.take::<TerminalTrait<'_>>().into(),
1913            SyntaxKind::TerminalTrue => self.take::<TerminalTrue<'_>>().into(),
1914            SyntaxKind::TerminalType => self.take::<TerminalType<'_>>().into(),
1915            SyntaxKind::TerminalUse => self.take::<TerminalUse<'_>>().into(),
1916            SyntaxKind::TerminalPub => self.take::<TerminalPub<'_>>().into(),
1917            SyntaxKind::TerminalAnd => self.take::<TerminalAnd<'_>>().into(),
1918            SyntaxKind::TerminalAndAnd => self.take::<TerminalAndAnd<'_>>().into(),
1919            SyntaxKind::TerminalArrow => self.take::<TerminalArrow<'_>>().into(),
1920            SyntaxKind::TerminalAt => self.take::<TerminalAt<'_>>().into(),
1921            SyntaxKind::TerminalBadCharacters => self.take::<TerminalBadCharacters<'_>>().into(),
1922            SyntaxKind::TerminalColon => self.take::<TerminalColon<'_>>().into(),
1923            SyntaxKind::TerminalColonColon => self.take::<TerminalColonColon<'_>>().into(),
1924            SyntaxKind::TerminalComma => self.take::<TerminalComma<'_>>().into(),
1925            SyntaxKind::TerminalDiv => self.take::<TerminalDiv<'_>>().into(),
1926            SyntaxKind::TerminalDivEq => self.take::<TerminalDivEq<'_>>().into(),
1927            SyntaxKind::TerminalDollar => self.take::<TerminalDollar<'_>>().into(),
1928            SyntaxKind::TerminalDot => self.take::<TerminalDot<'_>>().into(),
1929            SyntaxKind::TerminalDotDot => self.take::<TerminalDotDot<'_>>().into(),
1930            SyntaxKind::TerminalDotDotEq => self.take::<TerminalDotDotEq<'_>>().into(),
1931            SyntaxKind::TerminalEndOfFile => self.take::<TerminalEndOfFile<'_>>().into(),
1932            SyntaxKind::TerminalEq => self.take::<TerminalEq<'_>>().into(),
1933            SyntaxKind::TerminalEqEq => self.take::<TerminalEqEq<'_>>().into(),
1934            SyntaxKind::TerminalGE => self.take::<TerminalGE<'_>>().into(),
1935            SyntaxKind::TerminalGT => self.take::<TerminalGT<'_>>().into(),
1936            SyntaxKind::TerminalHash => self.take::<TerminalHash<'_>>().into(),
1937            SyntaxKind::TerminalLBrace => self.take::<TerminalLBrace<'_>>().into(),
1938            SyntaxKind::TerminalLBrack => self.take::<TerminalLBrack<'_>>().into(),
1939            SyntaxKind::TerminalLE => self.take::<TerminalLE<'_>>().into(),
1940            SyntaxKind::TerminalLParen => self.take::<TerminalLParen<'_>>().into(),
1941            SyntaxKind::TerminalLT => self.take::<TerminalLT<'_>>().into(),
1942            SyntaxKind::TerminalMatchArrow => self.take::<TerminalMatchArrow<'_>>().into(),
1943            SyntaxKind::TerminalMinus => self.take::<TerminalMinus<'_>>().into(),
1944            SyntaxKind::TerminalMinusEq => self.take::<TerminalMinusEq<'_>>().into(),
1945            SyntaxKind::TerminalMod => self.take::<TerminalMod<'_>>().into(),
1946            SyntaxKind::TerminalModEq => self.take::<TerminalModEq<'_>>().into(),
1947            SyntaxKind::TerminalMul => self.take::<TerminalMul<'_>>().into(),
1948            SyntaxKind::TerminalMulEq => self.take::<TerminalMulEq<'_>>().into(),
1949            SyntaxKind::TerminalNeq => self.take::<TerminalNeq<'_>>().into(),
1950            SyntaxKind::TerminalNot => self.take::<TerminalNot<'_>>().into(),
1951            SyntaxKind::TerminalBitNot => self.take::<TerminalBitNot<'_>>().into(),
1952            SyntaxKind::TerminalOr => self.take::<TerminalOr<'_>>().into(),
1953            SyntaxKind::TerminalOrOr => self.take::<TerminalOrOr<'_>>().into(),
1954            SyntaxKind::TerminalPlus => self.take::<TerminalPlus<'_>>().into(),
1955            SyntaxKind::TerminalPlusEq => self.take::<TerminalPlusEq<'_>>().into(),
1956            SyntaxKind::TerminalQuestionMark => self.take::<TerminalQuestionMark<'_>>().into(),
1957            SyntaxKind::TerminalRBrace => self.take::<TerminalRBrace<'_>>().into(),
1958            SyntaxKind::TerminalRBrack => self.take::<TerminalRBrack<'_>>().into(),
1959            SyntaxKind::TerminalRParen => self.take::<TerminalRParen<'_>>().into(),
1960            SyntaxKind::TerminalSemicolon => self.take::<TerminalSemicolon<'_>>().into(),
1961            SyntaxKind::TerminalUnderscore => self.take::<TerminalUnderscore<'_>>().into(),
1962            SyntaxKind::TerminalXor => self.take::<TerminalXor<'_>>().into(),
1963            other => unreachable!("Unexpected token kind: {other:?}"),
1964        }
1965    }
1966    /// Returns a GreenId of a node with an ArgListParenthesized|ArgListBracketed|ArgListBraced kind
1967    /// or TryParseFailure if such an argument list can't be parsed.
1968    pub(crate) fn parse_wrapped_arg_list(&mut self) -> WrappedArgListGreen<'a> {
1969        match self.peek().kind {
1970            SyntaxKind::TerminalLParen => self
1971                .expect_wrapped_argument_list::<TerminalLParen<'_>, TerminalRParen<'_>, _, _>(
1972                    ArgListParenthesized::new_green,
1973                )
1974                .into(),
1975            SyntaxKind::TerminalLBrack => self
1976                .expect_wrapped_argument_list::<TerminalLBrack<'_>, TerminalRBrack<'_>, _, _>(
1977                    ArgListBracketed::new_green,
1978                )
1979                .into(),
1980            SyntaxKind::TerminalLBrace => self
1981                .expect_wrapped_argument_list::<TerminalLBrace<'_>, TerminalRBrace<'_>, _, _>(
1982                    ArgListBraced::new_green,
1983                )
1984                .into(),
1985            _ => self.create_and_report_missing::<WrappedArgList<'_>>(
1986                ParserDiagnosticKind::MissingWrappedArgList,
1987            ),
1988        }
1989    }
1990
1991    /// Assumes the current token is LTerminal.
1992    /// Expected pattern: `[LTerminal](<expr>,)*<expr>?[RTerminal]`
1993    /// Gets `new_green` a green id node builder for the list of the requested type, applies it to
1994    /// the parsed list and returns the result.
1995    fn expect_wrapped_argument_list<
1996        LTerminal: syntax::node::Terminal<'a>,
1997        RTerminal: syntax::node::Terminal<'a>,
1998        ListGreen,
1999        NewGreen: Fn(&'a dyn Database, LTerminal::Green, ArgListGreen<'a>, RTerminal::Green) -> ListGreen,
2000    >(
2001        &mut self,
2002        new_green: NewGreen,
2003    ) -> ListGreen {
2004        let l_term = self.take::<LTerminal>();
2005        let exprs: Vec<ArgListElementOrSeparatorGreen<'_>> = self
2006            .parse_separated_list::<Arg<'_>, TerminalComma<'_>, ArgListElementOrSeparatorGreen<'_>>(
2007                Self::try_parse_function_argument,
2008                is_of_kind!(rparen, rbrace, rbrack, block, module_item_kw),
2009                "argument",
2010            );
2011        let r_term: <RTerminal as TypedSyntaxNode<'_>>::Green = self.parse_token::<RTerminal>();
2012        new_green(self.db, l_term, ArgList::new_green(self.db, &exprs), r_term)
2013    }
2014
2015    /// Assumes the current token is LParen.
2016    /// Expected pattern: `\(<ArgList>\)`
2017    fn expect_parenthesized_argument_list(&mut self) -> ArgListParenthesizedGreen<'a> {
2018        self.expect_wrapped_argument_list::<TerminalLParen<'_>, TerminalRParen<'_>, _, _>(
2019            ArgListParenthesized::new_green,
2020        )
2021    }
2022
2023    /// Tries to parse parenthesized argument list.
2024    /// Expected pattern: `\(<ArgList>\)`
2025    fn try_parse_parenthesized_argument_list(&mut self) -> OptionArgListParenthesizedGreen<'a> {
2026        if self.peek().kind == SyntaxKind::TerminalLParen {
2027            self.expect_parenthesized_argument_list().into()
2028        } else {
2029            OptionArgListParenthesizedEmpty::new_green(self.db).into()
2030        }
2031    }
2032
2033    /// Parses a function call's argument, which contains possibly modifiers, and an argument
2034    /// clause.
2035    fn try_parse_function_argument(&mut self) -> TryParseResult<ArgGreen<'a>> {
2036        let modifiers_list = self.parse_modifier_list();
2037        let arg_clause = self.try_parse_argument_clause();
2038        match arg_clause {
2039            Ok(arg_clause) => {
2040                let modifiers = ModifierList::new_green(self.db, &modifiers_list);
2041                Ok(Arg::new_green(self.db, modifiers, arg_clause))
2042            }
2043            Err(_) if !modifiers_list.is_empty() => {
2044                let modifiers = ModifierList::new_green(self.db, &modifiers_list);
2045                let arg_clause = ArgClauseUnnamed::new_green(self.db, self.parse_expr()).into();
2046                Ok(Arg::new_green(self.db, modifiers, arg_clause))
2047            }
2048            Err(err) => Err(err),
2049        }
2050    }
2051
2052    /// Parses a function call's argument, which is an expression with or without the name
2053    /// of the argument.
2054    ///
2055    /// Possible patterns:
2056    /// * `<Expr>` (unnamed).
2057    /// * `<Identifier>: <Expr>` (named).
2058    /// * `:<Identifier>` (Field init shorthand - syntactic sugar for `a: a`).
2059    fn try_parse_argument_clause(&mut self) -> TryParseResult<ArgClauseGreen<'a>> {
2060        if self.peek().kind == SyntaxKind::TerminalColon {
2061            let colon = self.take::<TerminalColon<'_>>();
2062            let name = self.parse_identifier();
2063            return Ok(ArgClauseFieldInitShorthand::new_green(
2064                self.db,
2065                colon,
2066                ExprFieldInitShorthand::new_green(self.db, name),
2067            )
2068            .into());
2069        }
2070
2071        // Read an expression.
2072        let value = self.try_parse_expr()?;
2073        // If the next token is `:` and the expression is an identifier, this is the argument's
2074        // name.
2075        Ok(
2076            if self.peek().kind == SyntaxKind::TerminalColon
2077                && let Some(argname) = self.try_extract_identifier(value)
2078            {
2079                let colon = self.take::<TerminalColon<'_>>();
2080                let expr = self.parse_expr();
2081                ArgClauseNamed::new_green(self.db, argname, colon, expr).into()
2082            } else {
2083                ArgClauseUnnamed::new_green(self.db, value).into()
2084            },
2085        )
2086    }
2087
2088    /// If the given `expr` is a simple identifier, returns the corresponding green node.
2089    /// Otherwise, returns `TryParseFailure`.
2090    fn try_extract_identifier(&self, expr: ExprGreen<'a>) -> Option<TerminalIdentifierGreen<'a>> {
2091        // Check that `expr` is `ExprPath`.
2092        let GreenNode {
2093            kind: SyntaxKind::ExprPath,
2094            details: GreenNodeDetails::Node { children: children0, .. },
2095        } = expr.0.long(self.db)
2096        else {
2097            return None;
2098        };
2099
2100        // Extract ExprPathInner
2101        let [_dollar, path_inner] = children0[..] else {
2102            return None;
2103        };
2104
2105        let GreenNode {
2106            kind: SyntaxKind::ExprPathInner,
2107            details: GreenNodeDetails::Node { children: children1, .. },
2108        } = path_inner.long(self.db)
2109        else {
2110            return None;
2111        };
2112
2113        // Check that it has one child.
2114        let [path_segment] = children1[..] else {
2115            return None;
2116        };
2117
2118        // Check that `path_segment` is `PathSegmentSimple`.
2119        let GreenNode {
2120            kind: SyntaxKind::PathSegmentSimple,
2121            details: GreenNodeDetails::Node { children: children2, .. },
2122        } = path_segment.long(self.db)
2123        else {
2124            return None;
2125        };
2126
2127        // Check that it has one child.
2128        let [ident] = children2[..] else {
2129            return None;
2130        };
2131
2132        // Check that it is indeed `TerminalIdentifier`.
2133        let GreenNode { kind: SyntaxKind::TerminalIdentifier, .. } = ident.long(self.db) else {
2134            return None;
2135        };
2136
2137        Some(TerminalIdentifierGreen(ident))
2138    }
2139
2140    /// Assumes the current token is LBrace.
2141    /// Expected pattern: `<StructArgListBraced>`
2142    fn expect_constructor_call(&mut self, path: ExprPathGreen<'a>) -> ExprStructCtorCallGreen<'a> {
2143        let ctor_name = path;
2144        let args = self.expect_struct_ctor_argument_list_braced();
2145        ExprStructCtorCall::new_green(self.db, ctor_name, args)
2146    }
2147
2148    /// Assumes the current token is LParen.
2149    /// Expected pattern: `\((<expr>,)*<expr>?\)`
2150    /// Returns a GreenId of a node with kind ExprParenthesized|ExprTuple.
2151    fn expect_parenthesized_expr(&mut self) -> ExprGreen<'a> {
2152        let lparen = self.take::<TerminalLParen<'_>>();
2153        let exprs: Vec<ExprListElementOrSeparatorGreen<'_>> = self
2154            .parse_separated_list::<Expr<'_>, TerminalComma<'_>, ExprListElementOrSeparatorGreen<'_>>(
2155                Self::try_parse_expr,
2156                is_of_kind!(rparen, block, rbrace, module_item_kw),
2157                "expression",
2158            );
2159        let rparen = self.parse_token::<TerminalRParen<'_>>();
2160
2161        if let [ExprListElementOrSeparatorGreen::Element(expr)] = &exprs[..] {
2162            // We have exactly one item and no separator --> This is not a tuple.
2163            ExprParenthesized::new_green(self.db, lparen, *expr, rparen).into()
2164        } else {
2165            ExprListParenthesized::new_green(
2166                self.db,
2167                lparen,
2168                ExprList::new_green(self.db, &exprs),
2169                rparen,
2170            )
2171            .into()
2172        }
2173    }
2174
2175    /// Assumes the current token is LParen.
2176    /// Expected pattern: `\((<type_expr>,)*<type_expr>?\)`
2177    /// Returns a GreenId of a node with kind ExprTuple.
2178    fn expect_type_tuple_expr(&mut self) -> ExprGreen<'a> {
2179        let lparen = self.take::<TerminalLParen<'_>>();
2180        let exprs: Vec<ExprListElementOrSeparatorGreen<'_>> = self
2181            .parse_separated_list::<Expr<'_>, TerminalComma<'_>, ExprListElementOrSeparatorGreen<'_>>(
2182                Self::try_parse_type_expr,
2183                is_of_kind!(rparen, block, rbrace, module_item_kw),
2184                "type expression",
2185            );
2186        let rparen = self.parse_token::<TerminalRParen<'_>>();
2187        if let [ExprListElementOrSeparatorGreen::Element(_)] = &exprs[..] {
2188            self.add_diagnostic(
2189                ParserDiagnosticKind::MissingToken(SyntaxKind::TokenComma),
2190                TextSpan::cursor(self.offset),
2191            );
2192        }
2193        ExprListParenthesized::new_green(
2194            self.db,
2195            lparen,
2196            ExprList::new_green(self.db, &exprs),
2197            rparen,
2198        )
2199        .into()
2200    }
2201
2202    /// Assumes the current token is LBrack.
2203    /// Expected pattern: `\[<type_expr>; <expr>\]`.
2204    /// Returns a GreenId of a node with kind ExprFixedSizeArray.
2205    fn expect_type_fixed_size_array_expr(&mut self) -> ExprGreen<'a> {
2206        let lbrack = self.take::<TerminalLBrack<'_>>();
2207        let exprs: Vec<ExprListElementOrSeparatorGreen<'_>> = self
2208            .parse_separated_list::<Expr<'_>, TerminalComma<'_>, ExprListElementOrSeparatorGreen<'_>>(
2209                Self::try_parse_type_expr,
2210                is_of_kind!(rbrack, semicolon),
2211                "type expression",
2212            );
2213        let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
2214        let size_expr = self.parse_expr();
2215        let fixed_size_array_size =
2216            FixedSizeArraySize::new_green(self.db, semicolon, size_expr).into();
2217        let rbrack = self.parse_token::<TerminalRBrack<'_>>();
2218        ExprFixedSizeArray::new_green(
2219            self.db,
2220            lbrack,
2221            ExprList::new_green(self.db, &exprs),
2222            fixed_size_array_size,
2223            rbrack,
2224        )
2225        .into()
2226    }
2227
2228    /// Assumes the current token is DotDot.
2229    /// Expected pattern: `\.\.<Expr>`
2230    fn expect_struct_argument_tail(&mut self) -> StructArgTailGreen<'a> {
2231        let dotdot = self.take::<TerminalDotDot<'_>>(); // ..
2232        // TODO(yuval): consider changing this to SimpleExpr once it exists.
2233        let expr = self.parse_expr();
2234        StructArgTail::new_green(self.db, dotdot, expr)
2235    }
2236
2237    // For the similar syntax in Rust, see
2238    // https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax.
2239    /// Like parse_argument, but also allows a struct-arg-tail, e.g. 'let s2 = S{"s2", ..s1};'
2240    /// Returns a GreenId of a node with kind StructArgSingle|StructArgTail.
2241    fn try_parse_struct_ctor_argument(&mut self) -> TryParseResult<StructArgGreen<'a>> {
2242        match self.peek().kind {
2243            SyntaxKind::TerminalDotDot => Ok(self.expect_struct_argument_tail().into()),
2244            _ => self.try_parse_argument_single().map(|arg| arg.into()),
2245        }
2246    }
2247
2248    /// Returns a GreenId of a node with kind StructArgExpr or OptionStructArgExprEmpty if an
2249    /// argument expression `(":<value>")` can't be parsed.
2250    fn parse_option_struct_arg_expression(&mut self) -> OptionStructArgExprGreen<'a> {
2251        if self.peek().kind == SyntaxKind::TerminalColon {
2252            let colon = self.take::<TerminalColon<'_>>();
2253            let value = self.parse_expr();
2254            StructArgExpr::new_green(self.db, colon, value).into()
2255        } else {
2256            OptionStructArgExprEmpty::new_green(self.db).into()
2257        }
2258    }
2259
2260    /// Returns a GreenId of a node with kind OptionExprClause or OptionExprClauseEmpty if an
2261    /// argument expression `("Expr")` can't be parsed.
2262    fn parse_option_expression_clause(&mut self) -> OptionExprClauseGreen<'a> {
2263        if self.peek().kind == SyntaxKind::TerminalSemicolon {
2264            OptionExprClauseEmpty::new_green(self.db).into()
2265        } else {
2266            let value = self.parse_expr();
2267            ExprClause::new_green(self.db, value).into()
2268        }
2269    }
2270
2271    /// Returns a GreenId of a node with kind StructArgSingle.
2272    fn try_parse_argument_single(&mut self) -> TryParseResult<StructArgSingleGreen<'a>> {
2273        let identifier = self.try_parse_identifier()?;
2274        let struct_arg_expr = self.parse_option_struct_arg_expression(); // :<expr>
2275        Ok(StructArgSingle::new_green(self.db, identifier, struct_arg_expr))
2276    }
2277
2278    /// Returns a GreenId of a node with kind ExprBlock.
2279    fn parse_block(&mut self) -> ExprBlockGreen<'a> {
2280        let skipped_tokens = self.skip_until(is_of_kind!(rbrace, lbrace, module_item_kw, block));
2281
2282        if let Err(SkippedError(span)) = skipped_tokens {
2283            self.add_diagnostic(
2284                ParserDiagnosticKind::SkippedElement { element_name: "'{'".into() },
2285                span,
2286            );
2287        }
2288
2289        let is_rbrace_or_top_level = is_of_kind!(rbrace, module_item_kw);
2290        if is_rbrace_or_top_level(self.peek().kind) {
2291            return ExprBlock::new_green(
2292                self.db,
2293                self.create_and_report_missing_terminal::<TerminalLBrace<'_>>(),
2294                StatementList::new_green(self.db, &[]),
2295                TerminalRBrace::missing(self.db),
2296            );
2297        }
2298        // Don't report diagnostic if one has already been reported.
2299        let lbrace = self.parse_token_ex::<TerminalLBrace<'_>>(skipped_tokens.is_ok());
2300        let statements = StatementList::new_green(
2301            self.db,
2302            &self.parse_list(
2303                Self::try_parse_statement,
2304                is_of_kind!(rbrace, module_item_kw),
2305                "statement",
2306            ),
2307        );
2308        let rbrace = self.parse_token::<TerminalRBrace<'_>>();
2309        ExprBlock::new_green(self.db, lbrace, statements, rbrace)
2310    }
2311
2312    /// Assumes the current token is `Match`.
2313    /// Expected pattern: `match <expr> \{<MatchArm>*\}`
2314    fn expect_match_expr(&mut self) -> ExprMatchGreen<'a> {
2315        let match_kw = self.take::<TerminalMatch<'_>>();
2316        let expr =
2317            self.parse_expr_limited(MAX_PRECEDENCE, LbraceAllowed::Forbid, AndLetBehavior::Simple);
2318        let lbrace = self.parse_token::<TerminalLBrace<'_>>();
2319        let arms = MatchArms::new_green(
2320            self.db,
2321            &self
2322                .parse_separated_list::<MatchArm<'_>, TerminalComma<'_>, MatchArmsElementOrSeparatorGreen<'_>>(
2323                    Self::try_parse_match_arm,
2324                    is_of_kind!(block, rbrace, module_item_kw),
2325                    "match arm",
2326                ),
2327        );
2328        let rbrace = self.parse_token::<TerminalRBrace<'_>>();
2329        ExprMatch::new_green(self.db, match_kw, expr, lbrace, arms, rbrace)
2330    }
2331
2332    /// Assumes the current token is `If`.
2333    fn expect_if_expr(&mut self) -> ExprIfGreen<'a> {
2334        let if_kw = self.take::<TerminalIf<'a>>();
2335
2336        let conditions = self.parse_condition_list();
2337        let if_block = self.parse_block();
2338        let else_clause = if self.peek().kind == SyntaxKind::TerminalElse {
2339            let else_kw = self.take::<TerminalElse<'a>>();
2340            let else_block_or_if = if self.peek().kind == SyntaxKind::TerminalIf {
2341                self.expect_if_expr().into()
2342            } else {
2343                self.parse_block().into()
2344            };
2345            ElseClause::new_green(self.db, else_kw, else_block_or_if).into()
2346        } else {
2347            OptionElseClauseEmpty::new_green(self.db).into()
2348        };
2349        ExprIf::new_green(self.db, if_kw, conditions, if_block, else_clause)
2350    }
2351
2352    /// If `condition` is a [ConditionExpr] of the form `<expr> <op> <expr>`, returns the operator's
2353    /// kind.
2354    /// Otherwise, returns `None`.
2355    fn get_binary_operator(&self, condition: ConditionGreen<'_>) -> Option<SyntaxKind> {
2356        let condition_expr_green = condition.0.long(self.db);
2357        require(condition_expr_green.kind == SyntaxKind::ConditionExpr)?;
2358
2359        let expr_binary_green = condition_expr_green.children()[0].long(self.db);
2360        require(expr_binary_green.kind == SyntaxKind::ExprBinary)?;
2361
2362        Some(expr_binary_green.children()[1].long(self.db).kind)
2363    }
2364
2365    /// Parses a conjunction of conditions of the form `<condition> && <condition> && ...`,
2366    /// where each condition is either `<expr>` or `let <pattern> = <expr>`.
2367    ///
2368    /// Assumes the next expected token (after the condition list) is `{`. This assumption is used
2369    /// in case of an error.
2370    fn parse_condition_list(&mut self) -> ConditionListAndGreen<'a> {
2371        let and_and_precedence = get_post_operator_precedence(SyntaxKind::TerminalAndAnd).unwrap();
2372
2373        let start_offset = self.offset.add_width(self.current_width);
2374        let condition = self.parse_condition_expr(false);
2375        let mut conditions: Vec<ConditionListAndElementOrSeparatorGreen<'_>> =
2376            vec![condition.into()];
2377
2378        // If there is more than one condition, check that the first condition does not have a
2379        // precedence lower than `&&`.
2380        if self.peek().kind == SyntaxKind::TerminalAndAnd
2381            && let Some(op) = self.get_binary_operator(condition)
2382            && let Some(precedence) = get_post_operator_precedence(op)
2383            && precedence > and_and_precedence
2384        {
2385            let offset = self.offset.add_width(self.current_width - self.last_trivia_length);
2386            self.add_diagnostic(
2387                ParserDiagnosticKind::LowPrecedenceOperatorInIfLet { op },
2388                TextSpan::new(start_offset, offset),
2389            );
2390        }
2391
2392        while self.peek().kind == SyntaxKind::TerminalAndAnd {
2393            let and_and = self.take::<TerminalAndAnd<'a>>();
2394            conditions.push(and_and.into());
2395
2396            let condition = self.parse_condition_expr(true);
2397            conditions.push(condition.into());
2398        }
2399
2400        let peek_item = self.peek();
2401        if let Some(op_precedence) = get_post_operator_precedence(peek_item.kind)
2402            && op_precedence > and_and_precedence
2403        {
2404            self.add_diagnostic(
2405                ParserDiagnosticKind::LowPrecedenceOperatorInIfLet { op: peek_item.kind },
2406                TextSpan::cursor(self.offset.add_width(self.current_width)),
2407            );
2408            // Skip the rest of the tokens until `{`. Don't report additional diagnostics.
2409            let _ = self.skip_until(is_of_kind!(rbrace, lbrace, module_item_kw, block));
2410        }
2411        ConditionListAnd::new_green(self.db, &conditions)
2412    }
2413
2414    /// Parses condition exprs of the form `<expr>` or `let <pattern> = <expr>`.
2415    ///
2416    /// In the case of `let <pattern> = <expr>`, the parser will stop at the first `&&` token
2417    /// (which is not inside parenthesis).
2418    /// If `stop_at_and` is true, this will also be the case for `<expr>`.
2419    fn parse_condition_expr(&mut self, stop_at_and: bool) -> ConditionGreen<'a> {
2420        let and_and_precedence = get_post_operator_precedence(SyntaxKind::TerminalAndAnd).unwrap();
2421        if self.peek().kind == SyntaxKind::TerminalLet {
2422            let let_kw = self.take::<TerminalLet<'a>>();
2423            let pattern_list = self
2424            .parse_separated_list_inner::<Pattern<'_>, TerminalOr<'_>, PatternListOrElementOrSeparatorGreen<'_>>(
2425                Self::try_parse_pattern,
2426                is_of_kind!(eq),
2427                "pattern",
2428                Some(ParserDiagnosticKind::DisallowedTrailingSeparatorOr),
2429            );
2430
2431            let pattern_list_green = if pattern_list.is_empty() {
2432                self.create_and_report_missing::<PatternListOr<'_>>(
2433                    ParserDiagnosticKind::MissingPattern,
2434                )
2435            } else {
2436                PatternListOr::new_green(self.db, &pattern_list)
2437            };
2438            let eq = self.parse_token::<TerminalEq<'a>>();
2439            let expr: ExprGreen<'_> = self.parse_expr_limited(
2440                and_and_precedence,
2441                LbraceAllowed::Forbid,
2442                AndLetBehavior::Stop,
2443            );
2444            ConditionLet::new_green(self.db, let_kw, pattern_list_green, eq, expr).into()
2445        } else {
2446            let condition = self.parse_expr_limited(
2447                if stop_at_and { and_and_precedence } else { MAX_PRECEDENCE },
2448                LbraceAllowed::Forbid,
2449                AndLetBehavior::Stop,
2450            );
2451            ConditionExpr::new_green(self.db, condition).into()
2452        }
2453    }
2454
2455    /// Assumes the current token is `Loop`.
2456    /// Expected pattern: `loop <block>`.
2457    fn expect_loop_expr(&mut self) -> ExprLoopGreen<'a> {
2458        let loop_kw = self.take::<TerminalLoop<'a>>();
2459        let body = self.parse_block();
2460
2461        ExprLoop::new_green(self.db, loop_kw, body)
2462    }
2463
2464    /// Assumes the current token is `While`.
2465    /// Expected pattern: `while <condition> <block>`.
2466    fn expect_while_expr(&mut self) -> ExprWhileGreen<'a> {
2467        let while_kw = self.take::<TerminalWhile<'a>>();
2468        let conditions = self.parse_condition_list();
2469        let body = self.parse_block();
2470
2471        ExprWhile::new_green(self.db, while_kw, conditions, body)
2472    }
2473
2474    /// Assumes the current token is `For`.
2475    /// Expected pattern: `for <pattern> <identifier> <expression> <block>`.
2476    /// Identifier will be checked to be 'in' in semantics.
2477    fn expect_for_expr(&mut self) -> ExprForGreen<'a> {
2478        let for_kw = self.take::<TerminalFor<'a>>();
2479        let pattern = self.parse_pattern();
2480        let ident = self.take_raw();
2481        let in_identifier: TerminalIdentifierGreen<'_> = match ident.text.long(self.db).as_str() {
2482            "in" => self.add_trivia_to_terminal::<TerminalIdentifier<'_>>(ident),
2483            _ => {
2484                self.append_skipped_token_to_pending_trivia(
2485                    ident,
2486                    ParserDiagnosticKind::SkippedElement { element_name: "'in'".into() },
2487                );
2488                TerminalIdentifier::missing(self.db)
2489            }
2490        };
2491        let expression =
2492            self.parse_expr_limited(MAX_PRECEDENCE, LbraceAllowed::Forbid, AndLetBehavior::Simple);
2493        let body = self.parse_block();
2494        ExprFor::new_green(self.db, for_kw, pattern, in_identifier, expression, body)
2495    }
2496
2497    /// Assumes the current token is `|`.
2498    /// Expected pattern: `| <params> | <ReturnTypeClause> <expression>`.
2499    fn expect_closure_expr(&mut self) -> ExprClosureGreen<'a> {
2500        self.unglue::<TerminalOrOr<'_>, TerminalOr<'_>, TerminalOr<'_>>("|", "|");
2501        let leftor = self.take::<TerminalOr<'a>>();
2502        let params = self.parse_closure_param_list();
2503        let rightor = self.parse_token::<TerminalOr<'a>>();
2504        let params = ClosureParams::new_green(self.db, leftor, params, rightor);
2505        let mut block_required = self.peek().kind == SyntaxKind::TerminalArrow;
2506
2507        let return_ty = self.parse_option_return_type_clause();
2508        let optional_no_panic = if self.peek().kind == SyntaxKind::TerminalNoPanic {
2509            block_required = true;
2510            self.take::<TerminalNoPanic<'a>>().into()
2511        } else {
2512            OptionTerminalNoPanicEmpty::new_green(self.db).into()
2513        };
2514        let expr = if block_required { self.parse_block().into() } else { self.parse_expr() };
2515
2516        ExprClosure::new_green(self.db, params, return_ty, optional_no_panic, expr)
2517    }
2518
2519    /// Assumes the current token is LBrack.
2520    /// Expected pattern: `\[<expr>; <expr>\]`.
2521    fn expect_fixed_size_array_expr(&mut self) -> ExprFixedSizeArrayGreen<'a> {
2522        let lbrack = self.take::<TerminalLBrack<'_>>();
2523        let exprs: Vec<ExprListElementOrSeparatorGreen<'_>> = self
2524            .parse_separated_list::<Expr<'_>, TerminalComma<'_>, ExprListElementOrSeparatorGreen<'_>>(
2525                Self::try_parse_expr,
2526                is_of_kind!(rbrack, semicolon),
2527                "expression",
2528            );
2529        let size_green = if self.peek().kind == SyntaxKind::TerminalSemicolon {
2530            let semicolon = self.take::<TerminalSemicolon<'_>>();
2531            let size = self.parse_expr();
2532            FixedSizeArraySize::new_green(self.db, semicolon, size).into()
2533        } else {
2534            OptionFixedSizeArraySizeEmpty::new_green(self.db).into()
2535        };
2536        let rbrack = self.parse_token::<TerminalRBrack<'_>>();
2537        ExprFixedSizeArray::new_green(
2538            self.db,
2539            lbrack,
2540            ExprList::new_green(self.db, &exprs),
2541            size_green,
2542            rbrack,
2543        )
2544    }
2545
2546    /// Returns a GreenId of a node with a MatchArm kind or TryParseFailure if a match arm can't be
2547    /// parsed.
2548    pub fn try_parse_match_arm(&mut self) -> TryParseResult<MatchArmGreen<'a>> {
2549        let pattern_list = self
2550            .parse_separated_list_inner::<Pattern<'_>, TerminalOr<'_>, PatternListOrElementOrSeparatorGreen<'_>>(
2551                Self::try_parse_pattern,
2552                is_of_kind!(match_arrow, rparen, block, rbrace, module_item_kw),
2553                "pattern",
2554                Some(ParserDiagnosticKind::DisallowedTrailingSeparatorOr),
2555            );
2556        if pattern_list.is_empty() {
2557            return Err(TryParseFailure::SkipToken);
2558        }
2559
2560        let pattern_list_green = PatternListOr::new_green(self.db, &pattern_list);
2561
2562        let arrow = self.parse_token::<TerminalMatchArrow<'_>>();
2563        let expr = self.parse_expr();
2564        Ok(MatchArm::new_green(self.db, pattern_list_green, arrow, expr))
2565    }
2566
2567    /// Returns a GreenId of a node with some Pattern kind (see
2568    /// [syntax::node::ast::Pattern]) or TryParseFailure if a pattern can't be parsed.
2569    fn try_parse_pattern(&mut self) -> TryParseResult<PatternGreen<'a>> {
2570        let modifier_list = self.parse_modifier_list();
2571        if !modifier_list.is_empty() {
2572            let modifiers = ModifierList::new_green(self.db, &modifier_list);
2573            let name = self.parse_identifier();
2574            return Ok(PatternIdentifier::new_green(self.db, modifiers, name).into());
2575        };
2576
2577        // TODO(yuval): Support "Or" patterns.
2578        Ok(match self.peek().kind {
2579            SyntaxKind::TerminalLiteralNumber => self.take_terminal_literal_number().into(),
2580            SyntaxKind::TerminalShortString => self.take_terminal_short_string().into(),
2581            SyntaxKind::TerminalTrue => self.take::<TerminalTrue<'_>>().into(),
2582            SyntaxKind::TerminalFalse => self.take::<TerminalFalse<'_>>().into(),
2583            SyntaxKind::TerminalUnderscore => self.take::<TerminalUnderscore<'_>>().into(),
2584            SyntaxKind::TerminalIdentifier => {
2585                // TODO(ilya): Consider parsing a single identifier as PatternIdentifier rather
2586                // then ExprPath.
2587                let path = self.parse_path();
2588                match self.peek().kind {
2589                    SyntaxKind::TerminalLBrace => {
2590                        let lbrace = self.take::<TerminalLBrace<'_>>();
2591                        let params = PatternStructParamList::new_green(
2592                            self.db,
2593                            &self.parse_separated_list::<
2594                                PatternStructParam<'_>,
2595                                TerminalComma<'_>,
2596                                PatternStructParamListElementOrSeparatorGreen<'_>>
2597                            (
2598                                Self::try_parse_pattern_struct_param,
2599                                is_of_kind!(rparen, block, rbrace, module_item_kw),
2600                                "struct pattern parameter",
2601                            ),
2602                        );
2603                        let rbrace = self.parse_token::<TerminalRBrace<'_>>();
2604                        PatternStruct::new_green(self.db, path, lbrace, params, rbrace).into()
2605                    }
2606                    SyntaxKind::TerminalLParen => {
2607                        // Enum pattern.
2608                        let lparen = self.take::<TerminalLParen<'_>>();
2609                        let pattern = self.parse_pattern();
2610                        let rparen = self.parse_token::<TerminalRParen<'_>>();
2611                        let inner_pattern =
2612                            PatternEnumInnerPattern::new_green(self.db, lparen, pattern, rparen);
2613                        PatternEnum::new_green(self.db, path, inner_pattern.into()).into()
2614                    }
2615                    _ => {
2616                        // Check that `expr` is `ExprPath`.
2617                        let GreenNode {
2618                            kind: SyntaxKind::ExprPath,
2619                            details: GreenNodeDetails::Node { children: path_children, .. },
2620                        } = path.0.long(self.db)
2621                        else {
2622                            return Err(TryParseFailure::SkipToken);
2623                        };
2624
2625                        // Extract ExprPathInner
2626                        let [_dollar, path_inner] = path_children[..] else {
2627                            return Err(TryParseFailure::SkipToken);
2628                        };
2629
2630                        let GreenNode {
2631                            kind: SyntaxKind::ExprPathInner,
2632                            details: GreenNodeDetails::Node { children: inner_path_children, .. },
2633                        } = path_inner.long(self.db)
2634                        else {
2635                            return Err(TryParseFailure::SkipToken);
2636                        };
2637
2638                        // If the path has more than 1 element assume it's a simplified Enum variant
2639                        // Eg. MyEnum::A(()) ~ MyEnum::A
2640                        // Multi-element path identifiers aren't allowed, for now this mechanism is
2641                        // sufficient.
2642                        match inner_path_children.len() {
2643                            // 0 => return None, - unreachable
2644                            1 => path.into(),
2645                            _ => PatternEnum::new_green(
2646                                self.db,
2647                                path,
2648                                OptionPatternEnumInnerPatternEmpty::new_green(self.db).into(),
2649                            )
2650                            .into(),
2651                        }
2652                    }
2653                }
2654            }
2655            SyntaxKind::TerminalLParen => {
2656                let lparen = self.take::<TerminalLParen<'_>>();
2657                let patterns = PatternList::new_green(self.db,  &self.parse_separated_list::<
2658                    Pattern<'_>,
2659                    TerminalComma<'_>,
2660                    PatternListElementOrSeparatorGreen<'_>>
2661                (
2662                    Self::try_parse_pattern,
2663                    is_of_kind!(rparen, block, rbrace, module_item_kw),
2664                    "pattern",
2665                ));
2666                let rparen = self.parse_token::<TerminalRParen<'_>>();
2667                PatternTuple::new_green(self.db, lparen, patterns, rparen).into()
2668            }
2669            SyntaxKind::TerminalLBrack => {
2670                let lbrack = self.take::<TerminalLBrack<'_>>();
2671                let patterns = PatternList::new_green(self.db,  &self.parse_separated_list::<
2672                    Pattern<'_>,
2673                    TerminalComma<'_>,
2674                    PatternListElementOrSeparatorGreen<'_>>
2675                (
2676                    Self::try_parse_pattern,
2677                    is_of_kind!(rbrack, block, rbrace, module_item_kw),
2678                    "pattern",
2679                ));
2680                let rbrack = self.parse_token::<TerminalRBrack<'_>>();
2681                PatternFixedSizeArray::new_green(self.db, lbrack, patterns, rbrack).into()
2682            }
2683            _ => return Err(TryParseFailure::SkipToken),
2684        })
2685    }
2686    /// Returns a GreenId of a node with some Pattern kind (see
2687    /// [syntax::node::ast::Pattern]).
2688    fn parse_pattern(&mut self) -> PatternGreen<'a> {
2689        // If not found, return a missing underscore pattern.
2690        match self.try_parse_pattern() {
2691            Ok(pattern) => pattern,
2692            Err(_) => self.create_and_report_missing_terminal::<TerminalUnderscore<'_>>().into(),
2693        }
2694    }
2695
2696    /// Returns a GreenId of a syntax inside a struct pattern. Example:
2697    /// `MyStruct { param0, param1: _, .. }`.
2698    fn try_parse_pattern_struct_param(&mut self) -> TryParseResult<PatternStructParamGreen<'a>> {
2699        Ok(match self.peek().kind {
2700            SyntaxKind::TerminalDotDot => self.take::<TerminalDotDot<'_>>().into(),
2701            _ => {
2702                let modifier_list = self.parse_modifier_list();
2703                let name = if modifier_list.is_empty() {
2704                    self.try_parse_identifier()?
2705                } else {
2706                    self.parse_identifier()
2707                };
2708                let modifiers = ModifierList::new_green(self.db, &modifier_list);
2709                if self.peek().kind == SyntaxKind::TerminalColon {
2710                    let colon = self.take::<TerminalColon<'_>>();
2711                    let pattern = self.parse_pattern();
2712                    PatternStructParamWithExpr::new_green(self.db, modifiers, name, colon, pattern)
2713                        .into()
2714                } else {
2715                    PatternIdentifier::new_green(self.db, modifiers, name).into()
2716                }
2717            }
2718        })
2719    }
2720
2721    // ------------------------------- Statements -------------------------------
2722
2723    /// Returns a GreenId of a node with a Statement.* kind (see
2724    /// [syntax::node::ast::Statement]) or TryParseFailure if a statement can't be parsed.
2725    pub fn try_parse_statement(&mut self) -> TryParseResult<StatementGreen<'a>> {
2726        let maybe_attributes = self.try_parse_attribute_list("Statement");
2727        let (has_attrs, attributes) = match maybe_attributes {
2728            Ok(attributes) => (true, attributes),
2729            Err(_) => (false, AttributeList::new_green(self.db, &[])),
2730        };
2731        match self.peek().kind {
2732            SyntaxKind::TerminalLet => {
2733                let let_kw = self.take::<TerminalLet<'_>>();
2734                let pattern = self.parse_pattern();
2735                let type_clause = self.parse_option_type_clause();
2736                let eq = self.parse_token::<TerminalEq<'_>>();
2737                let rhs = self.parse_expr();
2738
2739                // Check if this is a let-else statement.
2740                let let_else_clause: OptionLetElseClauseGreen<'_> =
2741                    if self.peek().kind == SyntaxKind::TerminalElse {
2742                        let else_kw = self.take::<TerminalElse<'_>>();
2743                        let else_block = self.parse_block();
2744                        LetElseClause::new_green(self.db, else_kw, else_block).into()
2745                    } else {
2746                        OptionLetElseClauseEmpty::new_green(self.db).into()
2747                    };
2748
2749                let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
2750                Ok(StatementLet::new_green(
2751                    self.db,
2752                    attributes,
2753                    let_kw,
2754                    pattern,
2755                    type_clause,
2756                    eq,
2757                    rhs,
2758                    let_else_clause,
2759                    semicolon,
2760                )
2761                .into())
2762            }
2763            SyntaxKind::TerminalContinue => {
2764                let continue_kw = self.take::<TerminalContinue<'_>>();
2765                let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
2766                Ok(StatementContinue::new_green(self.db, attributes, continue_kw, semicolon).into())
2767            }
2768            SyntaxKind::TerminalReturn => {
2769                let return_kw = self.take::<TerminalReturn<'_>>();
2770                let expr = self.parse_option_expression_clause();
2771                let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
2772                Ok(StatementReturn::new_green(self.db, attributes, return_kw, expr, semicolon)
2773                    .into())
2774            }
2775            SyntaxKind::TerminalBreak => {
2776                let break_kw = self.take::<TerminalBreak<'_>>();
2777                let expr = self.parse_option_expression_clause();
2778                let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
2779                Ok(StatementBreak::new_green(self.db, attributes, break_kw, expr, semicolon).into())
2780            }
2781            SyntaxKind::TerminalConst => {
2782                let const_kw = self.take::<TerminalConst<'_>>();
2783                Ok(StatementItem::new_green(
2784                    self.db,
2785                    self.expect_item_const(
2786                        attributes,
2787                        VisibilityDefault::new_green(self.db).into(),
2788                        const_kw,
2789                    )
2790                    .into(),
2791                )
2792                .into())
2793            }
2794            SyntaxKind::TerminalUse => Ok(StatementItem::new_green(
2795                self.db,
2796                self.expect_item_use(attributes, VisibilityDefault::new_green(self.db).into())
2797                    .into(),
2798            )
2799            .into()),
2800            SyntaxKind::TerminalType => Ok(StatementItem::new_green(
2801                self.db,
2802                self.expect_item_type_alias(
2803                    attributes,
2804                    VisibilityDefault::new_green(self.db).into(),
2805                )
2806                .into(),
2807            )
2808            .into()),
2809            _ => match self.try_parse_expr() {
2810                Ok(expr) => {
2811                    let optional_semicolon = if self.peek().kind == SyntaxKind::TerminalSemicolon {
2812                        self.take::<TerminalSemicolon<'_>>().into()
2813                    } else {
2814                        OptionTerminalSemicolonEmpty::new_green(self.db).into()
2815                    };
2816                    Ok(StatementExpr::new_green(self.db, attributes, expr, optional_semicolon)
2817                        .into())
2818                }
2819                Err(_) if has_attrs => Ok(self
2820                    .skip_taken_node_and_return_missing::<Statement<'_>>(
2821                        attributes,
2822                        ParserDiagnosticKind::AttributesWithoutStatement,
2823                    )),
2824                Err(err) => Err(err),
2825            },
2826        }
2827    }
2828
2829    /// Returns a GreenId of a node with kind TypeClause or OptionTypeClauseEmpty if a type clause
2830    /// can't be parsed.
2831    fn parse_option_type_clause(&mut self) -> OptionTypeClauseGreen<'a> {
2832        match self.try_parse_type_clause() {
2833            Some(green) => green.into(),
2834            None => OptionTypeClauseEmpty::new_green(self.db).into(),
2835        }
2836    }
2837
2838    /// Parses a type clause of the form: `: <type>`.
2839    fn parse_type_clause(&mut self, error_recovery: ErrorRecovery) -> TypeClauseGreen<'a> {
2840        match self.try_parse_type_clause() {
2841            Some(green) => green,
2842            None => {
2843                let res = self.create_and_report_missing::<TypeClause<'_>>(
2844                    ParserDiagnosticKind::MissingTypeClause,
2845                );
2846                self.skip_until(error_recovery.should_stop).ok();
2847                res
2848            }
2849        }
2850    }
2851    fn try_parse_type_clause(&mut self) -> Option<TypeClauseGreen<'a>> {
2852        if self.peek().kind == SyntaxKind::TerminalColon {
2853            let colon = self.take::<TerminalColon<'_>>();
2854            let ty = self.parse_type_expr();
2855            Some(TypeClause::new_green(self.db, colon, ty))
2856        } else {
2857            None
2858        }
2859    }
2860
2861    /// Returns a GreenId of a node with kind ReturnTypeClause or OptionReturnTypeClauseEmpty if a
2862    /// return type clause can't be parsed.
2863    fn parse_option_return_type_clause(&mut self) -> OptionReturnTypeClauseGreen<'a> {
2864        if self.peek().kind == SyntaxKind::TerminalArrow {
2865            let arrow = self.take::<TerminalArrow<'_>>();
2866            let return_type = self.parse_type_expr();
2867            ReturnTypeClause::new_green(self.db, arrow, return_type).into()
2868        } else {
2869            OptionReturnTypeClauseEmpty::new_green(self.db).into()
2870        }
2871    }
2872
2873    /// Returns a GreenId of a node with kind ImplicitsClause or OptionImplicitsClauseEmpty if a
2874    /// implicits-clause can't be parsed.
2875    fn parse_option_implicits_clause(&mut self) -> OptionImplicitsClauseGreen<'a> {
2876        if self.peek().kind == SyntaxKind::TerminalImplicits {
2877            let implicits_kw = self.take::<TerminalImplicits<'_>>();
2878            let lparen = self.parse_token::<TerminalLParen<'_>>();
2879            let implicits = ImplicitsList::new_green(
2880                self.db,
2881                &self.parse_separated_list::<ExprPath<'_>, TerminalComma<'_>, ImplicitsListElementOrSeparatorGreen<'_>>(
2882                    Self::try_parse_path,
2883                    // Don't stop at keywords as try_parse_path handles keywords inside it. Otherwise the diagnostic is less accurate.
2884                    is_of_kind!(rparen, lbrace, rbrace),
2885                    "implicit type",
2886                ),
2887            );
2888            let rparen = self.parse_token::<TerminalRParen<'_>>();
2889            ImplicitsClause::new_green(self.db, implicits_kw, lparen, implicits, rparen).into()
2890        } else {
2891            OptionImplicitsClauseEmpty::new_green(self.db).into()
2892        }
2893    }
2894
2895    /// Returns a GreenId of a node with kind ParamList.
2896    fn parse_param_list(&mut self) -> ParamListGreen<'a> {
2897        ParamList::new_green(
2898            self.db,
2899            &self.parse_separated_list::<Param<'_>, TerminalComma<'_>, ParamListElementOrSeparatorGreen<'_>>(
2900                Self::try_parse_param,
2901                is_of_kind!(rparen, block, lbrace, rbrace, module_item_kw),
2902                "parameter",
2903            ),
2904        )
2905    }
2906
2907    /// Returns a GreenId of a node with kind ClosureParamList.
2908    fn parse_closure_param_list(&mut self) -> ParamListGreen<'a> {
2909        ParamList::new_green(
2910            self.db,
2911            &self.parse_separated_list::<Param<'_>, TerminalComma<'_>, ParamListElementOrSeparatorGreen<'_>>(
2912                Self::try_parse_closure_param,
2913                is_of_kind!(or, block, lbrace, rbrace, module_item_kw),
2914                "parameter",
2915            ),
2916        )
2917    }
2918
2919    /// Returns a GreenId of a node with kind Modifier or TryParseFailure if a modifier can't be
2920    /// parsed.
2921    fn try_parse_modifier(&mut self) -> Option<ModifierGreen<'a>> {
2922        match self.peek().kind {
2923            SyntaxKind::TerminalRef => Some(self.take::<TerminalRef<'_>>().into()),
2924            SyntaxKind::TerminalMut => Some(self.take::<TerminalMut<'_>>().into()),
2925            _ => None,
2926        }
2927    }
2928
2929    /// Returns a vector of GreenIds with kind Modifier.
2930    fn parse_modifier_list(&mut self) -> Vec<ModifierGreen<'a>> {
2931        let mut modifier_list = vec![];
2932
2933        while let Some(modifier) = self.try_parse_modifier() {
2934            modifier_list.push(modifier);
2935        }
2936        modifier_list
2937    }
2938
2939    /// Returns a GreenId of a node with kind Param or TryParseFailure if a parameter can't be
2940    /// parsed.
2941    fn try_parse_param(&mut self) -> TryParseResult<ParamGreen<'a>> {
2942        let modifier_list = self.parse_modifier_list();
2943        let name = if modifier_list.is_empty() {
2944            self.try_parse_identifier()?
2945        } else {
2946            // If we had modifiers then the identifier is not optional and can't be '_'.
2947            self.parse_identifier()
2948        };
2949
2950        let type_clause = self
2951            .parse_type_clause(ErrorRecovery {
2952                should_stop: is_of_kind!(comma, rparen, module_item_kw),
2953            })
2954            .into();
2955        Ok(Param::new_green(
2956            self.db,
2957            ModifierList::new_green(self.db, &modifier_list),
2958            name,
2959            type_clause,
2960        ))
2961    }
2962
2963    /// Returns a GreenId of a node with kind Param or TryParseFailure if a parameter can't
2964    /// be parsed.
2965    fn try_parse_closure_param(&mut self) -> TryParseResult<ParamGreen<'a>> {
2966        let modifier_list = self.parse_modifier_list();
2967        let name = if modifier_list.is_empty() {
2968            self.try_parse_identifier()?
2969        } else {
2970            // If we had modifiers then the identifier is not optional and can't be '_'.
2971            self.parse_identifier()
2972        };
2973
2974        let type_clause = self.parse_option_type_clause();
2975        Ok(Param::new_green(
2976            self.db,
2977            ModifierList::new_green(self.db, &modifier_list),
2978            name,
2979            type_clause,
2980        ))
2981    }
2982
2983    /// Returns a GreenId of a node with kind MemberList.
2984    fn parse_member_list(&mut self) -> MemberListGreen<'a> {
2985        MemberList::new_green(
2986            self.db,
2987            &self.parse_separated_list::<
2988                Member<'_>,
2989                TerminalComma<'_>,
2990                MemberListElementOrSeparatorGreen<'_>,
2991            >(
2992                Self::try_parse_member,
2993                is_of_kind!(rparen, block, lbrace, rbrace, module_item_kw),
2994                "member or variant",
2995            ),
2996        )
2997    }
2998
2999    /// Returns a GreenId of a node with kind Member or TryParseFailure if a struct member can't be
3000    /// parsed.
3001    fn try_parse_member(&mut self) -> TryParseResult<MemberGreen<'a>> {
3002        let attributes = self.try_parse_attribute_list("Struct member");
3003        let visibility = self.parse_visibility();
3004        let (name, attributes) = match attributes {
3005            Ok(attributes) => (self.parse_identifier(), attributes),
3006            Err(_) => (self.try_parse_identifier()?, AttributeList::new_green(self.db, &[])),
3007        };
3008        let type_clause = self.parse_type_clause(ErrorRecovery {
3009            should_stop: is_of_kind!(comma, rbrace, module_item_kw),
3010        });
3011        Ok(Member::new_green(self.db, attributes, visibility, name, type_clause))
3012    }
3013
3014    /// Returns a GreenId of a node with kind VariantList.
3015    fn parse_variant_list(&mut self) -> VariantListGreen<'a> {
3016        VariantList::new_green(
3017            self.db,
3018            &self
3019                .parse_separated_list::<Variant<'_>, TerminalComma<'_>, VariantListElementOrSeparatorGreen<'_>>(
3020                    Self::try_parse_variant,
3021                    is_of_kind!(rparen, block, lbrace, rbrace, module_item_kw),
3022                    "variant",
3023                ),
3024        )
3025    }
3026
3027    /// Returns a GreenId of a node with kind Variant or TryParseFailure if an enum variant can't be
3028    /// parsed.
3029    fn try_parse_variant(&mut self) -> TryParseResult<VariantGreen<'a>> {
3030        let attributes = self.try_parse_attribute_list("Enum variant");
3031        let (name, attributes) = match attributes {
3032            Ok(attributes) => (self.parse_identifier(), attributes),
3033            Err(_) => (self.try_parse_identifier()?, AttributeList::new_green(self.db, &[])),
3034        };
3035
3036        let type_clause = self.parse_option_type_clause();
3037        Ok(Variant::new_green(self.db, attributes, name, type_clause))
3038    }
3039
3040    /// Expected pattern: `<PathSegment>(::<PathSegment>)*`
3041    /// Returns a GreenId of a node with kind ExprPath.
3042    fn parse_path(&mut self) -> ExprPathGreen<'a> {
3043        let dollar = match self.peek().kind {
3044            SyntaxKind::TerminalDollar => self.take::<TerminalDollar<'_>>().into(),
3045            _ => OptionTerminalDollarEmpty::new_green(self.db).into(),
3046        };
3047
3048        let mut children: Vec<ExprPathInnerElementOrSeparatorGreen<'_>> = vec![];
3049        loop {
3050            let (segment, optional_separator) = self.parse_path_segment();
3051            children.push(segment.into());
3052
3053            if let Some(separator) = optional_separator {
3054                children.push(separator.into());
3055                continue;
3056            }
3057            break;
3058        }
3059
3060        ExprPath::new_green(self.db, dollar, ExprPathInner::new_green(self.db, &children))
3061    }
3062    /// Returns a GreenId of a node with kind ExprPath or TryParseFailure if a path can't be parsed.
3063    fn try_parse_path(&mut self) -> TryParseResult<ExprPathGreen<'a>> {
3064        if self.is_peek_identifier_like() {
3065            Ok(self.parse_path())
3066        } else {
3067            Err(TryParseFailure::SkipToken)
3068        }
3069    }
3070
3071    /// Expected pattern: `(<PathSegment<'_>>::)*<PathSegment<'_>>(::){0,1}<GenericArgs>`.
3072    ///
3073    /// Returns a GreenId of a node with kind ExprPath.
3074    fn parse_type_path(&mut self) -> ExprPathGreen<'a> {
3075        let dollar = match self.peek().kind {
3076            SyntaxKind::TerminalDollar => self.take::<TerminalDollar<'_>>().into(),
3077            _ => OptionTerminalDollarEmpty::new_green(self.db).into(),
3078        };
3079
3080        let mut children: Vec<ExprPathInnerElementOrSeparatorGreen<'_>> = vec![];
3081        loop {
3082            let (segment, optional_separator) = self.parse_type_path_segment();
3083            children.push(segment.into());
3084
3085            if let Some(separator) = optional_separator {
3086                children.push(separator.into());
3087                continue;
3088            }
3089            break;
3090        }
3091
3092        ExprPath::new_green(self.db, dollar, ExprPathInner::new_green(self.db, &children))
3093    }
3094
3095    /// Returns a PathSegment and an optional separator.
3096    fn parse_path_segment(
3097        &mut self,
3098    ) -> (PathSegmentGreen<'a>, Option<TerminalColonColonGreen<'a>>) {
3099        let identifier = match self.try_parse_identifier() {
3100            Ok(identifier) => identifier,
3101            Err(_) => {
3102                return (
3103                    self.create_and_report_missing::<PathSegment<'_>>(
3104                        ParserDiagnosticKind::MissingPathSegment,
3105                    ),
3106                    // TODO(ilya, 10/10/2022): Should we continue parsing the path here?
3107                    None,
3108                );
3109            }
3110        };
3111        match self.try_parse_token::<TerminalColonColon<'_>>() {
3112            Ok(separator) if self.peek().kind == SyntaxKind::TerminalLT => (
3113                PathSegmentWithGenericArgs::new_green(
3114                    self.db,
3115                    identifier,
3116                    separator.into(),
3117                    self.expect_generic_args(),
3118                )
3119                .into(),
3120                self.try_parse_token::<TerminalColonColon<'_>>().ok(),
3121            ),
3122            optional_separator => {
3123                (PathSegmentSimple::new_green(self.db, identifier).into(), optional_separator.ok())
3124            }
3125        }
3126    }
3127
3128    /// Returns a Typed PathSegment or a normal PathSegment.
3129    /// Additionally returns an optional separators.
3130    fn parse_type_path_segment(
3131        &mut self,
3132    ) -> (PathSegmentGreen<'a>, Option<TerminalColonColonGreen<'a>>) {
3133        let identifier = match self.try_parse_identifier() {
3134            Ok(identifier) => identifier,
3135            Err(_) => {
3136                return (
3137                    self.create_and_report_missing::<PathSegment<'_>>(
3138                        ParserDiagnosticKind::MissingPathSegment,
3139                    ),
3140                    // TODO(ilya, 10/10/2022): Should we continue parsing the path here?
3141                    None,
3142                );
3143            }
3144        };
3145        match self.try_parse_token::<TerminalColonColon<'_>>() {
3146            Err(_) if self.peek().kind == SyntaxKind::TerminalLT => (
3147                PathSegmentWithGenericArgs::new_green(
3148                    self.db,
3149                    identifier,
3150                    OptionTerminalColonColonEmpty::new_green(self.db).into(),
3151                    self.expect_generic_args(),
3152                )
3153                .into(),
3154                None,
3155            ),
3156            // This is here to preserve backwards compatibility.
3157            // This allows Option::<T> to still work after this change.
3158            Ok(separator) if self.peek().kind == SyntaxKind::TerminalLT => (
3159                PathSegmentWithGenericArgs::new_green(
3160                    self.db,
3161                    identifier,
3162                    separator.into(),
3163                    self.expect_generic_args(),
3164                )
3165                .into(),
3166                self.try_parse_token::<TerminalColonColon<'_>>().ok(),
3167            ),
3168            optional_separator => {
3169                (PathSegmentSimple::new_green(self.db, identifier).into(), optional_separator.ok())
3170            }
3171        }
3172    }
3173
3174    /// Takes and validates a TerminalLiteralNumber token.
3175    fn take_terminal_literal_number(&mut self) -> TerminalLiteralNumberGreen<'a> {
3176        let diag = validate_literal_number(self.peek().text.long(self.db));
3177        let green = self.take::<TerminalLiteralNumber<'_>>();
3178        self.add_optional_diagnostic(diag);
3179        green
3180    }
3181
3182    /// Takes and validates a TerminalShortString token.
3183    fn take_terminal_short_string(&mut self) -> TerminalShortStringGreen<'a> {
3184        let diag = validate_short_string(self.peek().text.long(self.db));
3185        let green = self.take::<TerminalShortString<'_>>();
3186        self.add_optional_diagnostic(diag);
3187        green
3188    }
3189
3190    /// Takes and validates a TerminalString token.
3191    fn take_terminal_string(&mut self) -> TerminalStringGreen<'a> {
3192        let diag = validate_string(self.peek().text.long(self.db));
3193        let green = self.take::<TerminalString<'_>>();
3194        self.add_optional_diagnostic(diag);
3195        green
3196    }
3197
3198    /// Adds a diagnostic of kind `kind` if provided, at the current offset.
3199    fn add_optional_diagnostic(&mut self, err: Option<ValidationError>) {
3200        if let Some(err) = err {
3201            let span = match err.location {
3202                ValidationLocation::Full => {
3203                    TextSpan::new_with_width(self.offset, self.current_width)
3204                }
3205                ValidationLocation::After => {
3206                    TextSpan::cursor(self.offset.add_width(self.current_width))
3207                }
3208            };
3209            self.add_diagnostic(err.kind, span);
3210        }
3211    }
3212
3213    /// Returns a GreenId of a node with an
3214    /// ExprLiteral|ExprPath|ExprParenthesized|ExprTuple|ExprUnderscore kind, or TryParseFailure if
3215    /// such an expression can't be parsed.
3216    fn try_parse_generic_arg(&mut self) -> TryParseResult<GenericArgGreen<'a>> {
3217        let expr = match self.peek().kind {
3218            SyntaxKind::TerminalLiteralNumber => self.take_terminal_literal_number().into(),
3219            SyntaxKind::TerminalMinus => {
3220                let op = self.take::<TerminalMinus<'_>>().into();
3221                let expr = self.parse_token::<TerminalLiteralNumber<'_>>().into();
3222                ExprUnary::new_green(self.db, op, expr).into()
3223            }
3224            SyntaxKind::TerminalShortString => self.take_terminal_short_string().into(),
3225            SyntaxKind::TerminalTrue => self.take::<TerminalTrue<'_>>().into(),
3226            SyntaxKind::TerminalFalse => self.take::<TerminalFalse<'_>>().into(),
3227            SyntaxKind::TerminalLBrace => self.parse_block().into(),
3228            _ => self.try_parse_type_expr()?,
3229        };
3230
3231        // If the next token is `:` and the expression is an identifier, this is the argument's
3232        // name.
3233        if self.peek().kind == SyntaxKind::TerminalColon
3234            && let Some(argname) = self.try_extract_identifier(expr)
3235        {
3236            let colon = self.take::<TerminalColon<'_>>();
3237            let expr = self.parse_type_expr();
3238            return Ok(GenericArgNamed::new_green(self.db, argname, colon, expr).into());
3239        }
3240        Ok(GenericArgUnnamed::new_green(self.db, expr).into())
3241    }
3242
3243    /// Assumes the current token is LT.
3244    /// Expected pattern: `\< <GenericArgList> \>`
3245    fn expect_generic_args(&mut self) -> GenericArgsGreen<'a> {
3246        let langle = self.take::<TerminalLT<'_>>();
3247        let generic_args = GenericArgList::new_green(
3248            self.db,
3249            &self.parse_separated_list::<GenericArg<'_>, TerminalComma<'_>, GenericArgListElementOrSeparatorGreen<'_>>(
3250                Self::try_parse_generic_arg,
3251                is_of_kind!(rangle, rparen, block, lbrace, rbrace, module_item_kw),
3252                "generic arg",
3253            ),
3254        );
3255        self.unglue::<TerminalGE<'_>, TerminalGT<'_>, TerminalEq<'_>>(">", "=");
3256        let rangle = self.parse_token::<TerminalGT<'_>>();
3257        GenericArgs::new_green(self.db, langle, generic_args, rangle)
3258    }
3259
3260    /// Assumes the current token is LT.
3261    /// Expected pattern: `\< <GenericParamList> \>`
3262    fn expect_generic_params(&mut self) -> WrappedGenericParamListGreen<'a> {
3263        let langle = self.take::<TerminalLT<'_>>();
3264        let generic_params = GenericParamList::new_green(
3265            self.db,
3266            &self.parse_separated_list::<GenericParam<'_>, TerminalComma<'_>, GenericParamListElementOrSeparatorGreen<'_>>(
3267                Self::try_parse_generic_param,
3268                is_of_kind!(rangle, rparen, block, lbrace, rbrace, module_item_kw),
3269                "generic param",
3270            ),
3271        );
3272        let rangle = self.parse_token::<TerminalGT<'_>>();
3273        WrappedGenericParamList::new_green(self.db, langle, generic_params, rangle)
3274    }
3275
3276    fn parse_optional_generic_params(&mut self) -> OptionWrappedGenericParamListGreen<'a> {
3277        if self.peek().kind != SyntaxKind::TerminalLT {
3278            return OptionWrappedGenericParamListEmpty::new_green(self.db).into();
3279        }
3280        self.expect_generic_params().into()
3281    }
3282
3283    fn try_parse_generic_param(&mut self) -> TryParseResult<GenericParamGreen<'a>> {
3284        match self.peek().kind {
3285            SyntaxKind::TerminalConst => {
3286                let const_kw = self.take::<TerminalConst<'_>>();
3287                let name = self.parse_identifier();
3288                let colon = self.parse_token::<TerminalColon<'_>>();
3289                let ty = self.parse_type_expr();
3290                Ok(GenericParamConst::new_green(self.db, const_kw, name, colon, ty).into())
3291            }
3292            SyntaxKind::TerminalImpl => {
3293                let impl_kw = self.take::<TerminalImpl<'_>>();
3294                let name = self.parse_identifier();
3295                let colon = self.parse_token::<TerminalColon<'_>>();
3296                let trait_path = self.parse_type_path();
3297                let associated_item_constraints = self.parse_optional_associated_item_constraints();
3298                Ok(GenericParamImplNamed::new_green(
3299                    self.db,
3300                    impl_kw,
3301                    name,
3302                    colon,
3303                    trait_path,
3304                    associated_item_constraints,
3305                )
3306                .into())
3307            }
3308            SyntaxKind::TerminalPlus => {
3309                let plus = self.take::<TerminalPlus<'_>>();
3310                let trait_path = self.parse_type_path();
3311                let associated_item_constraints = self.parse_optional_associated_item_constraints();
3312                Ok(GenericParamImplAnonymous::new_green(
3313                    self.db,
3314                    plus,
3315                    trait_path,
3316                    associated_item_constraints,
3317                )
3318                .into())
3319            }
3320            SyntaxKind::TerminalMinus => {
3321                let minus = self.take::<TerminalMinus<'_>>();
3322                let trait_path = self.parse_type_path();
3323                Ok(GenericParamNegativeImpl::new_green(self.db, minus, trait_path).into())
3324            }
3325            _ => Ok(GenericParamType::new_green(self.db, self.try_parse_identifier()?).into()),
3326        }
3327    }
3328
3329    /// Assumes the current token is LBrack.
3330    /// Expected pattern: `[ <associated_item_constraints_list> ]>`
3331    fn expect_associated_item_constraints(&mut self) -> AssociatedItemConstraintsGreen<'a> {
3332        let lbrack = self.take::<TerminalLBrack<'_>>();
3333        let associated_item_constraints_list = AssociatedItemConstraintList::new_green(
3334            self.db,
3335            &self.parse_separated_list::<AssociatedItemConstraint<'_>, TerminalComma<'_>, AssociatedItemConstraintListElementOrSeparatorGreen<'_>>(
3336                Self::try_parse_associated_item_constraint,
3337                is_of_kind!(rbrack,rangle, rparen, block, lbrace, rbrace, module_item_kw),
3338                "associated type argument",
3339            ),
3340        );
3341        let rangle = self.parse_token::<TerminalRBrack<'_>>();
3342        AssociatedItemConstraints::new_green(
3343            self.db,
3344            lbrack,
3345            associated_item_constraints_list,
3346            rangle,
3347        )
3348    }
3349
3350    fn parse_optional_associated_item_constraints(
3351        &mut self,
3352    ) -> OptionAssociatedItemConstraintsGreen<'a> {
3353        if self.peek().kind != SyntaxKind::TerminalLBrack {
3354            return OptionAssociatedItemConstraintsEmpty::new_green(self.db).into();
3355        }
3356        self.expect_associated_item_constraints().into()
3357    }
3358
3359    /// Returns a GreenId of a node with kind AssociatedTypeArg or TryParseFailure if an associated
3360    /// type argument can't be parsed.
3361    fn try_parse_associated_item_constraint(
3362        &mut self,
3363    ) -> TryParseResult<AssociatedItemConstraintGreen<'a>> {
3364        let ident = self.try_parse_identifier()?;
3365        let colon = self.parse_token::<TerminalColon<'_>>();
3366        let ty = self.parse_type_expr();
3367        Ok(AssociatedItemConstraint::new_green(self.db, ident, colon, ty))
3368    }
3369
3370    // ------------------------------- Helpers -------------------------------
3371
3372    /// Parses a list of elements (without separators), where the elements are parsed using
3373    /// `try_parse_list_element`.
3374    /// Returns the list of green ids of the elements.
3375    ///
3376    /// `should_stop` is a predicate to decide how to proceed in case an element can't be parsed,
3377    /// according to the current token. If it returns true, the parsing of the list stops. If it
3378    /// returns false, the current token is skipped and we try to parse an element again.
3379    ///
3380    /// `expected_element` is a description of the expected element.
3381    fn parse_list<ElementGreen>(
3382        &mut self,
3383        try_parse_list_element: fn(&mut Self) -> TryParseResult<ElementGreen>,
3384        should_stop: fn(SyntaxKind) -> bool,
3385        expected_element: &str,
3386    ) -> Vec<ElementGreen> {
3387        let mut children: Vec<ElementGreen> = Vec::new();
3388        loop {
3389            let parse_result = try_parse_list_element(self);
3390            match parse_result {
3391                Ok(element_green) => {
3392                    children.push(element_green);
3393                }
3394                Err(err) => {
3395                    if should_stop(self.peek().kind) {
3396                        break;
3397                    }
3398                    if err == TryParseFailure::SkipToken {
3399                        self.skip_token(ParserDiagnosticKind::SkippedElement {
3400                            element_name: expected_element.into(),
3401                        });
3402                    }
3403                }
3404            }
3405        }
3406        children
3407    }
3408
3409    /// Parses a list of elements (without separators) that can be prefixed with attributes
3410    /// (#[...]), where the elements are parsed using `try_parse_list_element`.
3411    /// Returns the list of green ids of the elements.
3412    ///
3413    /// `should_stop` is a predicate to decide how to proceed in case an element can't be parsed,
3414    /// according to the current token. If it returns true, the parsing of the list stops. If it
3415    /// returns false, the current token is skipped and we try to parse an element again.
3416    ///
3417    /// `expected_element` is a description of the expected element. Note: it should not include
3418    /// "attribute".
3419    fn parse_attributed_list<ElementGreen>(
3420        &mut self,
3421        try_parse_list_element: fn(&mut Self) -> TryParseResult<ElementGreen>,
3422        should_stop: fn(SyntaxKind) -> bool,
3423        expected_element: &'a str,
3424    ) -> Vec<ElementGreen> {
3425        self.parse_list::<ElementGreen>(
3426            try_parse_list_element,
3427            should_stop,
3428            &or_an_attribute!(expected_element),
3429        )
3430    }
3431
3432    /// Parses a list of elements with `separator`s, where the elements are parsed using
3433    /// `try_parse_list_element`. Depending on the value of
3434    /// `forbid_trailing_separator` the separator may or may not appear in
3435    /// the end of the list. Returns the list of elements and separators. This list contains
3436    /// alternating children: [element, separator, element, separator, ...]. Separators may be
3437    /// missing. The length of the list is either 2 * #elements - 1 or 2 * #elements (a
3438    /// separator for each element or for each element but the last one).
3439    ///
3440    /// `should_stop` is a predicate to decide how to proceed in case an element or a separator
3441    /// can't be parsed, according to the current token.
3442    /// When parsing an element:
3443    /// If it returns true, the parsing of the list stops. If it returns false, the current token
3444    /// is skipped and we try to parse an element again.
3445    /// When parsing a separator:
3446    /// If it returns true, the parsing of the list stops. If it returns false, a missing separator
3447    /// is added and we continue to try to parse another element (with the same token).
3448    fn parse_separated_list_inner<
3449        Element: TypedSyntaxNode<'a>,
3450        Separator: syntax::node::Terminal<'a>,
3451        ElementOrSeparatorGreen,
3452    >(
3453        &mut self,
3454        try_parse_list_element: fn(&mut Self) -> TryParseResult<Element::Green>,
3455        should_stop: fn(SyntaxKind) -> bool,
3456        expected_element: &'static str,
3457        forbid_trailing_separator: Option<ParserDiagnosticKind>,
3458    ) -> Vec<ElementOrSeparatorGreen>
3459    where
3460        ElementOrSeparatorGreen: From<Separator::Green> + From<Element::Green>,
3461    {
3462        let mut children: Vec<ElementOrSeparatorGreen> = Vec::new();
3463        loop {
3464            match try_parse_list_element(self) {
3465                Err(_) if should_stop(self.peek().kind) => {
3466                    if let (Some(diagnostic_kind), true) =
3467                        (forbid_trailing_separator, !children.is_empty())
3468                    {
3469                        self.add_diagnostic(diagnostic_kind, TextSpan::cursor(self.offset));
3470                    }
3471                    break;
3472                }
3473                Err(_) => {
3474                    self.skip_token(ParserDiagnosticKind::SkippedElement {
3475                        element_name: expected_element.into(),
3476                    });
3477                    continue;
3478                }
3479                Ok(element) => {
3480                    children.push(element.into());
3481                }
3482            };
3483
3484            let separator = match self.try_parse_token::<Separator>() {
3485                Err(_) if should_stop(self.peek().kind) => {
3486                    break;
3487                }
3488                Err(_) => self.create_and_report_missing::<Separator>(
3489                    ParserDiagnosticKind::MissingToken(Separator::KIND),
3490                ),
3491                Ok(separator) => separator,
3492            };
3493            children.push(separator.into());
3494        }
3495        children
3496    }
3497    /// Calls parse_separated_list_inner with trailing separator enabled.
3498    fn parse_separated_list<
3499        Element: TypedSyntaxNode<'a>,
3500        Separator: syntax::node::Terminal<'a>,
3501        ElementOrSeparatorGreen,
3502    >(
3503        &mut self,
3504        try_parse_list_element: fn(&mut Self) -> TryParseResult<Element::Green>,
3505        should_stop: fn(SyntaxKind) -> bool,
3506        expected_element: &'static str,
3507    ) -> Vec<ElementOrSeparatorGreen>
3508    where
3509        ElementOrSeparatorGreen: From<Separator::Green> + From<Element::Green>,
3510    {
3511        self.parse_separated_list_inner::<Element, Separator, ElementOrSeparatorGreen>(
3512            try_parse_list_element,
3513            should_stop,
3514            expected_element,
3515            None,
3516        )
3517    }
3518
3519    /// Peeks at the next terminal from the Lexer without taking it.
3520    pub fn peek(&self) -> &LexerTerminal<'a> {
3521        self.next_terminal()
3522    }
3523
3524    /// Peeks at the token following the next one.
3525    /// Assumption: the next token is not EOF.
3526    pub fn peek_next_next_kind(&mut self) -> SyntaxKind {
3527        self.next_next_terminal().kind
3528    }
3529
3530    /// Consumes a '&&' token and pushes two '&' tokens into the token stream.
3531    /// If the current token is not '&&', does nothing.
3532    fn unglue_andand_for_unary(&mut self) {
3533        self.unglue::<TerminalAndAnd<'_>, TerminalAnd<'_>, TerminalAnd<'_>>("&", "&");
3534    }
3535
3536    /// Consumes a `Original` token and replaces it instead with its split into `First` and `Second`
3537    /// tokens and pushes them into the token stream. If the current token is not 'Original',
3538    /// does nothing.
3539    fn unglue<
3540        Original: syntax::node::Terminal<'a>,
3541        First: syntax::node::Terminal<'a>,
3542        Second: syntax::node::Terminal<'a>,
3543    >(
3544        &mut self,
3545        first: &'static str,
3546        second: &'static str,
3547    ) {
3548        if self.peek().kind != Original::KIND {
3549            return;
3550        }
3551        // Consume the original token and grab its trivia.
3552        let orig = self.advance();
3553        // Pushing the second first, with the trailing trivia.
3554        self.terminals.push_front(LexerTerminal {
3555            text: SmolStrId::from(self.db, second),
3556            kind: Second::KIND,
3557            leading_trivia: vec![],
3558            trailing_trivia: orig.trailing_trivia,
3559        });
3560        // Pushing the first second, with the leading trivia.
3561        self.terminals.push_front(LexerTerminal {
3562            text: SmolStrId::from(self.db, first),
3563            kind: First::KIND,
3564            leading_trivia: orig.leading_trivia,
3565            trailing_trivia: vec![],
3566        });
3567    }
3568
3569    /// Move forward one terminal.
3570    fn take_raw(&mut self) -> LexerTerminal<'a> {
3571        self.offset = self.offset.add_width(self.current_width);
3572        self.current_width = self.next_terminal().width(self.db);
3573        self.last_trivia_length =
3574            trivia_total_width(self.db, &self.next_terminal().trailing_trivia);
3575        self.advance()
3576    }
3577
3578    /// Skips the next, non-taken, token. A skipped token is a token which is not expected where it
3579    /// is found. Skipping this token means reporting an error, appending the token to the
3580    /// current trivia as skipped, and continuing the compilation as if it wasn't there.
3581    fn skip_token(&mut self, diagnostic_kind: ParserDiagnosticKind) {
3582        if self.peek().kind == SyntaxKind::TerminalEndOfFile {
3583            self.add_diagnostic(diagnostic_kind, TextSpan::cursor(self.offset));
3584            return;
3585        }
3586        let terminal = self.take_raw();
3587        self.append_skipped_token_to_pending_trivia(terminal, diagnostic_kind);
3588    }
3589
3590    /// Appends the given terminal to the pending trivia and reports a diagnostic. Used for skipping
3591    /// a taken ('take_raw') token.
3592    fn append_skipped_token_to_pending_trivia(
3593        &mut self,
3594        terminal: LexerTerminal<'a>,
3595        diagnostic_kind: ParserDiagnosticKind,
3596    ) {
3597        let orig_offset = self.offset;
3598        let diag_start =
3599            self.offset.add_width(trivia_total_width(self.db, &terminal.leading_trivia));
3600        let diag_end = diag_start.add_width(TextWidth::from_str(terminal.text.long(self.db)));
3601
3602        // Add to pending trivia.
3603        self.pending_trivia.extend(terminal.leading_trivia);
3604        self.pending_trivia.push(TokenSkipped::new_green(self.db, terminal.text).into());
3605        let trailing_trivia_width = trivia_total_width(self.db, &terminal.trailing_trivia);
3606        self.pending_trivia.extend(terminal.trailing_trivia);
3607        self.pending_skipped_token_diagnostics.push(PendingParserDiagnostic {
3608            kind: diagnostic_kind,
3609            span: TextSpan::new(diag_start, diag_end),
3610            leading_trivia_start: orig_offset,
3611            trailing_trivia_end: diag_end.add_width(trailing_trivia_width),
3612        });
3613    }
3614
3615    /// A wrapper for `skip_taken_node_with_offset` to report the skipped node diagnostic relative
3616    /// to the current offset. Use this when the skipped node is the last node taken.
3617    fn skip_taken_node_from_current_offset(
3618        &mut self,
3619        node_to_skip: impl Into<SkippedNodeGreen<'a>>,
3620        diagnostic_kind: ParserDiagnosticKind,
3621    ) {
3622        self.skip_taken_node_with_offset(
3623            node_to_skip,
3624            diagnostic_kind,
3625            self.offset.add_width(self.current_width),
3626        )
3627    }
3628
3629    /// Skips the given node which is a variant of `SkippedNode` and is already taken. A skipped
3630    /// node is a node which is not expected where it is found. Skipping this node means
3631    /// reporting the given error (pointing to right after the node), appending the node to the
3632    /// current trivia as skipped, and continuing the compilation as if it wasn't there.
3633    /// `end_of_node_offset` is the offset of the end of the skipped node.
3634    fn skip_taken_node_with_offset(
3635        &mut self,
3636        node_to_skip: impl Into<SkippedNodeGreen<'a>>,
3637        diagnostic_kind: ParserDiagnosticKind,
3638        end_of_node_offset: TextOffset,
3639    ) {
3640        let trivium_green = TriviumSkippedNode::new_green(self.db, node_to_skip.into()).into();
3641
3642        // Add to pending trivia.
3643        self.pending_trivia.push(trivium_green);
3644
3645        let start_of_node_offset = end_of_node_offset.sub_width(trivium_green.0.width(self.db));
3646        let diag_pos = end_of_node_offset
3647            .sub_width(trailing_trivia_width(self.db, trivium_green.0).unwrap_or_default());
3648
3649        self.pending_skipped_token_diagnostics.push(PendingParserDiagnostic {
3650            kind: diagnostic_kind,
3651            span: TextSpan::cursor(diag_pos),
3652            leading_trivia_start: start_of_node_offset,
3653            trailing_trivia_end: end_of_node_offset,
3654        });
3655    }
3656
3657    /// Skips the current token, reports the given diagnostic and returns missing kind of the
3658    /// expected terminal.
3659    fn skip_token_and_return_missing<ExpectedTerminal: syntax::node::Terminal<'a>>(
3660        &mut self,
3661        diagnostic: ParserDiagnosticKind,
3662    ) -> ExpectedTerminal::Green {
3663        self.skip_token(diagnostic);
3664        ExpectedTerminal::missing(self.db)
3665    }
3666
3667    /// Skips a given SkippedNode, reports the given diagnostic (pointing to right after the node)
3668    /// and returns missing kind of the expected node.
3669    fn skip_taken_node_and_return_missing<ExpectedNode: TypedSyntaxNode<'a>>(
3670        &mut self,
3671        node_to_skip: impl Into<SkippedNodeGreen<'a>>,
3672        diagnostic_kind: ParserDiagnosticKind,
3673    ) -> ExpectedNode::Green {
3674        self.skip_taken_node_from_current_offset(node_to_skip, diagnostic_kind);
3675        ExpectedNode::missing(self.db)
3676    }
3677
3678    /// Skips terminals until `should_stop` returns `true`.
3679    ///
3680    /// Returns the span of the skipped terminals, if any.
3681    pub(crate) fn skip_until(
3682        &mut self,
3683        should_stop: fn(SyntaxKind) -> bool,
3684    ) -> Result<(), SkippedError> {
3685        let mut diag_start = None;
3686        let mut diag_end = None;
3687        while !should_stop(self.peek().kind) {
3688            let terminal = self.take_raw();
3689            diag_start.get_or_insert(self.offset);
3690            diag_end =
3691                Some(self.offset.add_width(TextWidth::from_str(terminal.text.long(self.db))));
3692
3693            self.pending_trivia.extend(terminal.leading_trivia);
3694            self.pending_trivia.push(TokenSkipped::new_green(self.db, terminal.text).into());
3695            self.pending_trivia.extend(terminal.trailing_trivia);
3696        }
3697        if let (Some(diag_start), Some(diag_end)) = (diag_start, diag_end) {
3698            Err(SkippedError(TextSpan::new(diag_start, diag_end)))
3699        } else {
3700            Ok(())
3701        }
3702    }
3703
3704    /// Builds a new terminal to replace the given terminal by gluing the recently skipped terminals
3705    /// to the given terminal as extra leading trivia.
3706    fn add_trivia_to_terminal<Terminal: syntax::node::Terminal<'a>>(
3707        &mut self,
3708        lexer_terminal: LexerTerminal<'a>,
3709    ) -> Terminal::Green {
3710        let LexerTerminal { text, kind: _, leading_trivia, trailing_trivia } = lexer_terminal;
3711        let token = Terminal::TokenType::new_green(self.db, text);
3712        let mut new_leading_trivia = mem::take(&mut self.pending_trivia);
3713
3714        self.consume_pending_skipped_diagnostics();
3715
3716        new_leading_trivia.extend(leading_trivia);
3717        Terminal::new_green(
3718            self.db,
3719            Trivia::new_green(self.db, &new_leading_trivia),
3720            token,
3721            Trivia::new_green(self.db, &trailing_trivia),
3722        )
3723    }
3724
3725    /// Adds the pending skipped-tokens diagnostics, merging consecutive similar ones, and reset
3726    /// self.pending_skipped_token_diagnostics.
3727    fn consume_pending_skipped_diagnostics(&mut self) {
3728        let mut pending_skipped = self.pending_skipped_token_diagnostics.drain(..);
3729        let Some(first) = pending_skipped.next() else {
3730            return;
3731        };
3732
3733        let mut current_diag = first;
3734
3735        for diag in pending_skipped {
3736            if diag.kind == current_diag.kind
3737                && current_diag.trailing_trivia_end == diag.leading_trivia_start
3738            {
3739                // Aggregate this diagnostic with the previous ones.
3740                current_diag = PendingParserDiagnostic {
3741                    span: TextSpan::new(current_diag.span.start, diag.span.end),
3742                    kind: diag.kind,
3743                    leading_trivia_start: current_diag.leading_trivia_start,
3744                    trailing_trivia_end: diag.trailing_trivia_end,
3745                };
3746            } else {
3747                // Produce a diagnostic from the aggregated ones, and start aggregating a new
3748                // diagnostic.
3749                self.diagnostics.add(ParserDiagnostic {
3750                    file_id: self.file_id,
3751                    span: current_diag.span,
3752                    kind: current_diag.kind,
3753                });
3754                current_diag = diag;
3755            }
3756        }
3757        // Produce a diagnostic from the aggregated ones at the end.
3758        self.add_diagnostic(current_diag.kind, current_diag.span);
3759    }
3760
3761    /// Takes a token from the Lexer and place it in self.current. If tokens were skipped, glue them
3762    /// to this token as leading trivia.
3763    pub fn take<Terminal: syntax::node::Terminal<'a>>(&mut self) -> Terminal::Green {
3764        let token = self.take_raw();
3765        assert_eq!(token.kind, Terminal::KIND);
3766        self.add_trivia_to_terminal::<Terminal>(token)
3767    }
3768
3769    /// If the current leading trivia start with non-doc comments, creates a new `ItemHeaderDoc` and
3770    /// appends the trivia to it. The purpose of this item is to prevent non-doc comments moving
3771    /// from the top of the file formatter.
3772    fn take_doc(&mut self) -> Option<ItemHeaderDocGreen<'a>> {
3773        // Take all the trivia from `self.next_terminal`, until a doc-comment is found. If the
3774        // result does not contain a non-doc comment (i.e. regular comment or inner
3775        // comment), return None and do not change the next terminal leading trivia.
3776        let mut has_header_doc = false;
3777        let mut split_index = 0;
3778        for trivium in &self.next_terminal().leading_trivia {
3779            match trivium.0.long(self.db).kind {
3780                SyntaxKind::TokenSingleLineComment | SyntaxKind::TokenSingleLineInnerComment => {
3781                    has_header_doc = true;
3782                }
3783                SyntaxKind::TokenSingleLineDocComment => {
3784                    break;
3785                }
3786                _ => {}
3787            }
3788            split_index += 1;
3789        }
3790        if !has_header_doc {
3791            return None;
3792        }
3793        // Split the trivia into header doc and the rest.
3794        let header_doc = {
3795            let next_mut = self.next_terminal_mut();
3796            let leading_trivia = next_mut.leading_trivia.split_off(split_index);
3797            std::mem::replace(&mut next_mut.leading_trivia, leading_trivia)
3798        };
3799        let empty_text_id = SmolStrId::from(self.db, "");
3800        let empty_lexer_terminal = LexerTerminal {
3801            text: empty_text_id,
3802            kind: SyntaxKind::TerminalEmpty,
3803            leading_trivia: header_doc,
3804            trailing_trivia: vec![],
3805        };
3806        self.offset = self.offset.add_width(empty_lexer_terminal.width(self.db));
3807
3808        let empty_terminal = self.add_trivia_to_terminal::<TerminalEmpty<'_>>(empty_lexer_terminal);
3809        Some(ItemHeaderDoc::new_green(self.db, empty_terminal))
3810    }
3811
3812    /// If the current terminal is of kind `Terminal`, returns its Green wrapper. Otherwise, returns
3813    /// TryParseFailure.
3814    /// Note that this function should not be called for 'TerminalIdentifier' -
3815    /// try_parse_identifier() should be used instead.
3816    fn try_parse_token<Terminal: syntax::node::Terminal<'a>>(
3817        &mut self,
3818    ) -> TryParseResult<Terminal::Green> {
3819        if Terminal::KIND == self.peek().kind {
3820            Ok(self.take::<Terminal>())
3821        } else {
3822            Err(TryParseFailure::SkipToken)
3823        }
3824    }
3825
3826    /// If the current token is of kind `token_kind`, returns a GreenId of a node with this kind.
3827    /// Otherwise, returns Token::Missing.
3828    ///
3829    /// Note that this function should not be called for 'TerminalIdentifier' - parse_identifier()
3830    /// should be used instead.
3831    fn parse_token<Terminal: syntax::node::Terminal<'a>>(&mut self) -> Terminal::Green {
3832        self.parse_token_ex::<Terminal>(true)
3833    }
3834
3835    /// Same as [Self::parse_token], except that the diagnostic may be omitted.
3836    fn parse_token_ex<Terminal: syntax::node::Terminal<'a>>(
3837        &mut self,
3838        report_diagnostic: bool,
3839    ) -> Terminal::Green {
3840        match self.try_parse_token::<Terminal>() {
3841            Ok(green) => green,
3842            Err(_) => {
3843                if report_diagnostic {
3844                    self.create_and_report_missing_terminal::<Terminal>()
3845                } else {
3846                    Terminal::missing(self.db)
3847                }
3848            }
3849        }
3850    }
3851}
3852
3853/// Controls whether Lbrace (`{`) is allowed in the expression.
3854///
3855/// Lbrace is always allowed in sub-expressions (e.g. in parenthesized expression). For example,
3856/// while `1 + MyStruct { ... }` may not be valid, `1 + (MyStruct { ... })` is always ok.
3857///
3858/// This can be used to parse the argument of a `match` statement,
3859/// so that the `{` that opens the `match` body is not confused with other potential uses of
3860/// `{`.
3861#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3862enum LbraceAllowed {
3863    Forbid,
3864    Allow,
3865}
3866
3867/// Controls the behavior of the parser when encountering `&& let` tokens.
3868#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3869enum AndLetBehavior {
3870    /// Parse without special handling of `&& let`.
3871    Simple,
3872    /// Stop parsing an expression at `&& let` and return the expression so far.
3873    Stop,
3874}
3875
3876/// Indicates that [Parser::skip_until] skipped some terminals.
3877pub(crate) struct SkippedError(pub(crate) TextSpan);
3878
3879/// Defines the parser behavior in the case of a parsing error.
3880struct ErrorRecovery {
3881    /// In the case of a parsing error, tokens will be skipped until `should_stop`
3882    /// returns `true`. For example, one can stop at tokens such as `,` and `}`.
3883    should_stop: fn(SyntaxKind) -> bool,
3884}
3885
3886enum ExternItem<'a> {
3887    Function(ItemExternFunctionGreen<'a>),
3888    Type(ItemExternTypeGreen<'a>),
3889}
3890
3891#[derive(Debug)]
3892enum ImplItemOrAlias<'a> {
3893    Item(ItemImplGreen<'a>),
3894    Alias(ItemImplAliasGreen<'a>),
3895}
3896
3897/// A parser diagnostic that is not yet reported as it is accumulated with similar consecutive
3898/// diagnostics.
3899pub struct PendingParserDiagnostic {
3900    pub span: TextSpan,
3901    pub kind: ParserDiagnosticKind,
3902    pub leading_trivia_start: TextOffset,
3903    pub trailing_trivia_end: TextOffset,
3904}
3905
3906/// Returns the total width of the given trivia list.
3907fn trivia_total_width(db: &dyn Database, trivia: &[TriviumGreen<'_>]) -> TextWidth {
3908    trivia.iter().map(|trivium| trivium.0.width(db)).sum::<TextWidth>()
3909}
3910
3911/// The width of the trailing trivia, traversing the tree to the bottom right node.
3912fn trailing_trivia_width(db: &dyn Database, green_id: GreenId<'_>) -> Option<TextWidth> {
3913    let node = green_id.long(db);
3914    if node.kind == SyntaxKind::Trivia {
3915        return Some(node.width(db));
3916    }
3917    match &node.details {
3918        GreenNodeDetails::Token(_) => Some(TextWidth::default()),
3919        GreenNodeDetails::Node { children, .. } => {
3920            for child in children.iter().rev() {
3921                if let Some(width) = trailing_trivia_width(db, *child) {
3922                    return Some(width);
3923                }
3924            }
3925            None
3926        }
3927    }
3928}