Skip to main content

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                            _ => self.create_and_report_missing::<MacroRepetitionOperator<'_>>(
799                                ParserDiagnosticKind::MissingMacroRepetitionOperator,
800                            ),
801                        };
802                        Ok(MacroRepetition::new_green(
803                            self.db, dollar, lparen, elements, rparen, separator, operator,
804                        )
805                        .into())
806                    }
807                    _ => {
808                        let ident = self.parse_identifier();
809                        let param_kind: OptionParamKindGreen<'_> = if self.peek().kind
810                            == SyntaxKind::TerminalColon
811                        {
812                            let colon = self.parse_token::<TerminalColon<'_>>();
813                            let kind = self.parse_macro_rule_param_kind();
814                            let result = ParamKind::new_green(self.db, colon, kind).into();
815                            if let MacroParsingContext::MacroExpansion = self.macro_parsing_context
816                            {
817                                self.add_diagnostic(
818                                    ParserDiagnosticKind::InvalidParamKindInMacroExpansion,
819                                    TextSpan::new_with_width(self.offset, self.current_width),
820                                );
821                            }
822                            result
823                        } else {
824                            if let MacroParsingContext::MacroRule = self.macro_parsing_context {
825                                self.add_diagnostic(
826                                    ParserDiagnosticKind::InvalidParamKindInMacroRule,
827                                    TextSpan::new_with_width(self.offset, self.current_width),
828                                );
829                            }
830                            OptionParamKindEmpty::new_green(self.db).into()
831                        };
832                        self.macro_parsing_context = MacroParsingContext::None;
833                        Ok(MacroParam::new_green(self.db, dollar, ident, param_kind).into())
834                    }
835                }
836            }
837            SyntaxKind::TerminalLParen
838            | SyntaxKind::TerminalLBrace
839            | SyntaxKind::TerminalLBrack => {
840                let subtree = self.parse_macro_elements();
841                Ok(MacroWrapper::new_green(self.db, subtree).into())
842            }
843            _ => {
844                let token = self.parse_token_tree_leaf();
845                Ok(token.into())
846            }
847        }
848    }
849
850    fn parse_macro_elements(&mut self) -> WrappedMacroGreen<'a> {
851        match self.peek().kind {
852            SyntaxKind::TerminalLParen => self
853                .wrap_macro::<TerminalLParen<'_>, TerminalRParen<'_>, _, _>(
854                    ParenthesizedMacro::new_green,
855                )
856                .into(),
857            SyntaxKind::TerminalLBrace => self
858                .wrap_macro::<TerminalLBrace<'_>, TerminalRBrace<'_>, _, _>(BracedMacro::new_green)
859                .into(),
860            SyntaxKind::TerminalLBrack => self
861                .wrap_macro::<TerminalLBrack<'_>, TerminalRBrack<'_>, _, _>(
862                    BracketedMacro::new_green,
863                )
864                .into(),
865            _ => unreachable!("parse_macro_elements called on non-delimiter token"),
866        }
867    }
868
869    fn expect_wrapped_macro(&mut self) -> MacroElementsGreen<'a> {
870        let mut elements: Vec<MacroElementGreen<'a>> = vec![];
871        while !matches!(
872            self.peek().kind,
873            SyntaxKind::TerminalRParen
874                | SyntaxKind::TerminalRBrace
875                | SyntaxKind::TerminalRBrack
876                | SyntaxKind::TerminalEndOfFile
877        ) {
878            let element = self.try_parse_macro_element();
879            match element {
880                Ok(element) => elements.push(element),
881                Err(TryParseFailure::SkipToken) => {
882                    let _ = self.skip_until(is_of_kind!(rparen, rbrace, rbrack));
883                    break;
884                }
885                Err(TryParseFailure::DoNothing) => break,
886            }
887        }
888        MacroElements::new_green(self.db, &elements)
889    }
890
891    fn wrap_macro<
892        LTerminal: syntax::node::Terminal<'a>,
893        RTerminal: syntax::node::Terminal<'a>,
894        ListGreen,
895        NewGreen: Fn(
896            &'a dyn Database,
897            LTerminal::Green,
898            MacroElementsGreen<'a>,
899            RTerminal::Green,
900        ) -> ListGreen,
901    >(
902        &mut self,
903        new_green: NewGreen,
904    ) -> ListGreen {
905        let l_term = self.take::<LTerminal>();
906        let elements = self.expect_wrapped_macro();
907        let r_term = self.parse_token::<RTerminal>();
908        new_green(self.db, l_term, elements, r_term)
909    }
910
911    /// Returns a GreenId of a node with a MacroRuleParamKind kind.
912    fn parse_macro_rule_param_kind(&mut self) -> MacroParamKindGreen<'a> {
913        let peeked = self.peek();
914        match (peeked.kind, peeked.text.long(self.db).as_str()) {
915            (SyntaxKind::TerminalIdentifier, "ident") => {
916                ParamIdent::new_green(self.db, self.parse_token::<TerminalIdentifier<'_>>()).into()
917            }
918            (SyntaxKind::TerminalIdentifier, "expr") => {
919                ParamExpr::new_green(self.db, self.parse_token::<TerminalIdentifier<'_>>()).into()
920            }
921            _ => self.create_and_report_missing::<MacroParamKind<'_>>(
922                ParserDiagnosticKind::MissingMacroRuleParamKind,
923            ),
924        }
925    }
926
927    /// Returns a GreenId of a node with a UsePath kind or TryParseFailure if can't parse a UsePath.
928    fn try_parse_use_path(&mut self) -> TryParseResult<UsePathGreen<'a>> {
929        if !matches!(
930            self.peek().kind,
931            SyntaxKind::TerminalLBrace | SyntaxKind::TerminalIdentifier | SyntaxKind::TerminalMul
932        ) {
933            return Err(TryParseFailure::SkipToken);
934        }
935        Ok(self.parse_use_path())
936    }
937
938    /// Returns a GreenId of a node with a UsePath kind.
939    fn parse_use_path(&mut self) -> UsePathGreen<'a> {
940        match self.peek().kind {
941            SyntaxKind::TerminalLBrace => {
942                let lbrace = self.parse_token::<TerminalLBrace<'_>>();
943                let items = UsePathList::new_green(self.db,
944                    &self.parse_separated_list::<
945                        UsePath<'_>, TerminalComma<'_>, UsePathListElementOrSeparatorGreen<'_>
946                    >(
947                        Self::try_parse_use_path,
948                        is_of_kind!(rbrace, module_item_kw),
949                        "path segment",
950                    ));
951                let rbrace = self.parse_token::<TerminalRBrace<'_>>();
952                UsePathMulti::new_green(self.db, lbrace, items, rbrace).into()
953            }
954            SyntaxKind::TerminalMul => {
955                let star = self.parse_token::<TerminalMul<'_>>();
956                UsePathStar::new_green(self.db, star).into()
957            }
958            _ => {
959                if let Ok(ident) = self.try_parse_identifier() {
960                    let ident = PathSegmentSimple::new_green(self.db, ident).into();
961                    match self.peek().kind {
962                        SyntaxKind::TerminalColonColon => {
963                            let colon_colon = self.parse_token::<TerminalColonColon<'_>>();
964                            let use_path = self.parse_use_path();
965                            UsePathSingle::new_green(self.db, ident, colon_colon, use_path).into()
966                        }
967                        SyntaxKind::TerminalAs => {
968                            let as_kw = self.take::<TerminalAs<'_>>();
969                            let alias = self.parse_identifier();
970                            let alias_clause = AliasClause::new_green(self.db, as_kw, alias).into();
971                            UsePathLeaf::new_green(self.db, ident, alias_clause).into()
972                        }
973                        _ => {
974                            let alias_clause = OptionAliasClauseEmpty::new_green(self.db).into();
975                            UsePathLeaf::new_green(self.db, ident, alias_clause).into()
976                        }
977                    }
978                } else {
979                    let missing = self.create_and_report_missing::<TerminalIdentifier<'_>>(
980                        ParserDiagnosticKind::MissingPathSegment,
981                    );
982                    let ident = PathSegmentSimple::new_green(self.db, missing).into();
983                    UsePathLeaf::new_green(
984                        self.db,
985                        ident,
986                        OptionAliasClauseEmpty::new_green(self.db).into(),
987                    )
988                    .into()
989                }
990            }
991        }
992    }
993
994    /// Returns a GreenId of a node with an identifier kind or TryParseFailure if an identifier
995    /// can't be parsed.
996    /// Note that if the terminal is a keyword or an underscore, it is skipped, and
997    /// Some(missing-identifier) is returned.
998    fn try_parse_identifier(&mut self) -> TryParseResult<TerminalIdentifierGreen<'a>> {
999        let peeked = self.peek();
1000        if peeked.kind.is_keyword_terminal() {
1001            // TODO(spapini): don't skip every keyword. Instead, pass a recovery set.
1002            Ok(self.skip_token_and_return_missing::<TerminalIdentifier<'_>>(
1003                ParserDiagnosticKind::ReservedIdentifier {
1004                    identifier: peeked.text.long(self.db).to_string(),
1005                },
1006            ))
1007        } else if peeked.kind == SyntaxKind::TerminalUnderscore {
1008            Ok(self.skip_token_and_return_missing::<TerminalIdentifier<'_>>(
1009                ParserDiagnosticKind::UnderscoreNotAllowedAsIdentifier,
1010            ))
1011        } else {
1012            self.try_parse_token::<TerminalIdentifier<'_>>()
1013        }
1014    }
1015    /// Returns whether the current token is an identifier, a keyword or an underscore ('_'),
1016    /// without consuming it. This should be used mostly, instead of checking whether the current
1017    /// token is an identifier, because in many cases we'd want to consume the keyword/underscore as
1018    /// the identifier and raise a relevant diagnostic
1019    /// (ReservedIdentifier/UnderscoreNotAllowedAsIdentifier).
1020    fn is_peek_identifier_like(&self) -> bool {
1021        let kind = self.peek().kind;
1022        kind.is_keyword_terminal()
1023            || matches!(
1024                kind,
1025                SyntaxKind::TerminalUnderscore
1026                    | SyntaxKind::TerminalIdentifier
1027                    | SyntaxKind::TerminalDollar
1028            )
1029    }
1030
1031    /// Returns a GreenId of a node with an identifier kind.
1032    fn parse_identifier(&mut self) -> TerminalIdentifierGreen<'a> {
1033        match self.try_parse_identifier() {
1034            Ok(identifier) => identifier,
1035            Err(_) => self.create_and_report_missing_terminal::<TerminalIdentifier<'_>>(),
1036        }
1037    }
1038
1039    /// Returns a GreenId of node visibility.
1040    fn parse_visibility(&mut self) -> VisibilityGreen<'a> {
1041        match self.try_parse_visibility_pub() {
1042            Some(visibility) => visibility.into(),
1043            None => VisibilityDefault::new_green(self.db).into(),
1044        }
1045    }
1046
1047    /// Returns a GreenId of node with pub visibility or None if not starting with "pub".
1048    fn try_parse_visibility_pub(&mut self) -> Option<VisibilityPubGreen<'a>> {
1049        require(self.peek().kind == SyntaxKind::TerminalPub)?;
1050        let pub_kw = self.take::<TerminalPub<'_>>();
1051        let argument_clause = if self.peek().kind != SyntaxKind::TerminalLParen {
1052            OptionVisibilityPubArgumentClauseEmpty::new_green(self.db).into()
1053        } else {
1054            let lparen = self.parse_token::<TerminalLParen<'_>>();
1055            let argument = self.parse_token::<TerminalIdentifier<'_>>();
1056            let rparen = self.parse_token::<TerminalRParen<'_>>();
1057            VisibilityPubArgumentClause::new_green(self.db, lparen, argument, rparen).into()
1058        };
1059        Some(VisibilityPub::new_green(self.db, pub_kw, argument_clause))
1060    }
1061
1062    /// Returns a GreenId of a node with an attribute list kind or TryParseFailure if an attribute
1063    /// list can't be parsed.
1064    /// `expected_elements_str` are the expected elements that these attributes are parsed for.
1065    /// Note: it should not include "attribute".
1066    fn try_parse_attribute_list(
1067        &mut self,
1068        expected_elements_str: &str,
1069    ) -> TryParseResult<AttributeListGreen<'a>> {
1070        if self.peek().kind == SyntaxKind::TerminalHash {
1071            Ok(self.parse_attribute_list(expected_elements_str))
1072        } else {
1073            Err(TryParseFailure::SkipToken)
1074        }
1075    }
1076
1077    /// Parses an attribute list.
1078    /// `expected_elements_str` are the expected elements that these attributes are parsed for.
1079    /// Note: it should not include "attribute".
1080    fn parse_attribute_list(&mut self, expected_elements_str: &str) -> AttributeListGreen<'a> {
1081        AttributeList::new_green(
1082            self.db,
1083            &self.parse_list(
1084                Self::try_parse_attribute,
1085                |x| x != SyntaxKind::TerminalHash,
1086                &or_an_attribute!(expected_elements_str),
1087            ),
1088        )
1089    }
1090
1091    /// Returns a GreenId of a node with an attribute kind or TryParseFailure if an attribute can't
1092    /// be parsed.
1093    fn try_parse_attribute(&mut self) -> TryParseResult<AttributeGreen<'a>> {
1094        match self.peek().kind {
1095            SyntaxKind::TerminalHash => {
1096                let hash = self.take::<TerminalHash<'_>>();
1097                let lbrack = self.parse_token::<TerminalLBrack<'_>>();
1098                let attr = self.parse_path();
1099                let arguments = self.try_parse_parenthesized_argument_list();
1100                let rbrack = self.parse_token::<TerminalRBrack<'_>>();
1101
1102                Ok(Attribute::new_green(self.db, hash, lbrack, attr, arguments, rbrack))
1103            }
1104            _ => Err(TryParseFailure::SkipToken),
1105        }
1106    }
1107
1108    /// Assumes the current token is Function.
1109    /// Expected pattern: `<FunctionDeclaration>`.
1110    fn expect_function_declaration(
1111        &mut self,
1112        optional_const: OptionTerminalConstGreen<'a>,
1113    ) -> FunctionDeclarationGreen<'a> {
1114        let function_kw = self.take::<TerminalFunction<'_>>();
1115        self.expect_function_declaration_ex(optional_const, function_kw)
1116    }
1117
1118    /// Assumes the current token is Function.
1119    /// Expected pattern: `<FunctionDeclaration>`.
1120    fn expect_function_declaration_ex(
1121        &mut self,
1122        optional_const: OptionTerminalConstGreen<'a>,
1123        function_kw: TerminalFunctionGreen<'a>,
1124    ) -> FunctionDeclarationGreen<'a> {
1125        let name = self.parse_identifier();
1126        let generic_params = self.parse_optional_generic_params();
1127        let signature = self.expect_function_signature();
1128
1129        FunctionDeclaration::new_green(
1130            self.db,
1131            optional_const,
1132            function_kw,
1133            name,
1134            generic_params,
1135            signature,
1136        )
1137    }
1138
1139    /// Assumes the current token is Function.
1140    /// Expected pattern: `<FunctionDeclaration><Block>`.
1141    fn expect_item_function_with_body(
1142        &mut self,
1143        attributes: AttributeListGreen<'a>,
1144        visibility: VisibilityGreen<'a>,
1145        optional_const: OptionTerminalConstGreen<'a>,
1146    ) -> FunctionWithBodyGreen<'a> {
1147        let declaration = self.expect_function_declaration(optional_const);
1148        let function_body = self.parse_block();
1149        FunctionWithBody::new_green(self.db, attributes, visibility, declaration, function_body)
1150    }
1151
1152    /// Assumes the current token is Trait.
1153    fn expect_item_trait(
1154        &mut self,
1155        attributes: AttributeListGreen<'a>,
1156        visibility: VisibilityGreen<'a>,
1157    ) -> ItemTraitGreen<'a> {
1158        let trait_kw = self.take::<TerminalTrait<'_>>();
1159        let name = self.parse_identifier();
1160        let generic_params = self.parse_optional_generic_params();
1161        let body = if self.peek().kind == SyntaxKind::TerminalLBrace {
1162            let lbrace = self.take::<TerminalLBrace<'_>>();
1163            let items = TraitItemList::new_green(
1164                self.db,
1165                &self.parse_attributed_list(
1166                    Self::try_parse_trait_item,
1167                    is_of_kind!(rbrace, module_item_kw),
1168                    TRAIT_ITEM_DESCRIPTION,
1169                ),
1170            );
1171            let rbrace = self.parse_token::<TerminalRBrace<'_>>();
1172            TraitBody::new_green(self.db, lbrace, items, rbrace).into()
1173        } else {
1174            self.parse_token::<TerminalSemicolon<'_>>().into()
1175        };
1176
1177        ItemTrait::new_green(self.db, attributes, visibility, trait_kw, name, generic_params, body)
1178    }
1179
1180    /// Returns a GreenId of a node with a TraitItem.* kind (see
1181    /// [syntax::node::ast::TraitItem]), or TryParseFailure if a trait item can't be parsed.
1182    pub fn try_parse_trait_item(&mut self) -> TryParseResult<TraitItemGreen<'a>> {
1183        let maybe_attributes = self.try_parse_attribute_list(TRAIT_ITEM_DESCRIPTION);
1184
1185        let (has_attrs, attributes) = match maybe_attributes {
1186            Ok(attributes) => (true, attributes),
1187            Err(_) => (false, AttributeList::new_green(self.db, &[])),
1188        };
1189
1190        match self.peek().kind {
1191            SyntaxKind::TerminalFunction => Ok(self
1192                .expect_trait_item_function(
1193                    attributes,
1194                    OptionTerminalConstEmpty::new_green(self.db).into(),
1195                )
1196                .into()),
1197            SyntaxKind::TerminalType => Ok(self.expect_trait_item_type(attributes).into()),
1198            SyntaxKind::TerminalConst => {
1199                let const_kw = self.take::<TerminalConst<'_>>();
1200                Ok(if self.peek().kind == SyntaxKind::TerminalFunction {
1201                    self.expect_trait_item_function(attributes, const_kw.into()).into()
1202                } else {
1203                    self.expect_trait_item_const(attributes, const_kw).into()
1204                })
1205            }
1206            SyntaxKind::TerminalImpl => Ok(self.expect_trait_item_impl(attributes).into()),
1207            _ => {
1208                if has_attrs {
1209                    Ok(self.skip_taken_node_and_return_missing::<TraitItem<'_>>(
1210                        attributes,
1211                        ParserDiagnosticKind::AttributesWithoutTraitItem,
1212                    ))
1213                } else {
1214                    Err(TryParseFailure::SkipToken)
1215                }
1216            }
1217        }
1218    }
1219
1220    /// Assumes the current token is Function.
1221    /// Expected pattern: `<FunctionDeclaration><SemiColon>`.
1222    fn expect_trait_item_function(
1223        &mut self,
1224        attributes: AttributeListGreen<'a>,
1225        optional_const: OptionTerminalConstGreen<'a>,
1226    ) -> TraitItemFunctionGreen<'a> {
1227        let declaration = self.expect_function_declaration(optional_const);
1228        let body = if self.peek().kind == SyntaxKind::TerminalLBrace {
1229            self.parse_block().into()
1230        } else {
1231            self.parse_token::<TerminalSemicolon<'_>>().into()
1232        };
1233        TraitItemFunction::new_green(self.db, attributes, declaration, body)
1234    }
1235
1236    /// Assumes the current token is Type.
1237    /// Expected pattern: `type <name>;`
1238    fn expect_trait_item_type(
1239        &mut self,
1240        attributes: AttributeListGreen<'a>,
1241    ) -> TraitItemTypeGreen<'a> {
1242        let type_kw = self.take::<TerminalType<'_>>();
1243        let name = self.parse_identifier();
1244        let generic_params = self.parse_optional_generic_params();
1245        let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
1246        TraitItemType::new_green(self.db, attributes, type_kw, name, generic_params, semicolon)
1247    }
1248
1249    /// Assumes the current token is Const.
1250    /// Expected pattern: `const <name>: <type>;`
1251    fn expect_trait_item_const(
1252        &mut self,
1253        attributes: AttributeListGreen<'a>,
1254        const_kw: TerminalConstGreen<'a>,
1255    ) -> TraitItemConstantGreen<'a> {
1256        let name = self.parse_identifier();
1257        let type_clause = self.parse_type_clause(ErrorRecovery {
1258            should_stop: is_of_kind!(eq, semicolon, module_item_kw),
1259        });
1260        let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
1261
1262        TraitItemConstant::new_green(self.db, attributes, const_kw, name, type_clause, semicolon)
1263    }
1264
1265    /// Assumes the current token is Impl.
1266    /// Expected pattern: `impl <name>: <trait_path>;`
1267    fn expect_trait_item_impl(
1268        &mut self,
1269        attributes: AttributeListGreen<'a>,
1270    ) -> TraitItemImplGreen<'a> {
1271        let impl_kw = self.take::<TerminalImpl<'_>>();
1272        let name = self.parse_identifier();
1273        let colon = self.parse_token::<TerminalColon<'_>>();
1274        let trait_path = self.parse_type_path();
1275        let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
1276        TraitItemImpl::new_green(self.db, attributes, impl_kw, name, colon, trait_path, semicolon)
1277    }
1278
1279    /// Assumes the current token is Impl.
1280    fn expect_module_item_impl(
1281        &mut self,
1282        attributes: AttributeListGreen<'a>,
1283        visibility: VisibilityGreen<'a>,
1284    ) -> ModuleItemGreen<'a> {
1285        match self.expect_item_impl_inner(attributes, visibility, false) {
1286            ImplItemOrAlias::Item(green) => green.into(),
1287            ImplItemOrAlias::Alias(green) => green.into(),
1288        }
1289    }
1290
1291    /// Assumes the current token is Impl.
1292    /// Expects an impl impl-item (impl alias syntax): `impl <name> = <path>;`.
1293    fn expect_impl_item_impl(
1294        &mut self,
1295        attributes: AttributeListGreen<'a>,
1296        visibility: VisibilityGreen<'a>,
1297    ) -> ItemImplAliasGreen<'a> {
1298        extract_matches!(
1299            self.expect_item_impl_inner(attributes, visibility, true),
1300            ImplItemOrAlias::Alias
1301        )
1302    }
1303
1304    /// Assumes the current token is Impl.
1305    /// Expects either an impl item (`impl <name> of <trait_path> {<impl_body>}`) or and impl alias
1306    /// `impl <name> = <path>;`.
1307    /// If `only_allow_alias` is true, always returns an ImplItemOrAlias::Alias.
1308    fn expect_item_impl_inner(
1309        &mut self,
1310        attributes: AttributeListGreen<'a>,
1311        visibility: VisibilityGreen<'a>,
1312        only_allow_alias: bool,
1313    ) -> ImplItemOrAlias<'a> {
1314        let impl_kw = self.take::<TerminalImpl<'_>>();
1315        let name = self.parse_identifier();
1316        let generic_params = self.parse_optional_generic_params();
1317
1318        if self.peek().kind == SyntaxKind::TerminalEq || only_allow_alias {
1319            let eq = self.parse_token::<TerminalEq<'_>>();
1320            let impl_path = self.parse_type_path();
1321            let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
1322
1323            return ImplItemOrAlias::Alias(ItemImplAlias::new_green(
1324                self.db,
1325                attributes,
1326                visibility,
1327                impl_kw,
1328                name,
1329                generic_params,
1330                eq,
1331                impl_path,
1332                semicolon,
1333            ));
1334        }
1335
1336        let of_kw = self.parse_token::<TerminalOf<'_>>();
1337        let trait_path = self.parse_type_path();
1338        let body = if self.peek().kind == SyntaxKind::TerminalLBrace {
1339            let lbrace = self.take::<TerminalLBrace<'_>>();
1340            let items = ImplItemList::new_green(
1341                self.db,
1342                &self.parse_attributed_list(
1343                    Self::try_parse_impl_item,
1344                    is_of_kind!(rbrace),
1345                    IMPL_ITEM_DESCRIPTION,
1346                ),
1347            );
1348            let rbrace = self.parse_token::<TerminalRBrace<'_>>();
1349            ImplBody::new_green(self.db, lbrace, items, rbrace).into()
1350        } else {
1351            self.parse_token::<TerminalSemicolon<'_>>().into()
1352        };
1353
1354        ImplItemOrAlias::Item(ItemImpl::new_green(
1355            self.db,
1356            attributes,
1357            visibility,
1358            impl_kw,
1359            name,
1360            generic_params,
1361            of_kw,
1362            trait_path,
1363            body,
1364        ))
1365    }
1366
1367    /// Returns a GreenId of a node with a ImplItem.* kind (see
1368    /// [syntax::node::ast::ImplItem]), or TryParseFailure if an impl item can't be parsed.
1369    pub fn try_parse_impl_item(&mut self) -> TryParseResult<ImplItemGreen<'a>> {
1370        let maybe_attributes = self.try_parse_attribute_list(IMPL_ITEM_DESCRIPTION);
1371
1372        let (has_attrs, attributes) = match maybe_attributes {
1373            Ok(attributes) => (true, attributes),
1374            Err(_) => (false, AttributeList::new_green(self.db, &[])),
1375        };
1376
1377        // No visibility in impls, as these just implements the options of a trait, which is always
1378        // pub.
1379        let visibility = VisibilityDefault::new_green(self.db).into();
1380
1381        match self.peek().kind {
1382            SyntaxKind::TerminalFunction => Ok(self
1383                .expect_item_function_with_body(
1384                    attributes,
1385                    visibility,
1386                    OptionTerminalConstEmpty::new_green(self.db).into(),
1387                )
1388                .into()),
1389            SyntaxKind::TerminalType => {
1390                Ok(self.expect_item_type_alias(attributes, visibility).into())
1391            }
1392            SyntaxKind::TerminalConst => {
1393                let const_kw = self.take::<TerminalConst<'_>>();
1394                Ok(if self.peek().kind == SyntaxKind::TerminalFunction {
1395                    self.expect_item_function_with_body(attributes, visibility, const_kw.into())
1396                        .into()
1397                } else {
1398                    self.expect_item_const(attributes, visibility, const_kw).into()
1399                })
1400            }
1401            SyntaxKind::TerminalImpl => {
1402                Ok(self.expect_impl_item_impl(attributes, visibility).into())
1403            }
1404            // These are not supported semantically.
1405            SyntaxKind::TerminalModule => {
1406                Ok(self.expect_item_module(attributes, visibility).into())
1407            }
1408            SyntaxKind::TerminalStruct => {
1409                Ok(self.expect_item_struct(attributes, visibility).into())
1410            }
1411            SyntaxKind::TerminalEnum => Ok(self.expect_item_enum(attributes, visibility).into()),
1412            SyntaxKind::TerminalExtern => Ok(self.expect_item_extern(attributes, visibility)),
1413            SyntaxKind::TerminalUse => Ok(self.expect_item_use(attributes, visibility).into()),
1414            SyntaxKind::TerminalTrait => Ok(self.expect_item_trait(attributes, visibility).into()),
1415            _ => {
1416                if has_attrs {
1417                    Ok(self.skip_taken_node_and_return_missing::<ImplItem<'_>>(
1418                        attributes,
1419                        ParserDiagnosticKind::AttributesWithoutImplItem,
1420                    ))
1421                } else {
1422                    Err(TryParseFailure::SkipToken)
1423                }
1424            }
1425        }
1426    }
1427
1428    /// Assumes the current token is TerminalNot.
1429    fn expect_item_inline_macro(
1430        &mut self,
1431        attributes: AttributeListGreen<'a>,
1432        path: ExprPathGreen<'a>,
1433    ) -> ItemInlineMacroGreen<'a> {
1434        let bang = self.parse_token::<TerminalNot<'_>>();
1435        self.parse_item_inline_macro_given_bang(attributes, path, bang)
1436    }
1437
1438    /// Returns a GreenId of a node with an ItemInlineMacro kind, given the bang ('!') token.
1439    fn parse_item_inline_macro_given_bang(
1440        &mut self,
1441        attributes: AttributeListGreen<'a>,
1442        path: ExprPathGreen<'a>,
1443        bang: TerminalNotGreen<'a>,
1444    ) -> ItemInlineMacroGreen<'a> {
1445        let token_tree_node = self.parse_token_tree_node();
1446        let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
1447        ItemInlineMacro::new_green(self.db, attributes, path, bang, token_tree_node, semicolon)
1448    }
1449
1450    // ------------------------------- Expressions -------------------------------
1451
1452    /// Returns a GreenId of a node with an Expr.* kind (see [syntax::node::ast::Expr])
1453    /// or TryParseFailure if an expression can't be parsed.
1454    pub fn try_parse_expr(&mut self) -> TryParseResult<ExprGreen<'a>> {
1455        self.try_parse_expr_limited(MAX_PRECEDENCE, LbraceAllowed::Allow, AndLetBehavior::Simple)
1456    }
1457    /// Returns a GreenId of a node with an Expr.* kind (see [syntax::node::ast::Expr])
1458    /// or a node with kind ExprMissing if an expression can't be parsed.
1459    pub fn parse_expr(&mut self) -> ExprGreen<'a> {
1460        match self.try_parse_expr() {
1461            Ok(green) => green,
1462            Err(_) => {
1463                self.create_and_report_missing::<Expr<'_>>(ParserDiagnosticKind::MissingExpression)
1464            }
1465        }
1466    }
1467
1468    /// Assumes the current token is a binary operator. Otherwise it might panic.
1469    ///
1470    /// Returns a GreenId of the operator.
1471    fn parse_binary_operator(&mut self) -> BinaryOperatorGreen<'a> {
1472        // Note that if this code is not reached you might need to add the operator to
1473        // `get_post_operator_precedence`.
1474        match self.peek().kind {
1475            SyntaxKind::TerminalDot => self.take::<TerminalDot<'_>>().into(),
1476            SyntaxKind::TerminalMul => self.take::<TerminalMul<'_>>().into(),
1477            SyntaxKind::TerminalMulEq => self.take::<TerminalMulEq<'_>>().into(),
1478            SyntaxKind::TerminalDiv => self.take::<TerminalDiv<'_>>().into(),
1479            SyntaxKind::TerminalDivEq => self.take::<TerminalDivEq<'_>>().into(),
1480            SyntaxKind::TerminalMod => self.take::<TerminalMod<'_>>().into(),
1481            SyntaxKind::TerminalModEq => self.take::<TerminalModEq<'_>>().into(),
1482            SyntaxKind::TerminalPlus => self.take::<TerminalPlus<'_>>().into(),
1483            SyntaxKind::TerminalPlusEq => self.take::<TerminalPlusEq<'_>>().into(),
1484            SyntaxKind::TerminalMinus => self.take::<TerminalMinus<'_>>().into(),
1485            SyntaxKind::TerminalMinusEq => self.take::<TerminalMinusEq<'_>>().into(),
1486            SyntaxKind::TerminalEq => self.take::<TerminalEq<'_>>().into(),
1487            SyntaxKind::TerminalEqEq => self.take::<TerminalEqEq<'_>>().into(),
1488            SyntaxKind::TerminalNeq => self.take::<TerminalNeq<'_>>().into(),
1489            SyntaxKind::TerminalLT => self.take::<TerminalLT<'_>>().into(),
1490            SyntaxKind::TerminalGT => self.take::<TerminalGT<'_>>().into(),
1491            SyntaxKind::TerminalLE => self.take::<TerminalLE<'_>>().into(),
1492            SyntaxKind::TerminalGE => self.take::<TerminalGE<'_>>().into(),
1493            SyntaxKind::TerminalAnd => self.take::<TerminalAnd<'_>>().into(),
1494            SyntaxKind::TerminalAndAnd => self.take::<TerminalAndAnd<'_>>().into(),
1495            SyntaxKind::TerminalOrOr => self.take::<TerminalOrOr<'_>>().into(),
1496            SyntaxKind::TerminalOr => self.take::<TerminalOr<'_>>().into(),
1497            SyntaxKind::TerminalXor => self.take::<TerminalXor<'_>>().into(),
1498            SyntaxKind::TerminalDotDot => self.take::<TerminalDotDot<'_>>().into(),
1499            SyntaxKind::TerminalDotDotEq => self.take::<TerminalDotDotEq<'_>>().into(),
1500            _ => unreachable!(),
1501        }
1502    }
1503
1504    /// Assumes the current token is a unary operator, and returns a GreenId of the operator.
1505    fn expect_unary_operator(&mut self) -> UnaryOperatorGreen<'a> {
1506        match self.peek().kind {
1507            SyntaxKind::TerminalAt => self.take::<TerminalAt<'_>>().into(),
1508            SyntaxKind::TerminalAnd | SyntaxKind::TerminalAndAnd => {
1509                self.unglue_andand_for_unary();
1510                self.take::<TerminalAnd<'_>>().into()
1511            }
1512            SyntaxKind::TerminalNot => self.take::<TerminalNot<'_>>().into(),
1513            SyntaxKind::TerminalBitNot => self.take::<TerminalBitNot<'_>>().into(),
1514            SyntaxKind::TerminalMinus => self.take::<TerminalMinus<'_>>().into(),
1515            SyntaxKind::TerminalMul => self.take::<TerminalMul<'_>>().into(),
1516            _ => unreachable!(),
1517        }
1518    }
1519
1520    /// Checks if the current token is a relational or equality operator (`<`, `>`, `<=`, `>=`,
1521    /// `==`, or `!=`).
1522    ///
1523    /// This function is used to determine if the given `SyntaxKind` represents a relational or
1524    /// equality operator, which is commonly used in binary expressions.
1525    ///
1526    /// # Parameters:
1527    /// - `kind`: The `SyntaxKind` of the current token.
1528    ///
1529    /// # Returns:
1530    /// `true` if the token is a relational or equality operator, otherwise `false`.
1531    fn is_comparison_operator(&self, kind: SyntaxKind) -> bool {
1532        matches!(
1533            kind,
1534            SyntaxKind::TerminalLT
1535                | SyntaxKind::TerminalGT
1536                | SyntaxKind::TerminalLE
1537                | SyntaxKind::TerminalGE
1538                | SyntaxKind::TerminalEqEq
1539                | SyntaxKind::TerminalNeq
1540        )
1541    }
1542
1543    /// Returns a GreenId of a node with an Expr.* kind (see [syntax::node::ast::Expr])
1544    /// or TryParseFailure if such an expression can't be parsed.
1545    ///
1546    /// Parsing will be limited by:
1547    /// `parent_precedence` - parsing of binary operators limited to this.
1548    /// `lbrace_allowed` - See [LbraceAllowed].
1549    fn try_parse_expr_limited(
1550        &mut self,
1551        parent_precedence: usize,
1552        lbrace_allowed: LbraceAllowed,
1553        and_let_behavior: AndLetBehavior,
1554    ) -> TryParseResult<ExprGreen<'a>> {
1555        let mut expr = self.try_parse_atom_or_unary(lbrace_allowed)?;
1556        let mut child_op: Option<SyntaxKind> = None;
1557        loop {
1558            let peeked_kind = self.peek().kind;
1559            let Some(precedence) = get_post_operator_precedence(peeked_kind) else {
1560                return Ok(expr);
1561            };
1562            if precedence >= parent_precedence {
1563                return Ok(expr);
1564            }
1565            expr = match peeked_kind {
1566                // If the next two tokens are `&& let` (part of a let-chain), then they should be
1567                // parsed by the caller. Return immediately.
1568                SyntaxKind::TerminalAndAnd
1569                    if and_let_behavior == AndLetBehavior::Stop
1570                        && self.peek_next_next_kind() == SyntaxKind::TerminalLet =>
1571                {
1572                    return Ok(expr);
1573                }
1574                SyntaxKind::TerminalQuestionMark => ExprErrorPropagate::new_green(
1575                    self.db,
1576                    expr,
1577                    self.take::<TerminalQuestionMark<'_>>(),
1578                )
1579                .into(),
1580                SyntaxKind::TerminalLBrack => {
1581                    let lbrack = self.take::<TerminalLBrack<'_>>();
1582                    let index_expr = self.parse_expr();
1583                    let rbrack = self.parse_token::<TerminalRBrack<'_>>();
1584                    ExprIndexed::new_green(self.db, expr, lbrack, index_expr, rbrack).into()
1585                }
1586                current_op => {
1587                    if let Some(child_op_kind) = child_op
1588                        && self.is_comparison_operator(child_op_kind)
1589                        && self.is_comparison_operator(current_op)
1590                    {
1591                        self.add_diagnostic(
1592                            ParserDiagnosticKind::ConsecutiveMathOperators {
1593                                first_op: child_op_kind,
1594                                second_op: current_op,
1595                            },
1596                            TextSpan::cursor(self.offset.add_width(self.current_width)),
1597                        );
1598                    }
1599                    child_op = Some(current_op);
1600                    let op = self.parse_binary_operator();
1601                    let rhs = self.parse_expr_limited(precedence, lbrace_allowed, and_let_behavior);
1602                    ExprBinary::new_green(self.db, expr, op, rhs).into()
1603                }
1604            };
1605        }
1606    }
1607
1608    /// Returns a GreenId of a node with ExprPath, ExprFunctionCall, ExprStructCtorCall,
1609    /// ExprParenthesized, ExprTuple or ExprUnary kind, or TryParseFailure if such an expression
1610    /// can't be parsed.
1611    ///
1612    /// `lbrace_allowed` - See [LbraceAllowed].
1613    fn try_parse_atom_or_unary(
1614        &mut self,
1615        lbrace_allowed: LbraceAllowed,
1616    ) -> TryParseResult<ExprGreen<'a>> {
1617        let Some(precedence) = get_unary_operator_precedence(self.peek().kind) else {
1618            return self.try_parse_atom(lbrace_allowed);
1619        };
1620        let op = self.expect_unary_operator();
1621        let expr = self.parse_expr_limited(precedence, lbrace_allowed, AndLetBehavior::Simple);
1622        Ok(ExprUnary::new_green(self.db, op, expr).into())
1623    }
1624
1625    /// Returns a GreenId of a node with an Expr.* kind (see [syntax::node::ast::Expr]),
1626    /// excluding ExprBlock, or ExprMissing if such an expression can't be parsed.
1627    ///
1628    /// `lbrace_allowed` - See [LbraceAllowed].
1629    fn parse_expr_limited(
1630        &mut self,
1631        parent_precedence: usize,
1632        lbrace_allowed: LbraceAllowed,
1633        and_let_behavior: AndLetBehavior,
1634    ) -> ExprGreen<'a> {
1635        match self.try_parse_expr_limited(parent_precedence, lbrace_allowed, and_let_behavior) {
1636            Ok(green) => green,
1637            Err(_) => {
1638                self.create_and_report_missing::<Expr<'_>>(ParserDiagnosticKind::MissingExpression)
1639            }
1640        }
1641    }
1642
1643    /// Returns a GreenId of a node with an
1644    /// ExprPath|ExprFunctionCall|ExprStructCtorCall|ExprParenthesized|ExprTuple kind, or
1645    /// TryParseFailure if such an expression can't be parsed.
1646    ///
1647    /// `lbrace_allowed` - See [LbraceAllowed].
1648    fn try_parse_atom(&mut self, lbrace_allowed: LbraceAllowed) -> TryParseResult<ExprGreen<'a>> {
1649        // TODO(yuval): support paths starting with "::".
1650        match self.peek().kind {
1651            SyntaxKind::TerminalIdentifier | SyntaxKind::TerminalDollar => {
1652                // Call parse_path() and not expect_path(), because it's cheap.
1653                let path = self.parse_path();
1654                match self.peek().kind {
1655                    SyntaxKind::TerminalLParen => Ok(self.expect_function_call(path).into()),
1656                    SyntaxKind::TerminalLBrace if lbrace_allowed == LbraceAllowed::Allow => {
1657                        Ok(self.expect_constructor_call(path).into())
1658                    }
1659                    SyntaxKind::TerminalNot => Ok(self.expect_macro_call(path).into()),
1660                    _ => Ok(path.into()),
1661                }
1662            }
1663            SyntaxKind::TerminalFalse => Ok(self.take::<TerminalFalse<'_>>().into()),
1664            SyntaxKind::TerminalTrue => Ok(self.take::<TerminalTrue<'_>>().into()),
1665            SyntaxKind::TerminalLiteralNumber => Ok(self.take_terminal_literal_number().into()),
1666            SyntaxKind::TerminalShortString => Ok(self.take_terminal_short_string().into()),
1667            SyntaxKind::TerminalString => Ok(self.take_terminal_string().into()),
1668            SyntaxKind::TerminalLParen => {
1669                // Note that LBrace is allowed inside parenthesis, even if `lbrace_allowed` is
1670                // [LbraceAllowed::Forbid].
1671                Ok(self.expect_parenthesized_expr())
1672            }
1673            SyntaxKind::TerminalLBrack => Ok(self.expect_fixed_size_array_expr().into()),
1674            SyntaxKind::TerminalLBrace if lbrace_allowed == LbraceAllowed::Allow => {
1675                Ok(self.parse_block().into())
1676            }
1677            SyntaxKind::TerminalMatch if lbrace_allowed == LbraceAllowed::Allow => {
1678                Ok(self.expect_match_expr().into())
1679            }
1680            SyntaxKind::TerminalIf if lbrace_allowed == LbraceAllowed::Allow => {
1681                Ok(self.expect_if_expr().into())
1682            }
1683            SyntaxKind::TerminalLoop if lbrace_allowed == LbraceAllowed::Allow => {
1684                Ok(self.expect_loop_expr().into())
1685            }
1686            SyntaxKind::TerminalWhile if lbrace_allowed == LbraceAllowed::Allow => {
1687                Ok(self.expect_while_expr().into())
1688            }
1689            SyntaxKind::TerminalFor if lbrace_allowed == LbraceAllowed::Allow => {
1690                Ok(self.expect_for_expr().into())
1691            }
1692            SyntaxKind::TerminalOr | SyntaxKind::TerminalOrOr
1693                if lbrace_allowed == LbraceAllowed::Allow =>
1694            {
1695                Ok(self.expect_closure_expr().into())
1696            }
1697            _ => {
1698                // TODO(yuval): report to diagnostics.
1699                Err(TryParseFailure::SkipToken)
1700            }
1701        }
1702    }
1703
1704    /// Returns a GreenId of a node with an ExprPath|ExprParenthesized|ExprTuple kind, or
1705    /// TryParseFailure if such an expression can't be parsed.
1706    fn try_parse_type_expr(&mut self) -> TryParseResult<ExprGreen<'a>> {
1707        // TODO(yuval): support paths starting with "::".
1708        match self.peek().kind {
1709            SyntaxKind::TerminalUnderscore => Ok(self.take::<TerminalUnderscore<'_>>().into()),
1710            SyntaxKind::TerminalAt => {
1711                let op = self.take::<TerminalAt<'_>>().into();
1712                let expr = self.parse_type_expr();
1713                Ok(ExprUnary::new_green(self.db, op, expr).into())
1714            }
1715            SyntaxKind::TerminalAnd | SyntaxKind::TerminalAndAnd => {
1716                self.unglue_andand_for_unary();
1717                let op = self.take::<TerminalAnd<'_>>().into();
1718                let expr = self.parse_type_expr();
1719                Ok(ExprUnary::new_green(self.db, op, expr).into())
1720            }
1721            SyntaxKind::TerminalIdentifier | SyntaxKind::TerminalDollar => {
1722                Ok(self.parse_type_path().into())
1723            }
1724            SyntaxKind::TerminalLParen => Ok(self.expect_type_tuple_expr()),
1725            SyntaxKind::TerminalLBrack => Ok(self.expect_type_fixed_size_array_expr()),
1726            _ => {
1727                // TODO(yuval): report to diagnostics.
1728                Err(TryParseFailure::SkipToken)
1729            }
1730        }
1731    }
1732
1733    /// Returns a GreenId of a node with an ExprPath|ExprParenthesized|ExprTuple kind, or
1734    /// ExprMissing if such an expression can't be parsed.
1735    fn parse_type_expr(&mut self) -> ExprGreen<'a> {
1736        match self.try_parse_type_expr() {
1737            Ok(expr) => expr,
1738            Err(_) => self
1739                .create_and_report_missing::<Expr<'_>>(ParserDiagnosticKind::MissingTypeExpression),
1740        }
1741    }
1742
1743    /// Assumes the current token is LBrace.
1744    /// Expected pattern: `\{<StructArgList>\}`
1745    fn expect_struct_ctor_argument_list_braced(&mut self) -> StructArgListBracedGreen<'a> {
1746        let lbrace = self.take::<TerminalLBrace<'_>>();
1747        let arg_list = StructArgList::new_green(
1748            self.db,
1749            &self.parse_separated_list::<StructArg<'_>, TerminalComma<'_>, StructArgListElementOrSeparatorGreen<'_>>(
1750                Self::try_parse_struct_ctor_argument,
1751                is_of_kind!(rparen, block, rbrace, module_item_kw),
1752                "struct constructor argument",
1753            ),
1754        );
1755        let rbrace = self.parse_token::<TerminalRBrace<'_>>();
1756
1757        StructArgListBraced::new_green(self.db, lbrace, arg_list, rbrace)
1758    }
1759
1760    /// Assumes the current token is LParen.
1761    /// Expected pattern: `<ArgListParenthesized>`.
1762    fn expect_function_call(&mut self, path: ExprPathGreen<'a>) -> ExprFunctionCallGreen<'a> {
1763        let func_name = path;
1764        let parenthesized_args = self.expect_parenthesized_argument_list();
1765        ExprFunctionCall::new_green(self.db, func_name, parenthesized_args)
1766    }
1767
1768    /// Assumes the current token is TerminalNot.
1769    /// Expected pattern: `!<WrappedArgList>`.
1770    fn expect_macro_call(&mut self, path: ExprPathGreen<'a>) -> ExprInlineMacroGreen<'a> {
1771        let bang = self.take::<TerminalNot<'_>>();
1772        let macro_name = path;
1773        let token_tree_node = self.parse_token_tree_node();
1774        ExprInlineMacro::new_green(self.db, macro_name, bang, token_tree_node)
1775    }
1776
1777    /// Either parses a leaf of the tree (i.e. any non-parenthesis token) or an inner node (i.e. a
1778    /// parenthesized stream of tokens).
1779    fn parse_token_tree(&mut self) -> TokenTreeGreen<'a> {
1780        match self.peek().kind {
1781            SyntaxKind::TerminalLBrace
1782            | SyntaxKind::TerminalLParen
1783            | SyntaxKind::TerminalLBrack => self.parse_token_tree_node().into(),
1784            SyntaxKind::TerminalDollar => {
1785                let dollar: TerminalDollarGreen<'_> = self.take::<TerminalDollar<'_>>();
1786                match self.peek().kind {
1787                    SyntaxKind::TerminalLParen => {
1788                        let lparen = self.take::<TerminalLParen<'_>>();
1789                        let elements = TokenList::new_green(self.db, &self.parse_token_list());
1790                        let rparen = self.parse_token::<TerminalRParen<'_>>();
1791                        let separator: OptionTerminalCommaGreen<'_> = match self.peek().kind {
1792                            SyntaxKind::TerminalComma => self.take::<TerminalComma<'_>>().into(),
1793                            _ => OptionTerminalCommaEmpty::new_green(self.db).into(),
1794                        };
1795                        let operator = match self.peek().kind {
1796                            SyntaxKind::TerminalQuestionMark => {
1797                                self.take::<TerminalQuestionMark<'_>>().into()
1798                            }
1799                            SyntaxKind::TerminalPlus => self.take::<TerminalPlus<'_>>().into(),
1800                            SyntaxKind::TerminalMul => self.take::<TerminalMul<'_>>().into(),
1801                            _ => unreachable!(),
1802                        };
1803                        TokenTreeRepetition::new_green(
1804                            self.db, dollar, lparen, elements, rparen, separator, operator,
1805                        )
1806                        .into()
1807                    }
1808                    SyntaxKind::TerminalIdentifier => {
1809                        let identifier = self.take::<TerminalIdentifier<'_>>();
1810                        TokenTreeParam::new_green(self.db, dollar, identifier).into()
1811                    }
1812                    _ => self.parse_token_tree_leaf().into(),
1813                }
1814            }
1815            _ => self.parse_token_tree_leaf().into(),
1816        }
1817    }
1818
1819    fn parse_token_tree_leaf(&mut self) -> TokenTreeLeafGreen<'a> {
1820        let token_node = self.take_token_node();
1821        TokenTreeLeaf::new_green(self.db, token_node)
1822    }
1823
1824    fn parse_token_tree_node(&mut self) -> TokenTreeNodeGreen<'a> {
1825        let wrapped_token_tree = match self.peek().kind {
1826            SyntaxKind::TerminalLBrace => self
1827                .expect_wrapped_token_tree::<TerminalLBrace<'_>, TerminalRBrace<'_>, _, _>(
1828                    BracedTokenTree::new_green,
1829                )
1830                .into(),
1831            SyntaxKind::TerminalLParen => self
1832                .expect_wrapped_token_tree::<TerminalLParen<'_>, TerminalRParen<'_>, _, _>(
1833                    ParenthesizedTokenTree::new_green,
1834                )
1835                .into(),
1836            SyntaxKind::TerminalLBrack => self
1837                .expect_wrapped_token_tree::<TerminalLBrack<'_>, TerminalRBrack<'_>, _, _>(
1838                    BracketedTokenTree::new_green,
1839                )
1840                .into(),
1841            _ => {
1842                return self.create_and_report_missing::<TokenTreeNode<'_>>(
1843                    ParserDiagnosticKind::MissingWrappedArgList,
1844                );
1845            }
1846        };
1847        TokenTreeNode::new_green(self.db, wrapped_token_tree)
1848    }
1849
1850    /// Assumes the current token is LTerminal.
1851    /// Expected pattern: `[LTerminal](<expr>,)*<expr>?[RTerminal]`
1852    /// Gets `new_green` a green id node builder for the list of the requested type, applies it to
1853    /// the parsed list and returns the result.
1854    fn expect_wrapped_token_tree<
1855        LTerminal: syntax::node::Terminal<'a>,
1856        RTerminal: syntax::node::Terminal<'a>,
1857        ListGreen,
1858        NewGreen: Fn(&'a dyn Database, LTerminal::Green, TokenListGreen<'a>, RTerminal::Green) -> ListGreen,
1859    >(
1860        &mut self,
1861        new_green: NewGreen,
1862    ) -> ListGreen {
1863        let l_term = self.take::<LTerminal>();
1864        let tokens = self.parse_token_list();
1865        let r_term: <RTerminal as TypedSyntaxNode<'_>>::Green = self.parse_token::<RTerminal>();
1866        new_green(self.db, l_term, TokenList::new_green(self.db, &tokens), r_term)
1867    }
1868
1869    fn parse_token_list(&mut self) -> Vec<TokenTreeGreen<'a>> {
1870        let mut tokens: Vec<TokenTreeGreen<'_>> = vec![];
1871        while !matches!(
1872            self.peek().kind,
1873            SyntaxKind::TerminalRParen
1874                | SyntaxKind::TerminalRBrace
1875                | SyntaxKind::TerminalRBrack
1876                | SyntaxKind::TerminalEndOfFile
1877        ) {
1878            tokens.push(self.parse_token_tree());
1879        }
1880        tokens
1881    }
1882
1883    /// Takes a TokenNode according to the current SyntaxKind.
1884    fn take_token_node(&mut self) -> TokenNodeGreen<'a> {
1885        match self.peek().kind {
1886            SyntaxKind::TerminalIdentifier => self.take::<TerminalIdentifier<'_>>().into(),
1887            SyntaxKind::TerminalLiteralNumber => self.take::<TerminalLiteralNumber<'_>>().into(),
1888            SyntaxKind::TerminalShortString => self.take::<TerminalShortString<'_>>().into(),
1889            SyntaxKind::TerminalString => self.take::<TerminalString<'_>>().into(),
1890            SyntaxKind::TerminalAs => self.take::<TerminalAs<'_>>().into(),
1891            SyntaxKind::TerminalConst => self.take::<TerminalConst<'_>>().into(),
1892            SyntaxKind::TerminalElse => self.take::<TerminalElse<'_>>().into(),
1893            SyntaxKind::TerminalEnum => self.take::<TerminalEnum<'_>>().into(),
1894            SyntaxKind::TerminalExtern => self.take::<TerminalExtern<'_>>().into(),
1895            SyntaxKind::TerminalFalse => self.take::<TerminalFalse<'_>>().into(),
1896            SyntaxKind::TerminalFunction => self.take::<TerminalFunction<'_>>().into(),
1897            SyntaxKind::TerminalIf => self.take::<TerminalIf<'_>>().into(),
1898            SyntaxKind::TerminalWhile => self.take::<TerminalWhile<'_>>().into(),
1899            SyntaxKind::TerminalFor => self.take::<TerminalFor<'_>>().into(),
1900            SyntaxKind::TerminalLoop => self.take::<TerminalLoop<'_>>().into(),
1901            SyntaxKind::TerminalImpl => self.take::<TerminalImpl<'_>>().into(),
1902            SyntaxKind::TerminalImplicits => self.take::<TerminalImplicits<'_>>().into(),
1903            SyntaxKind::TerminalLet => self.take::<TerminalLet<'_>>().into(),
1904            SyntaxKind::TerminalMatch => self.take::<TerminalMatch<'_>>().into(),
1905            SyntaxKind::TerminalModule => self.take::<TerminalModule<'_>>().into(),
1906            SyntaxKind::TerminalMut => self.take::<TerminalMut<'_>>().into(),
1907            SyntaxKind::TerminalNoPanic => self.take::<TerminalNoPanic<'_>>().into(),
1908            SyntaxKind::TerminalOf => self.take::<TerminalOf<'_>>().into(),
1909            SyntaxKind::TerminalRef => self.take::<TerminalRef<'_>>().into(),
1910            SyntaxKind::TerminalContinue => self.take::<TerminalContinue<'_>>().into(),
1911            SyntaxKind::TerminalReturn => self.take::<TerminalReturn<'_>>().into(),
1912            SyntaxKind::TerminalBreak => self.take::<TerminalBreak<'_>>().into(),
1913            SyntaxKind::TerminalStruct => self.take::<TerminalStruct<'_>>().into(),
1914            SyntaxKind::TerminalTrait => self.take::<TerminalTrait<'_>>().into(),
1915            SyntaxKind::TerminalTrue => self.take::<TerminalTrue<'_>>().into(),
1916            SyntaxKind::TerminalType => self.take::<TerminalType<'_>>().into(),
1917            SyntaxKind::TerminalUse => self.take::<TerminalUse<'_>>().into(),
1918            SyntaxKind::TerminalPub => self.take::<TerminalPub<'_>>().into(),
1919            SyntaxKind::TerminalAnd => self.take::<TerminalAnd<'_>>().into(),
1920            SyntaxKind::TerminalAndAnd => self.take::<TerminalAndAnd<'_>>().into(),
1921            SyntaxKind::TerminalArrow => self.take::<TerminalArrow<'_>>().into(),
1922            SyntaxKind::TerminalAt => self.take::<TerminalAt<'_>>().into(),
1923            SyntaxKind::TerminalBadCharacters => self.take::<TerminalBadCharacters<'_>>().into(),
1924            SyntaxKind::TerminalColon => self.take::<TerminalColon<'_>>().into(),
1925            SyntaxKind::TerminalColonColon => self.take::<TerminalColonColon<'_>>().into(),
1926            SyntaxKind::TerminalComma => self.take::<TerminalComma<'_>>().into(),
1927            SyntaxKind::TerminalDiv => self.take::<TerminalDiv<'_>>().into(),
1928            SyntaxKind::TerminalDivEq => self.take::<TerminalDivEq<'_>>().into(),
1929            SyntaxKind::TerminalDollar => self.take::<TerminalDollar<'_>>().into(),
1930            SyntaxKind::TerminalDot => self.take::<TerminalDot<'_>>().into(),
1931            SyntaxKind::TerminalDotDot => self.take::<TerminalDotDot<'_>>().into(),
1932            SyntaxKind::TerminalDotDotEq => self.take::<TerminalDotDotEq<'_>>().into(),
1933            SyntaxKind::TerminalEndOfFile => self.take::<TerminalEndOfFile<'_>>().into(),
1934            SyntaxKind::TerminalEq => self.take::<TerminalEq<'_>>().into(),
1935            SyntaxKind::TerminalEqEq => self.take::<TerminalEqEq<'_>>().into(),
1936            SyntaxKind::TerminalGE => self.take::<TerminalGE<'_>>().into(),
1937            SyntaxKind::TerminalGT => self.take::<TerminalGT<'_>>().into(),
1938            SyntaxKind::TerminalHash => self.take::<TerminalHash<'_>>().into(),
1939            SyntaxKind::TerminalLBrace => self.take::<TerminalLBrace<'_>>().into(),
1940            SyntaxKind::TerminalLBrack => self.take::<TerminalLBrack<'_>>().into(),
1941            SyntaxKind::TerminalLE => self.take::<TerminalLE<'_>>().into(),
1942            SyntaxKind::TerminalLParen => self.take::<TerminalLParen<'_>>().into(),
1943            SyntaxKind::TerminalLT => self.take::<TerminalLT<'_>>().into(),
1944            SyntaxKind::TerminalMatchArrow => self.take::<TerminalMatchArrow<'_>>().into(),
1945            SyntaxKind::TerminalMinus => self.take::<TerminalMinus<'_>>().into(),
1946            SyntaxKind::TerminalMinusEq => self.take::<TerminalMinusEq<'_>>().into(),
1947            SyntaxKind::TerminalMod => self.take::<TerminalMod<'_>>().into(),
1948            SyntaxKind::TerminalModEq => self.take::<TerminalModEq<'_>>().into(),
1949            SyntaxKind::TerminalMul => self.take::<TerminalMul<'_>>().into(),
1950            SyntaxKind::TerminalMulEq => self.take::<TerminalMulEq<'_>>().into(),
1951            SyntaxKind::TerminalNeq => self.take::<TerminalNeq<'_>>().into(),
1952            SyntaxKind::TerminalNot => self.take::<TerminalNot<'_>>().into(),
1953            SyntaxKind::TerminalBitNot => self.take::<TerminalBitNot<'_>>().into(),
1954            SyntaxKind::TerminalOr => self.take::<TerminalOr<'_>>().into(),
1955            SyntaxKind::TerminalOrOr => self.take::<TerminalOrOr<'_>>().into(),
1956            SyntaxKind::TerminalPlus => self.take::<TerminalPlus<'_>>().into(),
1957            SyntaxKind::TerminalPlusEq => self.take::<TerminalPlusEq<'_>>().into(),
1958            SyntaxKind::TerminalQuestionMark => self.take::<TerminalQuestionMark<'_>>().into(),
1959            SyntaxKind::TerminalRBrace => self.take::<TerminalRBrace<'_>>().into(),
1960            SyntaxKind::TerminalRBrack => self.take::<TerminalRBrack<'_>>().into(),
1961            SyntaxKind::TerminalRParen => self.take::<TerminalRParen<'_>>().into(),
1962            SyntaxKind::TerminalSemicolon => self.take::<TerminalSemicolon<'_>>().into(),
1963            SyntaxKind::TerminalUnderscore => self.take::<TerminalUnderscore<'_>>().into(),
1964            SyntaxKind::TerminalXor => self.take::<TerminalXor<'_>>().into(),
1965            other => unreachable!("Unexpected token kind: {other:?}"),
1966        }
1967    }
1968    /// Returns a GreenId of a node with an ArgListParenthesized|ArgListBracketed|ArgListBraced kind
1969    /// or TryParseFailure if such an argument list can't be parsed.
1970    pub(crate) fn parse_wrapped_arg_list(&mut self) -> WrappedArgListGreen<'a> {
1971        match self.peek().kind {
1972            SyntaxKind::TerminalLParen => self
1973                .expect_wrapped_argument_list::<TerminalLParen<'_>, TerminalRParen<'_>, _, _>(
1974                    ArgListParenthesized::new_green,
1975                )
1976                .into(),
1977            SyntaxKind::TerminalLBrack => self
1978                .expect_wrapped_argument_list::<TerminalLBrack<'_>, TerminalRBrack<'_>, _, _>(
1979                    ArgListBracketed::new_green,
1980                )
1981                .into(),
1982            SyntaxKind::TerminalLBrace => self
1983                .expect_wrapped_argument_list::<TerminalLBrace<'_>, TerminalRBrace<'_>, _, _>(
1984                    ArgListBraced::new_green,
1985                )
1986                .into(),
1987            _ => self.create_and_report_missing::<WrappedArgList<'_>>(
1988                ParserDiagnosticKind::MissingWrappedArgList,
1989            ),
1990        }
1991    }
1992
1993    /// Assumes the current token is LTerminal.
1994    /// Expected pattern: `[LTerminal](<expr>,)*<expr>?[RTerminal]`
1995    /// Gets `new_green` a green id node builder for the list of the requested type, applies it to
1996    /// the parsed list and returns the result.
1997    fn expect_wrapped_argument_list<
1998        LTerminal: syntax::node::Terminal<'a>,
1999        RTerminal: syntax::node::Terminal<'a>,
2000        ListGreen,
2001        NewGreen: Fn(&'a dyn Database, LTerminal::Green, ArgListGreen<'a>, RTerminal::Green) -> ListGreen,
2002    >(
2003        &mut self,
2004        new_green: NewGreen,
2005    ) -> ListGreen {
2006        let l_term = self.take::<LTerminal>();
2007        let exprs: Vec<ArgListElementOrSeparatorGreen<'_>> = self
2008            .parse_separated_list::<Arg<'_>, TerminalComma<'_>, ArgListElementOrSeparatorGreen<'_>>(
2009                Self::try_parse_function_argument,
2010                is_of_kind!(rparen, rbrace, rbrack, block, module_item_kw),
2011                "argument",
2012            );
2013        let r_term: <RTerminal as TypedSyntaxNode<'_>>::Green = self.parse_token::<RTerminal>();
2014        new_green(self.db, l_term, ArgList::new_green(self.db, &exprs), r_term)
2015    }
2016
2017    /// Assumes the current token is LParen.
2018    /// Expected pattern: `\(<ArgList>\)`.
2019    fn expect_parenthesized_argument_list(&mut self) -> ArgListParenthesizedGreen<'a> {
2020        self.expect_wrapped_argument_list::<TerminalLParen<'_>, TerminalRParen<'_>, _, _>(
2021            ArgListParenthesized::new_green,
2022        )
2023    }
2024
2025    /// Tries to parse parenthesized argument list.
2026    /// Expected pattern: `\(<ArgList>\)`.
2027    fn try_parse_parenthesized_argument_list(&mut self) -> OptionArgListParenthesizedGreen<'a> {
2028        if self.peek().kind == SyntaxKind::TerminalLParen {
2029            self.expect_parenthesized_argument_list().into()
2030        } else {
2031            OptionArgListParenthesizedEmpty::new_green(self.db).into()
2032        }
2033    }
2034
2035    /// Parses a function call's argument, which contains possibly modifiers, and an argument
2036    /// clause.
2037    fn try_parse_function_argument(&mut self) -> TryParseResult<ArgGreen<'a>> {
2038        let modifiers_list = self.parse_modifier_list();
2039        let arg_clause = self.try_parse_argument_clause();
2040        match arg_clause {
2041            Ok(arg_clause) => {
2042                let modifiers = ModifierList::new_green(self.db, &modifiers_list);
2043                Ok(Arg::new_green(self.db, modifiers, arg_clause))
2044            }
2045            Err(_) if !modifiers_list.is_empty() => {
2046                let modifiers = ModifierList::new_green(self.db, &modifiers_list);
2047                let arg_clause = ArgClauseUnnamed::new_green(self.db, self.parse_expr()).into();
2048                Ok(Arg::new_green(self.db, modifiers, arg_clause))
2049            }
2050            Err(err) => Err(err),
2051        }
2052    }
2053
2054    /// Parses a function call's argument, which is an expression with or without the name
2055    /// of the argument.
2056    ///
2057    /// Possible patterns:
2058    /// * `<Expr>` (unnamed).
2059    /// * `<Identifier>: <Expr>` (named).
2060    /// * `:<Identifier>` (Field init shorthand - syntactic sugar for `a: a`).
2061    fn try_parse_argument_clause(&mut self) -> TryParseResult<ArgClauseGreen<'a>> {
2062        if self.peek().kind == SyntaxKind::TerminalColon {
2063            let colon = self.take::<TerminalColon<'_>>();
2064            let name = self.parse_identifier();
2065            return Ok(ArgClauseFieldInitShorthand::new_green(
2066                self.db,
2067                colon,
2068                ExprFieldInitShorthand::new_green(self.db, name),
2069            )
2070            .into());
2071        }
2072
2073        // Read an expression.
2074        let value = self.try_parse_expr()?;
2075        // If the next token is `:` and the expression is an identifier, this is the argument's
2076        // name.
2077        Ok(
2078            if self.peek().kind == SyntaxKind::TerminalColon
2079                && let Some(argname) = self.try_extract_identifier(value)
2080            {
2081                let colon = self.take::<TerminalColon<'_>>();
2082                let expr = self.parse_expr();
2083                ArgClauseNamed::new_green(self.db, argname, colon, expr).into()
2084            } else {
2085                ArgClauseUnnamed::new_green(self.db, value).into()
2086            },
2087        )
2088    }
2089
2090    /// If the given `expr` is a simple identifier, returns the corresponding green node.
2091    /// Otherwise, returns `TryParseFailure`.
2092    fn try_extract_identifier(&self, expr: ExprGreen<'a>) -> Option<TerminalIdentifierGreen<'a>> {
2093        // Check that `expr` is `ExprPath`.
2094        let GreenNode {
2095            kind: SyntaxKind::ExprPath,
2096            details: GreenNodeDetails::Node { children: children0, .. },
2097        } = expr.0.long(self.db)
2098        else {
2099            return None;
2100        };
2101
2102        // Extract ExprPathInner
2103        let [_dollar, path_inner] = children0[..] else {
2104            return None;
2105        };
2106
2107        let GreenNode {
2108            kind: SyntaxKind::ExprPathInner,
2109            details: GreenNodeDetails::Node { children: children1, .. },
2110        } = path_inner.long(self.db)
2111        else {
2112            return None;
2113        };
2114
2115        // Check that it has one child.
2116        let [path_segment] = children1[..] else {
2117            return None;
2118        };
2119
2120        // Check that `path_segment` is `PathSegmentSimple`.
2121        let GreenNode {
2122            kind: SyntaxKind::PathSegmentSimple,
2123            details: GreenNodeDetails::Node { children: children2, .. },
2124        } = path_segment.long(self.db)
2125        else {
2126            return None;
2127        };
2128
2129        // Check that it has one child.
2130        let [ident] = children2[..] else {
2131            return None;
2132        };
2133
2134        // Check that it is indeed `TerminalIdentifier`.
2135        let GreenNode { kind: SyntaxKind::TerminalIdentifier, .. } = ident.long(self.db) else {
2136            return None;
2137        };
2138
2139        Some(TerminalIdentifierGreen(ident))
2140    }
2141
2142    /// Assumes the current token is LBrace.
2143    /// Expected pattern: `<StructArgListBraced>`.
2144    fn expect_constructor_call(&mut self, path: ExprPathGreen<'a>) -> ExprStructCtorCallGreen<'a> {
2145        let ctor_name = path;
2146        let args = self.expect_struct_ctor_argument_list_braced();
2147        ExprStructCtorCall::new_green(self.db, ctor_name, args)
2148    }
2149
2150    /// Assumes the current token is LParen.
2151    /// Expected pattern: `\((<expr>,)*<expr>?\)`
2152    /// Returns a GreenId of a node with kind ExprParenthesized|ExprTuple.
2153    fn expect_parenthesized_expr(&mut self) -> ExprGreen<'a> {
2154        let lparen = self.take::<TerminalLParen<'_>>();
2155        let exprs: Vec<ExprListElementOrSeparatorGreen<'_>> = self
2156            .parse_separated_list::<Expr<'_>, TerminalComma<'_>, ExprListElementOrSeparatorGreen<'_>>(
2157                Self::try_parse_expr,
2158                is_of_kind!(rparen, block, rbrace, module_item_kw),
2159                "expression",
2160            );
2161        let rparen = self.parse_token::<TerminalRParen<'_>>();
2162
2163        if let [ExprListElementOrSeparatorGreen::Element(expr)] = &exprs[..] {
2164            // We have exactly one item and no separator --> This is not a tuple.
2165            ExprParenthesized::new_green(self.db, lparen, *expr, rparen).into()
2166        } else {
2167            ExprListParenthesized::new_green(
2168                self.db,
2169                lparen,
2170                ExprList::new_green(self.db, &exprs),
2171                rparen,
2172            )
2173            .into()
2174        }
2175    }
2176
2177    /// Assumes the current token is LParen.
2178    /// Expected pattern: `\((<type_expr>,)*<type_expr>?\)`
2179    /// Returns a GreenId of a node with kind ExprTuple.
2180    fn expect_type_tuple_expr(&mut self) -> ExprGreen<'a> {
2181        let lparen = self.take::<TerminalLParen<'_>>();
2182        let exprs: Vec<ExprListElementOrSeparatorGreen<'_>> = self
2183            .parse_separated_list::<Expr<'_>, TerminalComma<'_>, ExprListElementOrSeparatorGreen<'_>>(
2184                Self::try_parse_type_expr,
2185                is_of_kind!(rparen, block, rbrace, module_item_kw),
2186                "type expression",
2187            );
2188        let rparen = self.parse_token::<TerminalRParen<'_>>();
2189        if let [ExprListElementOrSeparatorGreen::Element(_)] = &exprs[..] {
2190            self.add_diagnostic(
2191                ParserDiagnosticKind::MissingToken(SyntaxKind::TokenComma),
2192                TextSpan::cursor(self.offset),
2193            );
2194        }
2195        ExprListParenthesized::new_green(
2196            self.db,
2197            lparen,
2198            ExprList::new_green(self.db, &exprs),
2199            rparen,
2200        )
2201        .into()
2202    }
2203
2204    /// Assumes the current token is LBrack.
2205    /// Expected pattern: `\[<type_expr>; <expr>\]`.
2206    /// Returns a GreenId of a node with kind ExprFixedSizeArray.
2207    fn expect_type_fixed_size_array_expr(&mut self) -> ExprGreen<'a> {
2208        let lbrack = self.take::<TerminalLBrack<'_>>();
2209        let exprs: Vec<ExprListElementOrSeparatorGreen<'_>> = self
2210            .parse_separated_list::<Expr<'_>, TerminalComma<'_>, ExprListElementOrSeparatorGreen<'_>>(
2211                Self::try_parse_type_expr,
2212                is_of_kind!(rbrack, semicolon),
2213                "type expression",
2214            );
2215        let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
2216        let size_expr = self.parse_expr();
2217        let fixed_size_array_size =
2218            FixedSizeArraySize::new_green(self.db, semicolon, size_expr).into();
2219        let rbrack = self.parse_token::<TerminalRBrack<'_>>();
2220        ExprFixedSizeArray::new_green(
2221            self.db,
2222            lbrack,
2223            ExprList::new_green(self.db, &exprs),
2224            fixed_size_array_size,
2225            rbrack,
2226        )
2227        .into()
2228    }
2229
2230    /// Assumes the current token is DotDot.
2231    /// Expected pattern: `\.\.<Expr>`.
2232    fn expect_struct_argument_tail(&mut self) -> StructArgTailGreen<'a> {
2233        let dotdot = self.take::<TerminalDotDot<'_>>(); // ..
2234        // TODO(yuval): consider changing this to SimpleExpr once it exists.
2235        let expr = self.parse_expr();
2236        StructArgTail::new_green(self.db, dotdot, expr)
2237    }
2238
2239    // For the similar syntax in Rust, see
2240    // https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax.
2241    /// Like parse_argument, but also allows a struct-arg-tail, e.g. 'let s2 = S{"s2", ..s1};'
2242    /// Returns a GreenId of a node with kind StructArgSingle|StructArgTail.
2243    fn try_parse_struct_ctor_argument(&mut self) -> TryParseResult<StructArgGreen<'a>> {
2244        match self.peek().kind {
2245            SyntaxKind::TerminalDotDot => Ok(self.expect_struct_argument_tail().into()),
2246            _ => self.try_parse_argument_single().map(|arg| arg.into()),
2247        }
2248    }
2249
2250    /// Returns a GreenId of a node with kind StructArgExpr or OptionStructArgExprEmpty if an
2251    /// argument expression `(":<value>")` can't be parsed.
2252    fn parse_option_struct_arg_expression(&mut self) -> OptionStructArgExprGreen<'a> {
2253        if self.peek().kind == SyntaxKind::TerminalColon {
2254            let colon = self.take::<TerminalColon<'_>>();
2255            let value = self.parse_expr();
2256            StructArgExpr::new_green(self.db, colon, value).into()
2257        } else {
2258            OptionStructArgExprEmpty::new_green(self.db).into()
2259        }
2260    }
2261
2262    /// Returns a GreenId of a node with kind OptionExprClause or OptionExprClauseEmpty if an
2263    /// argument expression `("Expr")` can't be parsed.
2264    fn parse_option_expression_clause(&mut self) -> OptionExprClauseGreen<'a> {
2265        if self.peek().kind == SyntaxKind::TerminalSemicolon {
2266            OptionExprClauseEmpty::new_green(self.db).into()
2267        } else {
2268            let value = self.parse_expr();
2269            ExprClause::new_green(self.db, value).into()
2270        }
2271    }
2272
2273    /// Returns a GreenId of a node with kind StructArgSingle.
2274    fn try_parse_argument_single(&mut self) -> TryParseResult<StructArgSingleGreen<'a>> {
2275        let identifier = self.try_parse_identifier()?;
2276        let struct_arg_expr = self.parse_option_struct_arg_expression(); // :<expr>
2277        Ok(StructArgSingle::new_green(self.db, identifier, struct_arg_expr))
2278    }
2279
2280    /// Returns a GreenId of a node with kind ExprBlock.
2281    fn parse_block(&mut self) -> ExprBlockGreen<'a> {
2282        let skipped_tokens = self.skip_until(is_of_kind!(rbrace, lbrace, module_item_kw, block));
2283
2284        if let Err(SkippedError(span)) = skipped_tokens {
2285            self.add_diagnostic(
2286                ParserDiagnosticKind::SkippedElement { element_name: "'{'".into() },
2287                span,
2288            );
2289        }
2290
2291        let is_rbrace_or_top_level = is_of_kind!(rbrace, module_item_kw);
2292        if is_rbrace_or_top_level(self.peek().kind) {
2293            return ExprBlock::new_green(
2294                self.db,
2295                self.create_and_report_missing_terminal::<TerminalLBrace<'_>>(),
2296                StatementList::new_green(self.db, &[]),
2297                TerminalRBrace::missing(self.db),
2298            );
2299        }
2300        // Don't report diagnostic if one has already been reported.
2301        let lbrace = self.parse_token_ex::<TerminalLBrace<'_>>(skipped_tokens.is_ok());
2302        let statements = StatementList::new_green(
2303            self.db,
2304            &self.parse_list(
2305                Self::try_parse_statement,
2306                is_of_kind!(rbrace, module_item_kw),
2307                "statement",
2308            ),
2309        );
2310        let rbrace = self.parse_token::<TerminalRBrace<'_>>();
2311        ExprBlock::new_green(self.db, lbrace, statements, rbrace)
2312    }
2313
2314    /// Assumes the current token is `Match`.
2315    /// Expected pattern: `match <expr> \{<MatchArm>*\}`
2316    fn expect_match_expr(&mut self) -> ExprMatchGreen<'a> {
2317        let match_kw = self.take::<TerminalMatch<'_>>();
2318        let expr =
2319            self.parse_expr_limited(MAX_PRECEDENCE, LbraceAllowed::Forbid, AndLetBehavior::Simple);
2320        let lbrace = self.parse_token::<TerminalLBrace<'_>>();
2321        let arms = MatchArms::new_green(
2322            self.db,
2323            &self
2324                .parse_separated_list::<MatchArm<'_>, TerminalComma<'_>, MatchArmsElementOrSeparatorGreen<'_>>(
2325                    Self::try_parse_match_arm,
2326                    is_of_kind!(block, rbrace, module_item_kw),
2327                    "match arm",
2328                ),
2329        );
2330        let rbrace = self.parse_token::<TerminalRBrace<'_>>();
2331        ExprMatch::new_green(self.db, match_kw, expr, lbrace, arms, rbrace)
2332    }
2333
2334    /// Assumes the current token is `If`.
2335    fn expect_if_expr(&mut self) -> ExprIfGreen<'a> {
2336        let if_kw = self.take::<TerminalIf<'a>>();
2337
2338        let conditions = self.parse_condition_list();
2339        let if_block = self.parse_block();
2340        let else_clause = if self.peek().kind == SyntaxKind::TerminalElse {
2341            let else_kw = self.take::<TerminalElse<'a>>();
2342            let else_block_or_if = if self.peek().kind == SyntaxKind::TerminalIf {
2343                self.expect_if_expr().into()
2344            } else {
2345                self.parse_block().into()
2346            };
2347            ElseClause::new_green(self.db, else_kw, else_block_or_if).into()
2348        } else {
2349            OptionElseClauseEmpty::new_green(self.db).into()
2350        };
2351        ExprIf::new_green(self.db, if_kw, conditions, if_block, else_clause)
2352    }
2353
2354    /// If `condition` is a [ConditionExpr] of the form `<expr> <op> <expr>`, returns the operator's
2355    /// kind.
2356    /// Otherwise, returns `None`.
2357    fn get_binary_operator(&self, condition: ConditionGreen<'_>) -> Option<SyntaxKind> {
2358        let condition_expr_green = condition.0.long(self.db);
2359        require(condition_expr_green.kind == SyntaxKind::ConditionExpr)?;
2360
2361        let expr_binary_green = condition_expr_green.children()[0].long(self.db);
2362        require(expr_binary_green.kind == SyntaxKind::ExprBinary)?;
2363
2364        Some(expr_binary_green.children()[1].long(self.db).kind)
2365    }
2366
2367    /// Parses a conjunction of conditions of the form `<condition> && <condition> && ...`,
2368    /// where each condition is either `<expr>` or `let <pattern> = <expr>`.
2369    ///
2370    /// Assumes the next expected token (after the condition list) is `{`. This assumption is used
2371    /// in case of an error.
2372    fn parse_condition_list(&mut self) -> ConditionListAndGreen<'a> {
2373        let and_and_precedence = get_post_operator_precedence(SyntaxKind::TerminalAndAnd).unwrap();
2374
2375        let start_offset = self.offset.add_width(self.current_width);
2376        let condition = self.parse_condition_expr(false);
2377        let mut conditions: Vec<ConditionListAndElementOrSeparatorGreen<'_>> =
2378            vec![condition.into()];
2379
2380        // If there is more than one condition, check that the first condition does not have a
2381        // precedence lower than `&&`.
2382        if self.peek().kind == SyntaxKind::TerminalAndAnd
2383            && let Some(op) = self.get_binary_operator(condition)
2384            && let Some(precedence) = get_post_operator_precedence(op)
2385            && precedence > and_and_precedence
2386        {
2387            let offset = self.offset.add_width(self.current_width - self.last_trivia_length);
2388            self.add_diagnostic(
2389                ParserDiagnosticKind::LowPrecedenceOperatorInIfLet { op },
2390                TextSpan::new(start_offset, offset),
2391            );
2392        }
2393
2394        while self.peek().kind == SyntaxKind::TerminalAndAnd {
2395            let and_and = self.take::<TerminalAndAnd<'a>>();
2396            conditions.push(and_and.into());
2397
2398            let condition = self.parse_condition_expr(true);
2399            conditions.push(condition.into());
2400        }
2401
2402        let peek_item = self.peek();
2403        if let Some(op_precedence) = get_post_operator_precedence(peek_item.kind)
2404            && op_precedence > and_and_precedence
2405        {
2406            self.add_diagnostic(
2407                ParserDiagnosticKind::LowPrecedenceOperatorInIfLet { op: peek_item.kind },
2408                TextSpan::cursor(self.offset.add_width(self.current_width)),
2409            );
2410            // Skip the rest of the tokens until `{`. Don't report additional diagnostics.
2411            let _ = self.skip_until(is_of_kind!(rbrace, lbrace, module_item_kw, block));
2412        }
2413        ConditionListAnd::new_green(self.db, &conditions)
2414    }
2415
2416    /// Parses condition exprs of the form `<expr>` or `let <pattern> = <expr>`.
2417    ///
2418    /// In the case of `let <pattern> = <expr>`, the parser will stop at the first `&&` token
2419    /// (which is not inside parenthesis).
2420    /// If `stop_at_and` is true, this will also be the case for `<expr>`.
2421    fn parse_condition_expr(&mut self, stop_at_and: bool) -> ConditionGreen<'a> {
2422        let and_and_precedence = get_post_operator_precedence(SyntaxKind::TerminalAndAnd).unwrap();
2423        if self.peek().kind == SyntaxKind::TerminalLet {
2424            let let_kw = self.take::<TerminalLet<'a>>();
2425            let pattern_list = self
2426            .parse_separated_list_inner::<Pattern<'_>, TerminalOr<'_>, PatternListOrElementOrSeparatorGreen<'_>>(
2427                Self::try_parse_pattern,
2428                is_of_kind!(eq),
2429                "pattern",
2430                Some(ParserDiagnosticKind::DisallowedTrailingSeparatorOr),
2431            );
2432
2433            let pattern_list_green = if pattern_list.is_empty() {
2434                self.create_and_report_missing::<PatternListOr<'_>>(
2435                    ParserDiagnosticKind::MissingPattern,
2436                )
2437            } else {
2438                PatternListOr::new_green(self.db, &pattern_list)
2439            };
2440            let eq = self.parse_token::<TerminalEq<'a>>();
2441            let expr: ExprGreen<'_> = self.parse_expr_limited(
2442                and_and_precedence,
2443                LbraceAllowed::Forbid,
2444                AndLetBehavior::Stop,
2445            );
2446            ConditionLet::new_green(self.db, let_kw, pattern_list_green, eq, expr).into()
2447        } else {
2448            let condition = self.parse_expr_limited(
2449                if stop_at_and { and_and_precedence } else { MAX_PRECEDENCE },
2450                LbraceAllowed::Forbid,
2451                AndLetBehavior::Stop,
2452            );
2453            ConditionExpr::new_green(self.db, condition).into()
2454        }
2455    }
2456
2457    /// Assumes the current token is `Loop`.
2458    /// Expected pattern: `loop <block>`.
2459    fn expect_loop_expr(&mut self) -> ExprLoopGreen<'a> {
2460        let loop_kw = self.take::<TerminalLoop<'a>>();
2461        let body = self.parse_block();
2462
2463        ExprLoop::new_green(self.db, loop_kw, body)
2464    }
2465
2466    /// Assumes the current token is `While`.
2467    /// Expected pattern: `while <condition> <block>`.
2468    fn expect_while_expr(&mut self) -> ExprWhileGreen<'a> {
2469        let while_kw = self.take::<TerminalWhile<'a>>();
2470        let conditions = self.parse_condition_list();
2471        let body = self.parse_block();
2472
2473        ExprWhile::new_green(self.db, while_kw, conditions, body)
2474    }
2475
2476    /// Assumes the current token is `For`.
2477    /// Expected pattern: `for <pattern> <identifier> <expression> <block>`.
2478    /// Identifier will be checked to be 'in' in semantics.
2479    fn expect_for_expr(&mut self) -> ExprForGreen<'a> {
2480        let for_kw = self.take::<TerminalFor<'a>>();
2481        let pattern = self.parse_pattern();
2482        let ident = self.take_raw();
2483        let in_identifier: TerminalIdentifierGreen<'_> = match ident.text.long(self.db).as_str() {
2484            "in" => self.add_trivia_to_terminal::<TerminalIdentifier<'_>>(ident),
2485            _ => {
2486                self.append_skipped_token_to_pending_trivia(
2487                    ident,
2488                    ParserDiagnosticKind::SkippedElement { element_name: "'in'".into() },
2489                );
2490                TerminalIdentifier::missing(self.db)
2491            }
2492        };
2493        let expression =
2494            self.parse_expr_limited(MAX_PRECEDENCE, LbraceAllowed::Forbid, AndLetBehavior::Simple);
2495        let body = self.parse_block();
2496        ExprFor::new_green(self.db, for_kw, pattern, in_identifier, expression, body)
2497    }
2498
2499    /// Assumes the current token is `|`.
2500    /// Expected pattern: `| <params> | <ReturnTypeClause> <expression>`.
2501    fn expect_closure_expr(&mut self) -> ExprClosureGreen<'a> {
2502        self.unglue::<TerminalOrOr<'_>, TerminalOr<'_>, TerminalOr<'_>>("|", "|");
2503        let leftor = self.take::<TerminalOr<'a>>();
2504        let params = self.parse_closure_param_list();
2505        let rightor = self.parse_token::<TerminalOr<'a>>();
2506        let params = ClosureParams::new_green(self.db, leftor, params, rightor);
2507        let mut block_required = self.peek().kind == SyntaxKind::TerminalArrow;
2508
2509        let return_ty = self.parse_option_return_type_clause();
2510        let optional_no_panic = if self.peek().kind == SyntaxKind::TerminalNoPanic {
2511            block_required = true;
2512            self.take::<TerminalNoPanic<'a>>().into()
2513        } else {
2514            OptionTerminalNoPanicEmpty::new_green(self.db).into()
2515        };
2516        let expr = if block_required { self.parse_block().into() } else { self.parse_expr() };
2517
2518        ExprClosure::new_green(self.db, params, return_ty, optional_no_panic, expr)
2519    }
2520
2521    /// Assumes the current token is LBrack.
2522    /// Expected pattern: `\[<expr>; <expr>\]`.
2523    fn expect_fixed_size_array_expr(&mut self) -> ExprFixedSizeArrayGreen<'a> {
2524        let lbrack = self.take::<TerminalLBrack<'_>>();
2525        let exprs: Vec<ExprListElementOrSeparatorGreen<'_>> = self
2526            .parse_separated_list::<Expr<'_>, TerminalComma<'_>, ExprListElementOrSeparatorGreen<'_>>(
2527                Self::try_parse_expr,
2528                is_of_kind!(rbrack, semicolon),
2529                "expression",
2530            );
2531        let size_green = if self.peek().kind == SyntaxKind::TerminalSemicolon {
2532            let semicolon = self.take::<TerminalSemicolon<'_>>();
2533            let size = self.parse_expr();
2534            FixedSizeArraySize::new_green(self.db, semicolon, size).into()
2535        } else {
2536            OptionFixedSizeArraySizeEmpty::new_green(self.db).into()
2537        };
2538        let rbrack = self.parse_token::<TerminalRBrack<'_>>();
2539        ExprFixedSizeArray::new_green(
2540            self.db,
2541            lbrack,
2542            ExprList::new_green(self.db, &exprs),
2543            size_green,
2544            rbrack,
2545        )
2546    }
2547
2548    /// Returns a GreenId of a node with a MatchArm kind or TryParseFailure if a match arm can't be
2549    /// parsed.
2550    pub fn try_parse_match_arm(&mut self) -> TryParseResult<MatchArmGreen<'a>> {
2551        let pattern_list = self
2552            .parse_separated_list_inner::<Pattern<'_>, TerminalOr<'_>, PatternListOrElementOrSeparatorGreen<'_>>(
2553                Self::try_parse_pattern,
2554                is_of_kind!(match_arrow, rparen, block, rbrace, module_item_kw),
2555                "pattern",
2556                Some(ParserDiagnosticKind::DisallowedTrailingSeparatorOr),
2557            );
2558        if pattern_list.is_empty() {
2559            return Err(TryParseFailure::SkipToken);
2560        }
2561
2562        let pattern_list_green = PatternListOr::new_green(self.db, &pattern_list);
2563
2564        let arrow = self.parse_token::<TerminalMatchArrow<'_>>();
2565        let expr = self.parse_expr();
2566        Ok(MatchArm::new_green(self.db, pattern_list_green, arrow, expr))
2567    }
2568
2569    /// Returns a GreenId of a node with some Pattern kind (see
2570    /// [syntax::node::ast::Pattern]) or TryParseFailure if a pattern can't be parsed.
2571    fn try_parse_pattern(&mut self) -> TryParseResult<PatternGreen<'a>> {
2572        let modifier_list = self.parse_modifier_list();
2573        if !modifier_list.is_empty() {
2574            let modifiers = ModifierList::new_green(self.db, &modifier_list);
2575            let name = self.parse_identifier();
2576            return Ok(PatternIdentifier::new_green(self.db, modifiers, name).into());
2577        };
2578
2579        // TODO(yuval): Support "Or" patterns.
2580        Ok(match self.peek().kind {
2581            SyntaxKind::TerminalLiteralNumber => self.take_terminal_literal_number().into(),
2582            SyntaxKind::TerminalShortString => self.take_terminal_short_string().into(),
2583            SyntaxKind::TerminalTrue => self.take::<TerminalTrue<'_>>().into(),
2584            SyntaxKind::TerminalFalse => self.take::<TerminalFalse<'_>>().into(),
2585            SyntaxKind::TerminalUnderscore => self.take::<TerminalUnderscore<'_>>().into(),
2586            SyntaxKind::TerminalIdentifier => {
2587                // TODO(ilya): Consider parsing a single identifier as PatternIdentifier rather
2588                // then ExprPath.
2589                let path = self.parse_path();
2590                match self.peek().kind {
2591                    SyntaxKind::TerminalLBrace => {
2592                        let lbrace = self.take::<TerminalLBrace<'_>>();
2593                        let params = PatternStructParamList::new_green(
2594                            self.db,
2595                            &self.parse_separated_list::<
2596                                PatternStructParam<'_>,
2597                                TerminalComma<'_>,
2598                                PatternStructParamListElementOrSeparatorGreen<'_>>
2599                            (
2600                                Self::try_parse_pattern_struct_param,
2601                                is_of_kind!(rparen, block, rbrace, module_item_kw),
2602                                "struct pattern parameter",
2603                            ),
2604                        );
2605                        let rbrace = self.parse_token::<TerminalRBrace<'_>>();
2606                        PatternStruct::new_green(self.db, path, lbrace, params, rbrace).into()
2607                    }
2608                    SyntaxKind::TerminalLParen => {
2609                        // Enum pattern.
2610                        let lparen = self.take::<TerminalLParen<'_>>();
2611                        let pattern = self.parse_pattern();
2612                        let rparen = self.parse_token::<TerminalRParen<'_>>();
2613                        let inner_pattern =
2614                            PatternEnumInnerPattern::new_green(self.db, lparen, pattern, rparen);
2615                        PatternEnum::new_green(self.db, path, inner_pattern.into()).into()
2616                    }
2617                    _ => {
2618                        // Check that `expr` is `ExprPath`.
2619                        let GreenNode {
2620                            kind: SyntaxKind::ExprPath,
2621                            details: GreenNodeDetails::Node { children: path_children, .. },
2622                        } = path.0.long(self.db)
2623                        else {
2624                            return Err(TryParseFailure::SkipToken);
2625                        };
2626
2627                        // Extract ExprPathInner
2628                        let [_dollar, path_inner] = path_children[..] else {
2629                            return Err(TryParseFailure::SkipToken);
2630                        };
2631
2632                        let GreenNode {
2633                            kind: SyntaxKind::ExprPathInner,
2634                            details: GreenNodeDetails::Node { children: inner_path_children, .. },
2635                        } = path_inner.long(self.db)
2636                        else {
2637                            return Err(TryParseFailure::SkipToken);
2638                        };
2639
2640                        // If the path has more than 1 element assume it's a simplified Enum variant
2641                        // Eg. MyEnum::A(()) ~ MyEnum::A
2642                        // Multi-element path identifiers aren't allowed, for now this mechanism is
2643                        // sufficient.
2644                        match inner_path_children.len() {
2645                            // 0 => return None, - unreachable
2646                            1 => path.into(),
2647                            _ => PatternEnum::new_green(
2648                                self.db,
2649                                path,
2650                                OptionPatternEnumInnerPatternEmpty::new_green(self.db).into(),
2651                            )
2652                            .into(),
2653                        }
2654                    }
2655                }
2656            }
2657            SyntaxKind::TerminalLParen => {
2658                let lparen = self.take::<TerminalLParen<'_>>();
2659                let patterns = PatternList::new_green(self.db,  &self.parse_separated_list::<
2660                    Pattern<'_>,
2661                    TerminalComma<'_>,
2662                    PatternListElementOrSeparatorGreen<'_>>
2663                (
2664                    Self::try_parse_pattern,
2665                    is_of_kind!(rparen, block, rbrace, module_item_kw),
2666                    "pattern",
2667                ));
2668                let rparen = self.parse_token::<TerminalRParen<'_>>();
2669                PatternTuple::new_green(self.db, lparen, patterns, rparen).into()
2670            }
2671            SyntaxKind::TerminalLBrack => {
2672                let lbrack = self.take::<TerminalLBrack<'_>>();
2673                let patterns = PatternList::new_green(self.db,  &self.parse_separated_list::<
2674                    Pattern<'_>,
2675                    TerminalComma<'_>,
2676                    PatternListElementOrSeparatorGreen<'_>>
2677                (
2678                    Self::try_parse_pattern,
2679                    is_of_kind!(rbrack, block, rbrace, module_item_kw),
2680                    "pattern",
2681                ));
2682                let rbrack = self.parse_token::<TerminalRBrack<'_>>();
2683                PatternFixedSizeArray::new_green(self.db, lbrack, patterns, rbrack).into()
2684            }
2685            _ => return Err(TryParseFailure::SkipToken),
2686        })
2687    }
2688    /// Returns a GreenId of a node with some Pattern kind (see
2689    /// [syntax::node::ast::Pattern]).
2690    fn parse_pattern(&mut self) -> PatternGreen<'a> {
2691        // If not found, return a missing underscore pattern.
2692        match self.try_parse_pattern() {
2693            Ok(pattern) => pattern,
2694            Err(_) => self.create_and_report_missing_terminal::<TerminalUnderscore<'_>>().into(),
2695        }
2696    }
2697
2698    /// Returns a GreenId of a syntax inside a struct pattern. Example:
2699    /// `MyStruct { param0, param1: _, .. }`.
2700    fn try_parse_pattern_struct_param(&mut self) -> TryParseResult<PatternStructParamGreen<'a>> {
2701        Ok(match self.peek().kind {
2702            SyntaxKind::TerminalDotDot => self.take::<TerminalDotDot<'_>>().into(),
2703            _ => {
2704                let modifier_list = self.parse_modifier_list();
2705                let name = if modifier_list.is_empty() {
2706                    self.try_parse_identifier()?
2707                } else {
2708                    self.parse_identifier()
2709                };
2710                let modifiers = ModifierList::new_green(self.db, &modifier_list);
2711                if self.peek().kind == SyntaxKind::TerminalColon {
2712                    let colon = self.take::<TerminalColon<'_>>();
2713                    let pattern = self.parse_pattern();
2714                    PatternStructParamWithExpr::new_green(self.db, modifiers, name, colon, pattern)
2715                        .into()
2716                } else {
2717                    PatternIdentifier::new_green(self.db, modifiers, name).into()
2718                }
2719            }
2720        })
2721    }
2722
2723    // ------------------------------- Statements -------------------------------
2724
2725    /// Returns a GreenId of a node with a Statement.* kind (see
2726    /// [syntax::node::ast::Statement]) or TryParseFailure if a statement can't be parsed.
2727    pub fn try_parse_statement(&mut self) -> TryParseResult<StatementGreen<'a>> {
2728        let maybe_attributes = self.try_parse_attribute_list("Statement");
2729        let (has_attrs, attributes) = match maybe_attributes {
2730            Ok(attributes) => (true, attributes),
2731            Err(_) => (false, AttributeList::new_green(self.db, &[])),
2732        };
2733        match self.peek().kind {
2734            SyntaxKind::TerminalLet => {
2735                let let_kw = self.take::<TerminalLet<'_>>();
2736                let pattern = self.parse_pattern();
2737                let type_clause = self.parse_option_type_clause();
2738                let eq = self.parse_token::<TerminalEq<'_>>();
2739                let rhs = self.parse_expr();
2740
2741                // Check if this is a let-else statement.
2742                let let_else_clause: OptionLetElseClauseGreen<'_> =
2743                    if self.peek().kind == SyntaxKind::TerminalElse {
2744                        let else_kw = self.take::<TerminalElse<'_>>();
2745                        let else_block = self.parse_block();
2746                        LetElseClause::new_green(self.db, else_kw, else_block).into()
2747                    } else {
2748                        OptionLetElseClauseEmpty::new_green(self.db).into()
2749                    };
2750
2751                let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
2752                Ok(StatementLet::new_green(
2753                    self.db,
2754                    attributes,
2755                    let_kw,
2756                    pattern,
2757                    type_clause,
2758                    eq,
2759                    rhs,
2760                    let_else_clause,
2761                    semicolon,
2762                )
2763                .into())
2764            }
2765            SyntaxKind::TerminalContinue => {
2766                let continue_kw = self.take::<TerminalContinue<'_>>();
2767                let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
2768                Ok(StatementContinue::new_green(self.db, attributes, continue_kw, semicolon).into())
2769            }
2770            SyntaxKind::TerminalReturn => {
2771                let return_kw = self.take::<TerminalReturn<'_>>();
2772                let expr = self.parse_option_expression_clause();
2773                let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
2774                Ok(StatementReturn::new_green(self.db, attributes, return_kw, expr, semicolon)
2775                    .into())
2776            }
2777            SyntaxKind::TerminalBreak => {
2778                let break_kw = self.take::<TerminalBreak<'_>>();
2779                let expr = self.parse_option_expression_clause();
2780                let semicolon = self.parse_token::<TerminalSemicolon<'_>>();
2781                Ok(StatementBreak::new_green(self.db, attributes, break_kw, expr, semicolon).into())
2782            }
2783            SyntaxKind::TerminalConst => {
2784                let const_kw = self.take::<TerminalConst<'_>>();
2785                Ok(StatementItem::new_green(
2786                    self.db,
2787                    self.expect_item_const(
2788                        attributes,
2789                        VisibilityDefault::new_green(self.db).into(),
2790                        const_kw,
2791                    )
2792                    .into(),
2793                )
2794                .into())
2795            }
2796            SyntaxKind::TerminalUse => Ok(StatementItem::new_green(
2797                self.db,
2798                self.expect_item_use(attributes, VisibilityDefault::new_green(self.db).into())
2799                    .into(),
2800            )
2801            .into()),
2802            SyntaxKind::TerminalType => Ok(StatementItem::new_green(
2803                self.db,
2804                self.expect_item_type_alias(
2805                    attributes,
2806                    VisibilityDefault::new_green(self.db).into(),
2807                )
2808                .into(),
2809            )
2810            .into()),
2811            _ => match self.try_parse_expr() {
2812                Ok(expr) => {
2813                    let optional_semicolon = if self.peek().kind == SyntaxKind::TerminalSemicolon {
2814                        self.take::<TerminalSemicolon<'_>>().into()
2815                    } else {
2816                        OptionTerminalSemicolonEmpty::new_green(self.db).into()
2817                    };
2818                    Ok(StatementExpr::new_green(self.db, attributes, expr, optional_semicolon)
2819                        .into())
2820                }
2821                Err(_) if has_attrs => Ok(self
2822                    .skip_taken_node_and_return_missing::<Statement<'_>>(
2823                        attributes,
2824                        ParserDiagnosticKind::AttributesWithoutStatement,
2825                    )),
2826                Err(err) => Err(err),
2827            },
2828        }
2829    }
2830
2831    /// Returns a GreenId of a node with kind TypeClause or OptionTypeClauseEmpty if a type clause
2832    /// can't be parsed.
2833    fn parse_option_type_clause(&mut self) -> OptionTypeClauseGreen<'a> {
2834        match self.try_parse_type_clause() {
2835            Some(green) => green.into(),
2836            None => OptionTypeClauseEmpty::new_green(self.db).into(),
2837        }
2838    }
2839
2840    /// Parses a type clause of the form: `: <type>`.
2841    fn parse_type_clause(&mut self, error_recovery: ErrorRecovery) -> TypeClauseGreen<'a> {
2842        match self.try_parse_type_clause() {
2843            Some(green) => green,
2844            None => {
2845                let res = self.create_and_report_missing::<TypeClause<'_>>(
2846                    ParserDiagnosticKind::MissingTypeClause,
2847                );
2848                self.skip_until(error_recovery.should_stop).ok();
2849                res
2850            }
2851        }
2852    }
2853    fn try_parse_type_clause(&mut self) -> Option<TypeClauseGreen<'a>> {
2854        if self.peek().kind == SyntaxKind::TerminalColon {
2855            let colon = self.take::<TerminalColon<'_>>();
2856            let ty = self.parse_type_expr();
2857            Some(TypeClause::new_green(self.db, colon, ty))
2858        } else {
2859            None
2860        }
2861    }
2862
2863    /// Returns a GreenId of a node with kind ReturnTypeClause or OptionReturnTypeClauseEmpty if a
2864    /// return type clause can't be parsed.
2865    fn parse_option_return_type_clause(&mut self) -> OptionReturnTypeClauseGreen<'a> {
2866        if self.peek().kind == SyntaxKind::TerminalArrow {
2867            let arrow = self.take::<TerminalArrow<'_>>();
2868            let return_type = self.parse_type_expr();
2869            ReturnTypeClause::new_green(self.db, arrow, return_type).into()
2870        } else {
2871            OptionReturnTypeClauseEmpty::new_green(self.db).into()
2872        }
2873    }
2874
2875    /// Returns a GreenId of a node with kind ImplicitsClause or OptionImplicitsClauseEmpty if a
2876    /// implicits-clause can't be parsed.
2877    fn parse_option_implicits_clause(&mut self) -> OptionImplicitsClauseGreen<'a> {
2878        if self.peek().kind == SyntaxKind::TerminalImplicits {
2879            let implicits_kw = self.take::<TerminalImplicits<'_>>();
2880            let lparen = self.parse_token::<TerminalLParen<'_>>();
2881            let implicits = ImplicitsList::new_green(
2882                self.db,
2883                &self.parse_separated_list::<ExprPath<'_>, TerminalComma<'_>, ImplicitsListElementOrSeparatorGreen<'_>>(
2884                    Self::try_parse_path,
2885                    // Don't stop at keywords as try_parse_path handles keywords inside it. Otherwise the diagnostic is less accurate.
2886                    is_of_kind!(rparen, lbrace, rbrace),
2887                    "implicit type",
2888                ),
2889            );
2890            let rparen = self.parse_token::<TerminalRParen<'_>>();
2891            ImplicitsClause::new_green(self.db, implicits_kw, lparen, implicits, rparen).into()
2892        } else {
2893            OptionImplicitsClauseEmpty::new_green(self.db).into()
2894        }
2895    }
2896
2897    /// Returns a GreenId of a node with kind ParamList.
2898    fn parse_param_list(&mut self) -> ParamListGreen<'a> {
2899        ParamList::new_green(
2900            self.db,
2901            &self.parse_separated_list::<Param<'_>, TerminalComma<'_>, ParamListElementOrSeparatorGreen<'_>>(
2902                Self::try_parse_param,
2903                is_of_kind!(rparen, block, lbrace, rbrace, module_item_kw),
2904                "parameter",
2905            ),
2906        )
2907    }
2908
2909    /// Returns a GreenId of a node with kind ClosureParamList.
2910    fn parse_closure_param_list(&mut self) -> ParamListGreen<'a> {
2911        ParamList::new_green(
2912            self.db,
2913            &self.parse_separated_list::<Param<'_>, TerminalComma<'_>, ParamListElementOrSeparatorGreen<'_>>(
2914                Self::try_parse_closure_param,
2915                is_of_kind!(or, block, lbrace, rbrace, module_item_kw),
2916                "parameter",
2917            ),
2918        )
2919    }
2920
2921    /// Returns a GreenId of a node with kind Modifier or TryParseFailure if a modifier can't be
2922    /// parsed.
2923    fn try_parse_modifier(&mut self) -> Option<ModifierGreen<'a>> {
2924        match self.peek().kind {
2925            SyntaxKind::TerminalRef => Some(self.take::<TerminalRef<'_>>().into()),
2926            SyntaxKind::TerminalMut => Some(self.take::<TerminalMut<'_>>().into()),
2927            _ => None,
2928        }
2929    }
2930
2931    /// Returns a vector of GreenIds with kind Modifier.
2932    fn parse_modifier_list(&mut self) -> Vec<ModifierGreen<'a>> {
2933        let mut modifier_list = vec![];
2934
2935        while let Some(modifier) = self.try_parse_modifier() {
2936            modifier_list.push(modifier);
2937        }
2938        modifier_list
2939    }
2940
2941    /// Returns a GreenId of a node with kind Param or TryParseFailure if a parameter can't be
2942    /// parsed.
2943    fn try_parse_param(&mut self) -> TryParseResult<ParamGreen<'a>> {
2944        let modifier_list = self.parse_modifier_list();
2945        let name = if modifier_list.is_empty() {
2946            self.try_parse_identifier()?
2947        } else {
2948            // If we had modifiers then the identifier is not optional and can't be '_'.
2949            self.parse_identifier()
2950        };
2951
2952        let type_clause = self
2953            .parse_type_clause(ErrorRecovery {
2954                should_stop: is_of_kind!(comma, rparen, module_item_kw),
2955            })
2956            .into();
2957        Ok(Param::new_green(
2958            self.db,
2959            ModifierList::new_green(self.db, &modifier_list),
2960            name,
2961            type_clause,
2962        ))
2963    }
2964
2965    /// Returns a GreenId of a node with kind Param or TryParseFailure if a parameter can't
2966    /// be parsed.
2967    fn try_parse_closure_param(&mut self) -> TryParseResult<ParamGreen<'a>> {
2968        let modifier_list = self.parse_modifier_list();
2969        let name = if modifier_list.is_empty() {
2970            self.try_parse_identifier()?
2971        } else {
2972            // If we had modifiers then the identifier is not optional and can't be '_'.
2973            self.parse_identifier()
2974        };
2975
2976        let type_clause = self.parse_option_type_clause();
2977        Ok(Param::new_green(
2978            self.db,
2979            ModifierList::new_green(self.db, &modifier_list),
2980            name,
2981            type_clause,
2982        ))
2983    }
2984
2985    /// Returns a GreenId of a node with kind MemberList.
2986    fn parse_member_list(&mut self) -> MemberListGreen<'a> {
2987        MemberList::new_green(
2988            self.db,
2989            &self.parse_separated_list::<
2990                Member<'_>,
2991                TerminalComma<'_>,
2992                MemberListElementOrSeparatorGreen<'_>,
2993            >(
2994                Self::try_parse_member,
2995                is_of_kind!(rparen, block, lbrace, rbrace, module_item_kw),
2996                "member or variant",
2997            ),
2998        )
2999    }
3000
3001    /// Returns a GreenId of a node with kind Member or TryParseFailure if a struct member can't be
3002    /// parsed.
3003    fn try_parse_member(&mut self) -> TryParseResult<MemberGreen<'a>> {
3004        let attributes = self.try_parse_attribute_list("Struct member");
3005        let visibility = self.parse_visibility();
3006        let (name, attributes) = match attributes {
3007            Ok(attributes) => (self.parse_identifier(), attributes),
3008            Err(_) => (self.try_parse_identifier()?, AttributeList::new_green(self.db, &[])),
3009        };
3010        let type_clause = self.parse_type_clause(ErrorRecovery {
3011            should_stop: is_of_kind!(comma, rbrace, module_item_kw),
3012        });
3013        Ok(Member::new_green(self.db, attributes, visibility, name, type_clause))
3014    }
3015
3016    /// Returns a GreenId of a node with kind VariantList.
3017    fn parse_variant_list(&mut self) -> VariantListGreen<'a> {
3018        VariantList::new_green(
3019            self.db,
3020            &self
3021                .parse_separated_list::<Variant<'_>, TerminalComma<'_>, VariantListElementOrSeparatorGreen<'_>>(
3022                    Self::try_parse_variant,
3023                    is_of_kind!(rparen, block, lbrace, rbrace, module_item_kw),
3024                    "variant",
3025                ),
3026        )
3027    }
3028
3029    /// Returns a GreenId of a node with kind Variant or TryParseFailure if an enum variant can't be
3030    /// parsed.
3031    fn try_parse_variant(&mut self) -> TryParseResult<VariantGreen<'a>> {
3032        let attributes = self.try_parse_attribute_list("Enum variant");
3033        let (name, attributes) = match attributes {
3034            Ok(attributes) => (self.parse_identifier(), attributes),
3035            Err(_) => (self.try_parse_identifier()?, AttributeList::new_green(self.db, &[])),
3036        };
3037
3038        let type_clause = self.parse_option_type_clause();
3039        Ok(Variant::new_green(self.db, attributes, name, type_clause))
3040    }
3041
3042    /// Expected pattern: `<PathSegment>(::<PathSegment>)*`
3043    /// Returns a GreenId of a node with kind ExprPath.
3044    fn parse_path(&mut self) -> ExprPathGreen<'a> {
3045        let dollar = match self.peek().kind {
3046            SyntaxKind::TerminalDollar => self.take::<TerminalDollar<'_>>().into(),
3047            _ => OptionTerminalDollarEmpty::new_green(self.db).into(),
3048        };
3049
3050        let mut children: Vec<ExprPathInnerElementOrSeparatorGreen<'_>> = vec![];
3051        loop {
3052            let (segment, optional_separator) = self.parse_path_segment();
3053            children.push(segment.into());
3054
3055            if let Some(separator) = optional_separator {
3056                children.push(separator.into());
3057                continue;
3058            }
3059            break;
3060        }
3061
3062        ExprPath::new_green(self.db, dollar, ExprPathInner::new_green(self.db, &children))
3063    }
3064    /// Returns a GreenId of a node with kind ExprPath or TryParseFailure if a path can't be parsed.
3065    fn try_parse_path(&mut self) -> TryParseResult<ExprPathGreen<'a>> {
3066        if self.is_peek_identifier_like() {
3067            Ok(self.parse_path())
3068        } else {
3069            Err(TryParseFailure::SkipToken)
3070        }
3071    }
3072
3073    /// Expected pattern: `(<PathSegment<'_>>::)*<PathSegment<'_>>(::){0,1}<GenericArgs>`.
3074    ///
3075    /// Returns a GreenId of a node with kind ExprPath.
3076    fn parse_type_path(&mut self) -> ExprPathGreen<'a> {
3077        let dollar = match self.peek().kind {
3078            SyntaxKind::TerminalDollar => self.take::<TerminalDollar<'_>>().into(),
3079            _ => OptionTerminalDollarEmpty::new_green(self.db).into(),
3080        };
3081
3082        let mut children: Vec<ExprPathInnerElementOrSeparatorGreen<'_>> = vec![];
3083        loop {
3084            let (segment, optional_separator) = self.parse_type_path_segment();
3085            children.push(segment.into());
3086
3087            if let Some(separator) = optional_separator {
3088                children.push(separator.into());
3089                continue;
3090            }
3091            break;
3092        }
3093
3094        ExprPath::new_green(self.db, dollar, ExprPathInner::new_green(self.db, &children))
3095    }
3096
3097    /// Returns a PathSegment and an optional separator.
3098    fn parse_path_segment(
3099        &mut self,
3100    ) -> (PathSegmentGreen<'a>, Option<TerminalColonColonGreen<'a>>) {
3101        let identifier = match self.try_parse_identifier() {
3102            Ok(identifier) => identifier,
3103            Err(_) => {
3104                return (
3105                    self.create_and_report_missing::<PathSegment<'_>>(
3106                        ParserDiagnosticKind::MissingPathSegment,
3107                    ),
3108                    None,
3109                );
3110            }
3111        };
3112        match self.try_parse_token::<TerminalColonColon<'_>>() {
3113            Ok(separator) if self.peek().kind == SyntaxKind::TerminalLT => (
3114                PathSegmentWithGenericArgs::new_green(
3115                    self.db,
3116                    identifier,
3117                    separator.into(),
3118                    self.expect_generic_args(),
3119                )
3120                .into(),
3121                self.try_parse_token::<TerminalColonColon<'_>>().ok(),
3122            ),
3123            optional_separator => {
3124                (PathSegmentSimple::new_green(self.db, identifier).into(), optional_separator.ok())
3125            }
3126        }
3127    }
3128
3129    /// Returns a Typed PathSegment or a normal PathSegment.
3130    /// Additionally returns an optional separators.
3131    fn parse_type_path_segment(
3132        &mut self,
3133    ) -> (PathSegmentGreen<'a>, Option<TerminalColonColonGreen<'a>>) {
3134        let identifier = match self.try_parse_identifier() {
3135            Ok(identifier) => identifier,
3136            Err(_) => {
3137                return (
3138                    self.create_and_report_missing::<PathSegment<'_>>(
3139                        ParserDiagnosticKind::MissingPathSegment,
3140                    ),
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}