]> git.lizzy.rs Git - rust.git/blob - crates/parser/src/grammar/items.rs
Move to upstream `macro_rules!` model
[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("macro_rules") && p.nth(1) == BANG => {
236             macro_rules(p, m);
237         }
238         IDENT if p.at_contextual_kw("union") && p.nth(1) == IDENT => {
239             // test union_items
240             // union Foo {}
241             // union Foo {
242             //     a: i32,
243             //     b: f32,
244             // }
245             adt::union(p, m);
246         }
247         T![enum] => adt::enum_(p, m),
248         T![use] => use_item::use_(p, m),
249         T![const] if (la == IDENT || la == T![_] || la == T![mut]) => consts::konst(p, m),
250         T![static] => consts::static_(p, m),
251         // test extern_block
252         // extern {}
253         T![extern] if la == T!['{'] || (la == STRING && p.nth(2) == T!['{']) => {
254             abi(p);
255             extern_item_list(p);
256             m.complete(p, EXTERN_BLOCK);
257         }
258         _ => return Err(m),
259     };
260     Ok(())
261 }
262
263 fn extern_crate(p: &mut Parser, m: Marker) {
264     assert!(p.at(T![extern]));
265     p.bump(T![extern]);
266     assert!(p.at(T![crate]));
267     p.bump(T![crate]);
268
269     if p.at(T![self]) {
270         p.bump(T![self]);
271     } else {
272         name_ref(p);
273     }
274
275     opt_rename(p);
276     p.expect(T![;]);
277     m.complete(p, EXTERN_CRATE);
278 }
279
280 pub(crate) fn extern_item_list(p: &mut Parser) {
281     assert!(p.at(T!['{']));
282     let m = p.start();
283     p.bump(T!['{']);
284     mod_contents(p, true);
285     p.expect(T!['}']);
286     m.complete(p, EXTERN_ITEM_LIST);
287 }
288
289 fn fn_(p: &mut Parser) {
290     assert!(p.at(T![fn]));
291     p.bump(T![fn]);
292
293     name_r(p, ITEM_RECOVERY_SET);
294     // test function_type_params
295     // fn foo<T: Clone + Copy>(){}
296     type_params::opt_generic_param_list(p);
297
298     if p.at(T!['(']) {
299         params::param_list_fn_def(p);
300     } else {
301         p.error("expected function arguments");
302     }
303     // test function_ret_type
304     // fn foo() {}
305     // fn bar() -> () {}
306     opt_ret_type(p);
307
308     // test function_where_clause
309     // fn foo<T>() where T: Copy {}
310     type_params::opt_where_clause(p);
311
312     // test fn_decl
313     // trait T { fn foo(); }
314     if p.at(T![;]) {
315         p.bump(T![;]);
316     } else {
317         expressions::block_expr(p)
318     }
319 }
320
321 // test type_item
322 // type Foo = Bar;
323 fn type_alias(p: &mut Parser, m: Marker) {
324     assert!(p.at(T![type]));
325     p.bump(T![type]);
326
327     name(p);
328
329     // test type_item_type_params
330     // type Result<T> = ();
331     type_params::opt_generic_param_list(p);
332
333     if p.at(T![:]) {
334         type_params::bounds(p);
335     }
336
337     // test type_item_where_clause
338     // type Foo where Foo: Copy = ();
339     type_params::opt_where_clause(p);
340     if p.eat(T![=]) {
341         types::type_(p);
342     }
343     p.expect(T![;]);
344     m.complete(p, TYPE_ALIAS);
345 }
346
347 pub(crate) fn mod_item(p: &mut Parser, m: Marker) {
348     assert!(p.at(T![mod]));
349     p.bump(T![mod]);
350
351     name(p);
352     if p.at(T!['{']) {
353         item_list(p);
354     } else if !p.eat(T![;]) {
355         p.error("expected `;` or `{`");
356     }
357     m.complete(p, MODULE);
358 }
359
360 pub(crate) fn item_list(p: &mut Parser) {
361     assert!(p.at(T!['{']));
362     let m = p.start();
363     p.bump(T!['{']);
364     mod_contents(p, true);
365     p.expect(T!['}']);
366     m.complete(p, ITEM_LIST);
367 }
368
369 fn macro_rules(p: &mut Parser, m: Marker) {
370     assert!(p.at_contextual_kw("macro_rules"));
371     p.bump_remap(T![macro_rules]);
372     p.expect(T![!]);
373
374     if p.at(IDENT) {
375         name(p);
376     }
377     // Special-case `macro_rules! try`.
378     // This is a hack until we do proper edition support
379
380     // test try_macro_rules
381     // macro_rules! try { () => {} }
382     if p.at(T![try]) {
383         let m = p.start();
384         p.bump_remap(IDENT);
385         m.complete(p, NAME);
386     }
387
388     match p.current() {
389         T!['{'] => {
390             token_tree(p);
391         }
392         _ => p.error("expected `{`"),
393     }
394     m.complete(p, MACRO_RULES);
395 }
396
397 // test macro_def
398 // macro m { ($i:ident) => {} }
399 // macro m($i:ident) {}
400 fn macro_def(p: &mut Parser, m: Marker) {
401     p.expect(T![macro]);
402     name_r(p, ITEM_RECOVERY_SET);
403     if p.at(T!['{']) {
404         token_tree(p);
405     } else if !p.at(T!['(']) {
406         p.error("unmatched `(`");
407     } else {
408         let m = p.start();
409         token_tree(p);
410         match p.current() {
411             T!['{'] | T!['['] | T!['('] => token_tree(p),
412             _ => p.error("expected `{`, `[`, `(`"),
413         }
414         m.complete(p, TOKEN_TREE);
415     }
416
417     m.complete(p, MACRO_DEF);
418 }
419
420 fn macro_call(p: &mut Parser) -> BlockLike {
421     assert!(paths::is_use_path_start(p));
422     paths::use_path(p);
423     macro_call_after_excl(p)
424 }
425
426 pub(super) fn macro_call_after_excl(p: &mut Parser) -> BlockLike {
427     p.expect(T![!]);
428
429     match p.current() {
430         T!['{'] => {
431             token_tree(p);
432             BlockLike::Block
433         }
434         T!['('] | T!['['] => {
435             token_tree(p);
436             BlockLike::NotBlock
437         }
438         _ => {
439             p.error("expected `{`, `[`, `(`");
440             BlockLike::NotBlock
441         }
442     }
443 }
444
445 pub(crate) fn token_tree(p: &mut Parser) {
446     let closing_paren_kind = match p.current() {
447         T!['{'] => T!['}'],
448         T!['('] => T![')'],
449         T!['['] => T![']'],
450         _ => unreachable!(),
451     };
452     let m = p.start();
453     p.bump_any();
454     while !p.at(EOF) && !p.at(closing_paren_kind) {
455         match p.current() {
456             T!['{'] | T!['('] | T!['['] => token_tree(p),
457             T!['}'] => {
458                 p.error("unmatched `}`");
459                 m.complete(p, TOKEN_TREE);
460                 return;
461             }
462             T![')'] | T![']'] => p.err_and_bump("unmatched brace"),
463             _ => p.bump_any(),
464         }
465     }
466     p.expect(closing_paren_kind);
467     m.complete(p, TOKEN_TREE);
468 }