]> git.lizzy.rs Git - rust.git/blob - crates/parser/src/grammar/items.rs
Wrap remaining self/super/crate in Name{Ref}
[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     T![fn],
31     T![struct],
32     T![enum],
33     T![impl],
34     T![trait],
35     T![const],
36     T![static],
37     T![let],
38     T![mod],
39     T![pub],
40     T![crate],
41     T![use],
42     T![macro],
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     if p.at(T![const]) && p.nth(1) != T!['{'] {
100         p.eat(T![const]);
101         has_mods = true;
102     }
103
104     // test_err async_without_semicolon
105     // fn foo() { let _ = async {} }
106     if p.at(T![async]) && p.nth(1) != T!['{'] && p.nth(1) != T![move] && p.nth(1) != T![|] {
107         p.eat(T![async]);
108         has_mods = true;
109     }
110
111     // test_err unsafe_block_in_mod
112     // fn foo(){} unsafe { } fn bar(){}
113     if p.at(T![unsafe]) && p.nth(1) != T!['{'] {
114         p.eat(T![unsafe]);
115         has_mods = true;
116     }
117
118     if p.at(T![extern]) && p.nth(1) != T!['{'] && (p.nth(1) != STRING || p.nth(2) != T!['{']) {
119         has_mods = true;
120         abi(p);
121     }
122     if p.at(IDENT) && p.at_contextual_kw("auto") && p.nth(1) == T![trait] {
123         p.bump_remap(T![auto]);
124         has_mods = true;
125     }
126
127     // test default_item
128     // default impl T for Foo {}
129     if p.at(IDENT) && p.at_contextual_kw("default") {
130         match p.nth(1) {
131             T![fn] | T![type] | T![const] | T![impl] => {
132                 p.bump_remap(T![default]);
133                 has_mods = true;
134             }
135             T![unsafe] => {
136                 // test default_unsafe_item
137                 // default unsafe impl T for Foo {
138                 //     default unsafe fn foo() {}
139                 // }
140                 if matches!(p.nth(2), T![impl] | T![fn]) {
141                     p.bump_remap(T![default]);
142                     p.bump(T![unsafe]);
143                     has_mods = true;
144                 }
145             }
146             _ => (),
147         }
148     }
149
150     // test existential_type
151     // existential type Foo: Fn() -> usize;
152     if p.at(IDENT) && p.at_contextual_kw("existential") && p.nth(1) == T![type] {
153         p.bump_remap(T![existential]);
154         has_mods = true;
155     }
156
157     // items
158     match p.current() {
159         // test fn
160         // fn foo() {}
161         T![fn] => {
162             fn_(p);
163             m.complete(p, FN);
164         }
165
166         // test trait
167         // trait T {}
168         T![trait] => {
169             traits::trait_(p);
170             m.complete(p, TRAIT);
171         }
172
173         T![const] if p.nth(1) != T!['{'] => {
174             consts::konst(p, m);
175         }
176
177         // test impl
178         // impl T for S {}
179         T![impl] => {
180             traits::impl_(p);
181             m.complete(p, IMPL);
182         }
183
184         T![type] => {
185             type_alias(p, m);
186         }
187
188         // unsafe extern "C" {}
189         T![extern] => {
190             abi(p);
191             extern_item_list(p);
192             m.complete(p, EXTERN_BLOCK);
193         }
194
195         _ => {
196             if !has_visibility && !has_mods {
197                 return Err(m);
198             } else {
199                 if has_mods {
200                     p.error("expected existential, fn, trait or impl");
201                 } else {
202                     p.error("expected an item");
203                 }
204                 m.complete(p, ERROR);
205             }
206         }
207     }
208     Ok(())
209 }
210
211 fn items_without_modifiers(p: &mut Parser, m: Marker) -> Result<(), Marker> {
212     let la = p.nth(1);
213     match p.current() {
214         // test extern_crate
215         // extern crate foo;
216         T![extern] if la == T![crate] => extern_crate(p, m),
217         T![type] => {
218             type_alias(p, m);
219         }
220         T![mod] => mod_item(p, m),
221         T![struct] => {
222             // test struct_items
223             // struct Foo;
224             // struct Foo {}
225             // struct Foo();
226             // struct Foo(String, usize);
227             // struct Foo {
228             //     a: i32,
229             //     b: f32,
230             // }
231             adt::strukt(p, m);
232         }
233         // test pub_macro_def
234         // pub macro m($:ident) {}
235         T![macro] => {
236             macro_def(p, m);
237         }
238         IDENT if p.at_contextual_kw("macro_rules") && p.nth(1) == BANG => {
239             macro_rules(p, m);
240         }
241         IDENT if p.at_contextual_kw("union") && p.nth(1) == IDENT => {
242             // test union_items
243             // union Foo {}
244             // union Foo {
245             //     a: i32,
246             //     b: f32,
247             // }
248             adt::union(p, m);
249         }
250         T![enum] => adt::enum_(p, m),
251         T![use] => use_item::use_(p, m),
252         T![const] if (la == IDENT || la == T![_] || la == T![mut]) => consts::konst(p, m),
253         T![static] => consts::static_(p, m),
254         // test extern_block
255         // extern {}
256         T![extern] if la == T!['{'] || (la == STRING && p.nth(2) == T!['{']) => {
257             abi(p);
258             extern_item_list(p);
259             m.complete(p, EXTERN_BLOCK);
260         }
261         _ => return Err(m),
262     };
263     Ok(())
264 }
265
266 fn extern_crate(p: &mut Parser, m: Marker) {
267     assert!(p.at(T![extern]));
268     p.bump(T![extern]);
269     assert!(p.at(T![crate]));
270     p.bump(T![crate]);
271
272     if p.at(T![self]) {
273         let m = p.start();
274         p.bump(T![self]);
275         m.complete(p, NAME_REF);
276     } else {
277         name_ref(p);
278     }
279
280     opt_rename(p);
281     p.expect(T![;]);
282     m.complete(p, EXTERN_CRATE);
283 }
284
285 pub(crate) fn extern_item_list(p: &mut Parser) {
286     assert!(p.at(T!['{']));
287     let m = p.start();
288     p.bump(T!['{']);
289     mod_contents(p, true);
290     p.expect(T!['}']);
291     m.complete(p, EXTERN_ITEM_LIST);
292 }
293
294 fn fn_(p: &mut Parser) {
295     assert!(p.at(T![fn]));
296     p.bump(T![fn]);
297
298     name_r(p, ITEM_RECOVERY_SET);
299     // test function_type_params
300     // fn foo<T: Clone + Copy>(){}
301     type_params::opt_generic_param_list(p);
302
303     if p.at(T!['(']) {
304         params::param_list_fn_def(p);
305     } else {
306         p.error("expected function arguments");
307     }
308     // test function_ret_type
309     // fn foo() {}
310     // fn bar() -> () {}
311     opt_ret_type(p);
312
313     // test function_where_clause
314     // fn foo<T>() where T: Copy {}
315     type_params::opt_where_clause(p);
316
317     // test fn_decl
318     // trait T { fn foo(); }
319     if p.at(T![;]) {
320         p.bump(T![;]);
321     } else {
322         expressions::block_expr(p)
323     }
324 }
325
326 // test type_item
327 // type Foo = Bar;
328 fn type_alias(p: &mut Parser, m: Marker) {
329     assert!(p.at(T![type]));
330     p.bump(T![type]);
331
332     name(p);
333
334     // test type_item_type_params
335     // type Result<T> = ();
336     type_params::opt_generic_param_list(p);
337
338     if p.at(T![:]) {
339         type_params::bounds(p);
340     }
341
342     // test type_item_where_clause
343     // type Foo where Foo: Copy = ();
344     type_params::opt_where_clause(p);
345     if p.eat(T![=]) {
346         types::type_(p);
347     }
348     p.expect(T![;]);
349     m.complete(p, TYPE_ALIAS);
350 }
351
352 pub(crate) fn mod_item(p: &mut Parser, m: Marker) {
353     assert!(p.at(T![mod]));
354     p.bump(T![mod]);
355
356     name(p);
357     if p.at(T!['{']) {
358         item_list(p);
359     } else if !p.eat(T![;]) {
360         p.error("expected `;` or `{`");
361     }
362     m.complete(p, MODULE);
363 }
364
365 pub(crate) fn item_list(p: &mut Parser) {
366     assert!(p.at(T!['{']));
367     let m = p.start();
368     p.bump(T!['{']);
369     mod_contents(p, true);
370     p.expect(T!['}']);
371     m.complete(p, ITEM_LIST);
372 }
373
374 fn macro_rules(p: &mut Parser, m: Marker) {
375     assert!(p.at_contextual_kw("macro_rules"));
376     p.bump_remap(T![macro_rules]);
377     p.expect(T![!]);
378
379     if p.at(IDENT) {
380         name(p);
381     }
382     // Special-case `macro_rules! try`.
383     // This is a hack until we do proper edition support
384
385     // test try_macro_rules
386     // macro_rules! try { () => {} }
387     if p.at(T![try]) {
388         let m = p.start();
389         p.bump_remap(IDENT);
390         m.complete(p, NAME);
391     }
392
393     match p.current() {
394         // test macro_rules_non_brace
395         // macro_rules! m ( ($i:ident) => {} );
396         // macro_rules! m [ ($i:ident) => {} ];
397         T!['['] | T!['('] => {
398             token_tree(p);
399             p.expect(T![;]);
400         }
401         T!['{'] => token_tree(p),
402         _ => p.error("expected `{`, `[`, `(`"),
403     }
404     m.complete(p, MACRO_RULES);
405 }
406
407 // test macro_def
408 // macro m { ($i:ident) => {} }
409 // macro m($i:ident) {}
410 fn macro_def(p: &mut Parser, m: Marker) {
411     p.expect(T![macro]);
412     name_r(p, ITEM_RECOVERY_SET);
413     if p.at(T!['{']) {
414         token_tree(p);
415     } else if !p.at(T!['(']) {
416         p.error("unmatched `(`");
417     } else {
418         let m = p.start();
419         token_tree(p);
420         match p.current() {
421             T!['{'] | T!['['] | T!['('] => token_tree(p),
422             _ => p.error("expected `{`, `[`, `(`"),
423         }
424         m.complete(p, TOKEN_TREE);
425     }
426
427     m.complete(p, MACRO_DEF);
428 }
429
430 fn macro_call(p: &mut Parser) -> BlockLike {
431     assert!(paths::is_use_path_start(p));
432     paths::use_path(p);
433     macro_call_after_excl(p)
434 }
435
436 pub(super) fn macro_call_after_excl(p: &mut Parser) -> BlockLike {
437     p.expect(T![!]);
438
439     match p.current() {
440         T!['{'] => {
441             token_tree(p);
442             BlockLike::Block
443         }
444         T!['('] | T!['['] => {
445             token_tree(p);
446             BlockLike::NotBlock
447         }
448         _ => {
449             p.error("expected `{`, `[`, `(`");
450             BlockLike::NotBlock
451         }
452     }
453 }
454
455 pub(crate) fn token_tree(p: &mut Parser) {
456     let closing_paren_kind = match p.current() {
457         T!['{'] => T!['}'],
458         T!['('] => T![')'],
459         T!['['] => T![']'],
460         _ => unreachable!(),
461     };
462     let m = p.start();
463     p.bump_any();
464     while !p.at(EOF) && !p.at(closing_paren_kind) {
465         match p.current() {
466             T!['{'] | T!['('] | T!['['] => token_tree(p),
467             T!['}'] => {
468                 p.error("unmatched `}`");
469                 m.complete(p, TOKEN_TREE);
470                 return;
471             }
472             T![')'] | T![']'] => p.err_and_bump("unmatched brace"),
473             _ => p.bump_any(),
474         }
475     }
476     p.expect(closing_paren_kind);
477     m.complete(p, TOKEN_TREE);
478 }