]> git.lizzy.rs Git - rust.git/blob - crates/parser/src/grammar/items.rs
Merge #6496
[rust.git] / crates / parser / src / grammar / items.rs
1 //! FIXME: write short doc here
2
3 mod consts;
4 mod adt;
5 mod traits;
6 mod use_item;
7
8 pub(crate) use self::{
9     adt::{record_field_list, variant_list},
10     expressions::{match_arm_list, record_expr_field_list},
11     traits::assoc_item_list,
12     use_item::use_tree_list,
13 };
14 use super::*;
15
16 // test mod_contents
17 // fn foo() {}
18 // macro_rules! foo {}
19 // foo::bar!();
20 // super::baz! {}
21 // struct S;
22 pub(super) fn mod_contents(p: &mut Parser, stop_on_r_curly: bool) {
23     attributes::inner_attrs(p);
24     while !(stop_on_r_curly && p.at(T!['}']) || p.at(EOF)) {
25         item_or_macro(p, stop_on_r_curly)
26     }
27 }
28
29 pub(super) const ITEM_RECOVERY_SET: TokenSet = TokenSet::new(&[
30     FN_KW,
31     STRUCT_KW,
32     ENUM_KW,
33     IMPL_KW,
34     TRAIT_KW,
35     CONST_KW,
36     STATIC_KW,
37     LET_KW,
38     MOD_KW,
39     PUB_KW,
40     CRATE_KW,
41     USE_KW,
42     MACRO_KW,
43     T![;],
44 ]);
45
46 pub(super) fn item_or_macro(p: &mut Parser, stop_on_r_curly: bool) {
47     let m = p.start();
48     attributes::outer_attrs(p);
49     let m = match maybe_item(p, m) {
50         Ok(()) => {
51             if p.at(T![;]) {
52                 p.err_and_bump(
53                     "expected item, found `;`\n\
54                      consider removing this semicolon",
55                 );
56             }
57             return;
58         }
59         Err(m) => m,
60     };
61     if paths::is_use_path_start(p) {
62         match macro_call(p) {
63             BlockLike::Block => (),
64             BlockLike::NotBlock => {
65                 p.expect(T![;]);
66             }
67         }
68         m.complete(p, MACRO_CALL);
69     } else {
70         m.abandon(p);
71         if p.at(T!['{']) {
72             error_block(p, "expected an item");
73         } else if p.at(T!['}']) && !stop_on_r_curly {
74             let e = p.start();
75             p.error("unmatched `}`");
76             p.bump(T!['}']);
77             e.complete(p, ERROR);
78         } else if !p.at(EOF) && !p.at(T!['}']) {
79             p.err_and_bump("expected an item");
80         } else {
81             p.error("expected an item");
82         }
83     }
84 }
85
86 pub(super) fn maybe_item(p: &mut Parser, m: Marker) -> Result<(), Marker> {
87     // test_err pub_expr
88     // fn foo() { pub 92; }
89     let has_visibility = opt_visibility(p);
90
91     let m = match items_without_modifiers(p, m) {
92         Ok(()) => return Ok(()),
93         Err(m) => m,
94     };
95
96     let mut has_mods = false;
97
98     // modifiers
99     has_mods |= p.eat(T![const]);
100
101     // test_err async_without_semicolon
102     // fn foo() { let _ = async {} }
103     if p.at(T![async]) && p.nth(1) != T!['{'] && p.nth(1) != T![move] && p.nth(1) != T![|] {
104         p.eat(T![async]);
105         has_mods = true;
106     }
107
108     // test_err unsafe_block_in_mod
109     // fn foo(){} unsafe { } fn bar(){}
110     if p.at(T![unsafe]) && p.nth(1) != T!['{'] {
111         p.eat(T![unsafe]);
112         has_mods = true;
113     }
114
115     if p.at(T![extern]) && p.nth(1) != T!['{'] && (p.nth(1) != STRING || p.nth(2) != T!['{']) {
116         has_mods = true;
117         abi(p);
118     }
119     if p.at(IDENT) && p.at_contextual_kw("auto") && p.nth(1) == T![trait] {
120         p.bump_remap(T![auto]);
121         has_mods = true;
122     }
123
124     // test default_item
125     // default impl T for Foo {}
126     if p.at(IDENT) && p.at_contextual_kw("default") {
127         match p.nth(1) {
128             T![fn] | T![type] | T![const] | T![impl] => {
129                 p.bump_remap(T![default]);
130                 has_mods = true;
131             }
132             T![unsafe] => {
133                 // test default_unsafe_item
134                 // default unsafe impl T for Foo {
135                 //     default unsafe fn foo() {}
136                 // }
137                 if matches!(p.nth(2), T![impl] | T![fn]) {
138                     p.bump_remap(T![default]);
139                     p.bump(T![unsafe]);
140                     has_mods = true;
141                 }
142             }
143             _ => (),
144         }
145     }
146
147     // test existential_type
148     // existential type Foo: Fn() -> usize;
149     if p.at(IDENT) && p.at_contextual_kw("existential") && p.nth(1) == T![type] {
150         p.bump_remap(T![existential]);
151         has_mods = true;
152     }
153
154     // items
155     match p.current() {
156         // test fn
157         // fn foo() {}
158         T![fn] => {
159             fn_(p);
160             m.complete(p, FN);
161         }
162
163         // test trait
164         // trait T {}
165         T![trait] => {
166             traits::trait_(p);
167             m.complete(p, TRAIT);
168         }
169
170         T![const] => {
171             consts::konst(p, m);
172         }
173
174         // test impl
175         // impl T for S {}
176         T![impl] => {
177             traits::impl_(p);
178             m.complete(p, IMPL);
179         }
180
181         T![type] => {
182             type_alias(p, m);
183         }
184
185         // unsafe extern "C" {}
186         T![extern] => {
187             abi(p);
188             extern_item_list(p);
189             m.complete(p, EXTERN_BLOCK);
190         }
191
192         _ => {
193             if !has_visibility && !has_mods {
194                 return Err(m);
195             } else {
196                 if has_mods {
197                     p.error("expected existential, fn, trait or impl");
198                 } else {
199                     p.error("expected an item");
200                 }
201                 m.complete(p, ERROR);
202             }
203         }
204     }
205     Ok(())
206 }
207
208 fn items_without_modifiers(p: &mut Parser, m: Marker) -> Result<(), Marker> {
209     let la = p.nth(1);
210     match p.current() {
211         // test extern_crate
212         // extern crate foo;
213         T![extern] if la == T![crate] => extern_crate(p, m),
214         T![type] => {
215             type_alias(p, m);
216         }
217         T![mod] => mod_item(p, m),
218         T![struct] => {
219             // test struct_items
220             // struct Foo;
221             // struct Foo {}
222             // struct Foo();
223             // struct Foo(String, usize);
224             // struct Foo {
225             //     a: i32,
226             //     b: f32,
227             // }
228             adt::strukt(p, m);
229         }
230         // test pub_macro_def
231         // pub macro m($:ident) {}
232         T![macro] => {
233             macro_def(p, m);
234         }
235         IDENT if p.at_contextual_kw("union") && p.nth(1) == IDENT => {
236             // test union_items
237             // union Foo {}
238             // union Foo {
239             //     a: i32,
240             //     b: f32,
241             // }
242             adt::union(p, m);
243         }
244         T![enum] => adt::enum_(p, m),
245         T![use] => use_item::use_(p, m),
246         T![const] if (la == IDENT || la == T![_] || la == T![mut]) => consts::konst(p, m),
247         T![static] => consts::static_(p, m),
248         // test extern_block
249         // extern {}
250         T![extern] if la == T!['{'] || (la == STRING && p.nth(2) == T!['{']) => {
251             abi(p);
252             extern_item_list(p);
253             m.complete(p, EXTERN_BLOCK);
254         }
255         _ => return Err(m),
256     };
257     Ok(())
258 }
259
260 fn extern_crate(p: &mut Parser, m: Marker) {
261     assert!(p.at(T![extern]));
262     p.bump(T![extern]);
263     assert!(p.at(T![crate]));
264     p.bump(T![crate]);
265
266     if p.at(T![self]) {
267         p.bump(T![self]);
268     } else {
269         name_ref(p);
270     }
271
272     opt_rename(p);
273     p.expect(T![;]);
274     m.complete(p, EXTERN_CRATE);
275 }
276
277 pub(crate) fn extern_item_list(p: &mut Parser) {
278     assert!(p.at(T!['{']));
279     let m = p.start();
280     p.bump(T!['{']);
281     mod_contents(p, true);
282     p.expect(T!['}']);
283     m.complete(p, EXTERN_ITEM_LIST);
284 }
285
286 fn fn_(p: &mut Parser) {
287     assert!(p.at(T![fn]));
288     p.bump(T![fn]);
289
290     name_r(p, ITEM_RECOVERY_SET);
291     // test function_type_params
292     // fn foo<T: Clone + Copy>(){}
293     type_params::opt_generic_param_list(p);
294
295     if p.at(T!['(']) {
296         params::param_list_fn_def(p);
297     } else {
298         p.error("expected function arguments");
299     }
300     // test function_ret_type
301     // fn foo() {}
302     // fn bar() -> () {}
303     opt_ret_type(p);
304
305     // test function_where_clause
306     // fn foo<T>() where T: Copy {}
307     type_params::opt_where_clause(p);
308
309     // test fn_decl
310     // trait T { fn foo(); }
311     if p.at(T![;]) {
312         p.bump(T![;]);
313     } else {
314         expressions::block_expr(p)
315     }
316 }
317
318 // test type_item
319 // type Foo = Bar;
320 fn type_alias(p: &mut Parser, m: Marker) {
321     assert!(p.at(T![type]));
322     p.bump(T![type]);
323
324     name(p);
325
326     // test type_item_type_params
327     // type Result<T> = ();
328     type_params::opt_generic_param_list(p);
329
330     if p.at(T![:]) {
331         type_params::bounds(p);
332     }
333
334     // test type_item_where_clause
335     // type Foo where Foo: Copy = ();
336     type_params::opt_where_clause(p);
337     if p.eat(T![=]) {
338         types::type_(p);
339     }
340     p.expect(T![;]);
341     m.complete(p, TYPE_ALIAS);
342 }
343
344 pub(crate) fn mod_item(p: &mut Parser, m: Marker) {
345     assert!(p.at(T![mod]));
346     p.bump(T![mod]);
347
348     name(p);
349     if p.at(T!['{']) {
350         item_list(p);
351     } else if !p.eat(T![;]) {
352         p.error("expected `;` or `{`");
353     }
354     m.complete(p, MODULE);
355 }
356
357 pub(crate) fn item_list(p: &mut Parser) {
358     assert!(p.at(T!['{']));
359     let m = p.start();
360     p.bump(T!['{']);
361     mod_contents(p, true);
362     p.expect(T!['}']);
363     m.complete(p, ITEM_LIST);
364 }
365
366 // test macro_def
367 // macro m { ($i:ident) => {} }
368 // macro m($i:ident) {}
369 fn macro_def(p: &mut Parser, m: Marker) {
370     p.expect(T![macro]);
371     name_r(p, ITEM_RECOVERY_SET);
372     if p.at(T!['{']) {
373         token_tree(p);
374     } else if !p.at(T!['(']) {
375         p.error("unmatched `(`");
376     } else {
377         let m = p.start();
378         token_tree(p);
379         match p.current() {
380             T!['{'] | T!['['] | T!['('] => token_tree(p),
381             _ => p.error("expected `{`, `[`, `(`"),
382         }
383         m.complete(p, TOKEN_TREE);
384     }
385
386     m.complete(p, MACRO_DEF);
387 }
388
389 fn macro_call(p: &mut Parser) -> BlockLike {
390     assert!(paths::is_use_path_start(p));
391     paths::use_path(p);
392     macro_call_after_excl(p)
393 }
394
395 pub(super) fn macro_call_after_excl(p: &mut Parser) -> BlockLike {
396     p.expect(T![!]);
397     if p.at(IDENT) {
398         name(p);
399     }
400     // Special-case `macro_rules! try`.
401     // This is a hack until we do proper edition support
402
403     // test try_macro_rules
404     // macro_rules! try { () => {} }
405     if p.at(T![try]) {
406         let m = p.start();
407         p.bump_remap(IDENT);
408         m.complete(p, NAME);
409     }
410
411     match p.current() {
412         T!['{'] => {
413             token_tree(p);
414             BlockLike::Block
415         }
416         T!['('] | T!['['] => {
417             token_tree(p);
418             BlockLike::NotBlock
419         }
420         _ => {
421             p.error("expected `{`, `[`, `(`");
422             BlockLike::NotBlock
423         }
424     }
425 }
426
427 pub(crate) fn token_tree(p: &mut Parser) {
428     let closing_paren_kind = match p.current() {
429         T!['{'] => T!['}'],
430         T!['('] => T![')'],
431         T!['['] => T![']'],
432         _ => unreachable!(),
433     };
434     let m = p.start();
435     p.bump_any();
436     while !p.at(EOF) && !p.at(closing_paren_kind) {
437         match p.current() {
438             T!['{'] | T!['('] | T!['['] => token_tree(p),
439             T!['}'] => {
440                 p.error("unmatched `}`");
441                 m.complete(p, TOKEN_TREE);
442                 return;
443             }
444             T![')'] | T![']'] => p.err_and_bump("unmatched brace"),
445             _ => p.bump_any(),
446         }
447     }
448     p.expect(closing_paren_kind);
449     m.complete(p, TOKEN_TREE);
450 }