]> git.lizzy.rs Git - rust.git/blob - crates/parser/src/grammar.rs
Merge #11165
[rust.git] / crates / parser / src / grammar.rs
1 //! This is the actual "grammar" of the Rust language.
2 //!
3 //! Each function in this module and its children corresponds
4 //! to a production of the formal grammar. Submodules roughly
5 //! correspond to different *areas* of the grammar. By convention,
6 //! each submodule starts with `use super::*` import and exports
7 //! "public" productions via `pub(super)`.
8 //!
9 //! See docs for [`Parser`](super::parser::Parser) to learn about API,
10 //! available to the grammar, and see docs for [`Event`](super::event::Event)
11 //! to learn how this actually manages to produce parse trees.
12 //!
13 //! Code in this module also contains inline tests, which start with
14 //! `// test name-of-the-test` comment and look like this:
15 //!
16 //! ```
17 //! // test function_with_zero_parameters
18 //! // fn foo() {}
19 //! ```
20 //!
21 //! After adding a new inline-test, run `cargo test -p xtask` to
22 //! extract it as a standalone text-fixture into
23 //! `crates/syntax/test_data/parser/`, and run `cargo test` once to
24 //! create the "gold" value.
25 //!
26 //! Coding convention: rules like `where_clause` always produce either a
27 //! node or an error, rules like `opt_where_clause` may produce nothing.
28 //! Non-opt rules typically start with `assert!(p.at(FIRST_TOKEN))`, the
29 //! caller is responsible for branching on the first token.
30
31 mod attributes;
32 mod expressions;
33 mod items;
34 mod params;
35 mod paths;
36 mod patterns;
37 mod generic_args;
38 mod generic_params;
39 mod types;
40
41 use crate::{
42     parser::{CompletedMarker, Marker, Parser},
43     SyntaxKind::{self, *},
44     TokenSet, T,
45 };
46
47 pub(crate) mod entry {
48     use super::*;
49
50     pub(crate) mod prefix {
51         use super::*;
52
53         pub(crate) fn vis(p: &mut Parser) {
54             let _ = opt_visibility(p, false);
55         }
56
57         pub(crate) fn block(p: &mut Parser) {
58             expressions::block_expr(p);
59         }
60
61         pub(crate) fn stmt(p: &mut Parser) {
62             expressions::stmt(p, expressions::Semicolon::Forbidden);
63         }
64
65         pub(crate) fn pat(p: &mut Parser) {
66             patterns::pattern_single(p);
67         }
68
69         pub(crate) fn ty(p: &mut Parser) {
70             types::type_(p);
71         }
72         pub(crate) fn expr(p: &mut Parser) {
73             let _ = expressions::expr(p);
74         }
75         pub(crate) fn path(p: &mut Parser) {
76             let _ = paths::type_path(p);
77         }
78         pub(crate) fn item(p: &mut Parser) {
79             items::item_or_macro(p, true);
80         }
81         // Parse a meta item , which excluded [], e.g : #[ MetaItem ]
82         pub(crate) fn meta_item(p: &mut Parser) {
83             attributes::meta(p);
84         }
85     }
86
87     pub(crate) mod top {
88         use super::*;
89
90         pub(crate) fn source_file(p: &mut Parser) {
91             let m = p.start();
92             p.eat(SHEBANG);
93             items::mod_contents(p, false);
94             m.complete(p, SOURCE_FILE);
95         }
96
97         pub(crate) fn macro_stmts(p: &mut Parser) {
98             let m = p.start();
99
100             while !p.at(EOF) {
101                 expressions::stmt(p, expressions::Semicolon::Optional);
102             }
103
104             m.complete(p, MACRO_STMTS);
105         }
106
107         pub(crate) fn macro_items(p: &mut Parser) {
108             let m = p.start();
109             items::mod_contents(p, false);
110             m.complete(p, MACRO_ITEMS);
111         }
112
113         pub(crate) fn pattern(p: &mut Parser) {
114             let m = p.start();
115             patterns::pattern_single(p);
116             if p.at(EOF) {
117                 m.abandon(p);
118                 return;
119             }
120             while !p.at(EOF) {
121                 p.bump_any();
122             }
123             m.complete(p, ERROR);
124         }
125
126         pub(crate) fn type_(p: &mut Parser) {
127             let m = p.start();
128             types::type_(p);
129             if p.at(EOF) {
130                 m.abandon(p);
131                 return;
132             }
133             while !p.at(EOF) {
134                 p.bump_any();
135             }
136             m.complete(p, ERROR);
137         }
138     }
139 }
140
141 pub(crate) fn reparser(
142     node: SyntaxKind,
143     first_child: Option<SyntaxKind>,
144     parent: Option<SyntaxKind>,
145 ) -> Option<fn(&mut Parser)> {
146     let res = match node {
147         BLOCK_EXPR => expressions::block_expr,
148         RECORD_FIELD_LIST => items::record_field_list,
149         RECORD_EXPR_FIELD_LIST => items::record_expr_field_list,
150         VARIANT_LIST => items::variant_list,
151         MATCH_ARM_LIST => items::match_arm_list,
152         USE_TREE_LIST => items::use_tree_list,
153         EXTERN_ITEM_LIST => items::extern_item_list,
154         TOKEN_TREE if first_child? == T!['{'] => items::token_tree,
155         ASSOC_ITEM_LIST => match parent? {
156             IMPL | TRAIT => items::assoc_item_list,
157             _ => return None,
158         },
159         ITEM_LIST => items::item_list,
160         _ => return None,
161     };
162     Some(res)
163 }
164
165 #[derive(Clone, Copy, PartialEq, Eq)]
166 enum BlockLike {
167     Block,
168     NotBlock,
169 }
170
171 impl BlockLike {
172     fn is_block(self) -> bool {
173         self == BlockLike::Block
174     }
175 }
176
177 fn opt_visibility(p: &mut Parser, in_tuple_field: bool) -> bool {
178     match p.current() {
179         T![pub] => {
180             let m = p.start();
181             p.bump(T![pub]);
182             if p.at(T!['(']) {
183                 match p.nth(1) {
184                     // test crate_visibility
185                     // pub(crate) struct S;
186                     // pub(self) struct S;
187                     // pub(super) struct S;
188
189                     // test pub_parens_typepath
190                     // struct B(pub (super::A));
191                     // struct B(pub (crate::A,));
192                     T![crate] | T![self] | T![super] | T![ident] if p.nth(2) != T![:] => {
193                         // If we are in a tuple struct, then the parens following `pub`
194                         // might be an tuple field, not part of the visibility. So in that
195                         // case we don't want to consume an identifier.
196
197                         // test pub_tuple_field
198                         // struct MyStruct(pub (u32, u32));
199                         if !(in_tuple_field && matches!(p.nth(1), T![ident])) {
200                             p.bump(T!['(']);
201                             paths::use_path(p);
202                             p.expect(T![')']);
203                         }
204                     }
205                     // test crate_visibility_in
206                     // pub(in super::A) struct S;
207                     // pub(in crate) struct S;
208                     T![in] => {
209                         p.bump(T!['(']);
210                         p.bump(T![in]);
211                         paths::use_path(p);
212                         p.expect(T![')']);
213                     }
214                     _ => (),
215                 }
216             }
217             m.complete(p, VISIBILITY);
218             true
219         }
220         // test crate_keyword_vis
221         // crate fn main() { }
222         // struct S { crate field: u32 }
223         // struct T(crate u32);
224         T![crate] => {
225             if p.nth_at(1, T![::]) {
226                 // test crate_keyword_path
227                 // fn foo() { crate::foo(); }
228                 return false;
229             }
230             let m = p.start();
231             p.bump(T![crate]);
232             m.complete(p, VISIBILITY);
233             true
234         }
235         _ => false,
236     }
237 }
238
239 fn opt_rename(p: &mut Parser) {
240     if p.at(T![as]) {
241         let m = p.start();
242         p.bump(T![as]);
243         if !p.eat(T![_]) {
244             name(p);
245         }
246         m.complete(p, RENAME);
247     }
248 }
249
250 fn abi(p: &mut Parser) {
251     assert!(p.at(T![extern]));
252     let abi = p.start();
253     p.bump(T![extern]);
254     p.eat(STRING);
255     abi.complete(p, ABI);
256 }
257
258 fn opt_ret_type(p: &mut Parser) -> bool {
259     if p.at(T![->]) {
260         let m = p.start();
261         p.bump(T![->]);
262         types::type_no_bounds(p);
263         m.complete(p, RET_TYPE);
264         true
265     } else {
266         false
267     }
268 }
269
270 fn name_r(p: &mut Parser, recovery: TokenSet) {
271     if p.at(IDENT) {
272         let m = p.start();
273         p.bump(IDENT);
274         m.complete(p, NAME);
275     } else {
276         p.err_recover("expected a name", recovery);
277     }
278 }
279
280 fn name(p: &mut Parser) {
281     name_r(p, TokenSet::EMPTY);
282 }
283
284 fn name_ref(p: &mut Parser) {
285     if p.at(IDENT) {
286         let m = p.start();
287         p.bump(IDENT);
288         m.complete(p, NAME_REF);
289     } else {
290         p.err_and_bump("expected identifier");
291     }
292 }
293
294 fn name_ref_or_index(p: &mut Parser) {
295     assert!(p.at(IDENT) || p.at(INT_NUMBER));
296     let m = p.start();
297     p.bump_any();
298     m.complete(p, NAME_REF);
299 }
300
301 fn lifetime(p: &mut Parser) {
302     assert!(p.at(LIFETIME_IDENT));
303     let m = p.start();
304     p.bump(LIFETIME_IDENT);
305     m.complete(p, LIFETIME);
306 }
307
308 fn error_block(p: &mut Parser, message: &str) {
309     assert!(p.at(T!['{']));
310     let m = p.start();
311     p.error(message);
312     p.bump(T!['{']);
313     expressions::expr_block_contents(p);
314     p.eat(T!['}']);
315     m.complete(p, ERROR);
316 }