]> git.lizzy.rs Git - rust.git/blob - crates/parser/src/grammar.rs
Merge #10734
[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_points {
48     use super::*;
49
50     pub(crate) fn source_file(p: &mut Parser) {
51         let m = p.start();
52         p.eat(SHEBANG);
53         items::mod_contents(p, false);
54         m.complete(p, SOURCE_FILE);
55     }
56
57     pub(crate) use expressions::block_expr;
58
59     pub(crate) use paths::type_path as path;
60
61     pub(crate) use patterns::pattern_single as pattern;
62
63     pub(crate) use types::type_;
64
65     pub(crate) fn expr(p: &mut Parser) {
66         let _ = expressions::expr(p);
67     }
68
69     pub(crate) fn stmt(p: &mut Parser) {
70         expressions::stmt(p, expressions::StmtWithSemi::No, true);
71     }
72
73     pub(crate) fn stmt_optional_semi(p: &mut Parser) {
74         expressions::stmt(p, expressions::StmtWithSemi::Optional, false);
75     }
76
77     pub(crate) fn visibility(p: &mut Parser) {
78         let _ = opt_visibility(p, false);
79     }
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     pub(crate) fn item(p: &mut Parser) {
87         items::item_or_macro(p, true);
88     }
89
90     pub(crate) fn macro_items(p: &mut Parser) {
91         let m = p.start();
92         items::mod_contents(p, false);
93         m.complete(p, MACRO_ITEMS);
94     }
95
96     pub(crate) fn macro_stmts(p: &mut Parser) {
97         let m = p.start();
98
99         while !p.at(EOF) {
100             if p.at(T![;]) {
101                 p.bump(T![;]);
102                 continue;
103             }
104
105             expressions::stmt(p, expressions::StmtWithSemi::Optional, true);
106         }
107
108         m.complete(p, MACRO_STMTS);
109     }
110
111     pub(crate) fn attr(p: &mut Parser) {
112         attributes::outer_attrs(p);
113     }
114 }
115
116 pub(crate) fn reparser(
117     node: SyntaxKind,
118     first_child: Option<SyntaxKind>,
119     parent: Option<SyntaxKind>,
120 ) -> Option<fn(&mut Parser)> {
121     let res = match node {
122         BLOCK_EXPR => expressions::block_expr,
123         RECORD_FIELD_LIST => items::record_field_list,
124         RECORD_EXPR_FIELD_LIST => items::record_expr_field_list,
125         VARIANT_LIST => items::variant_list,
126         MATCH_ARM_LIST => items::match_arm_list,
127         USE_TREE_LIST => items::use_tree_list,
128         EXTERN_ITEM_LIST => items::extern_item_list,
129         TOKEN_TREE if first_child? == T!['{'] => items::token_tree,
130         ASSOC_ITEM_LIST => match parent? {
131             IMPL | TRAIT => items::assoc_item_list,
132             _ => return None,
133         },
134         ITEM_LIST => items::item_list,
135         _ => return None,
136     };
137     Some(res)
138 }
139
140 #[derive(Clone, Copy, PartialEq, Eq)]
141 enum BlockLike {
142     Block,
143     NotBlock,
144 }
145
146 impl BlockLike {
147     fn is_block(self) -> bool {
148         self == BlockLike::Block
149     }
150 }
151
152 fn opt_visibility(p: &mut Parser, in_tuple_field: bool) -> bool {
153     match p.current() {
154         T![pub] => {
155             let m = p.start();
156             p.bump(T![pub]);
157             if p.at(T!['(']) {
158                 match p.nth(1) {
159                     // test crate_visibility
160                     // pub(crate) struct S;
161                     // pub(self) struct S;
162                     // pub(super) struct S;
163
164                     // test pub_parens_typepath
165                     // struct B(pub (super::A));
166                     // struct B(pub (crate::A,));
167                     T![crate] | T![self] | T![super] | T![ident] if p.nth(2) != T![:] => {
168                         // If we are in a tuple struct, then the parens following `pub`
169                         // might be an tuple field, not part of the visibility. So in that
170                         // case we don't want to consume an identifier.
171
172                         // test pub_tuple_field
173                         // struct MyStruct(pub (u32, u32));
174                         if !(in_tuple_field && matches!(p.nth(1), T![ident])) {
175                             p.bump(T!['(']);
176                             paths::use_path(p);
177                             p.expect(T![')']);
178                         }
179                     }
180                     // test crate_visibility_in
181                     // pub(in super::A) struct S;
182                     // pub(in crate) struct S;
183                     T![in] => {
184                         p.bump(T!['(']);
185                         p.bump(T![in]);
186                         paths::use_path(p);
187                         p.expect(T![')']);
188                     }
189                     _ => (),
190                 }
191             }
192             m.complete(p, VISIBILITY);
193             true
194         }
195         // test crate_keyword_vis
196         // crate fn main() { }
197         // struct S { crate field: u32 }
198         // struct T(crate u32);
199         T![crate] => {
200             if p.nth_at(1, T![::]) {
201                 // test crate_keyword_path
202                 // fn foo() { crate::foo(); }
203                 return false;
204             }
205             let m = p.start();
206             p.bump(T![crate]);
207             m.complete(p, VISIBILITY);
208             true
209         }
210         _ => false,
211     }
212 }
213
214 fn opt_rename(p: &mut Parser) {
215     if p.at(T![as]) {
216         let m = p.start();
217         p.bump(T![as]);
218         if !p.eat(T![_]) {
219             name(p);
220         }
221         m.complete(p, RENAME);
222     }
223 }
224
225 fn abi(p: &mut Parser) {
226     assert!(p.at(T![extern]));
227     let abi = p.start();
228     p.bump(T![extern]);
229     p.eat(STRING);
230     abi.complete(p, ABI);
231 }
232
233 fn opt_ret_type(p: &mut Parser) -> bool {
234     if p.at(T![->]) {
235         let m = p.start();
236         p.bump(T![->]);
237         types::type_no_bounds(p);
238         m.complete(p, RET_TYPE);
239         true
240     } else {
241         false
242     }
243 }
244
245 fn name_r(p: &mut Parser, recovery: TokenSet) {
246     if p.at(IDENT) {
247         let m = p.start();
248         p.bump(IDENT);
249         m.complete(p, NAME);
250     } else {
251         p.err_recover("expected a name", recovery);
252     }
253 }
254
255 fn name(p: &mut Parser) {
256     name_r(p, TokenSet::EMPTY);
257 }
258
259 fn name_ref(p: &mut Parser) {
260     if p.at(IDENT) {
261         let m = p.start();
262         p.bump(IDENT);
263         m.complete(p, NAME_REF);
264     } else {
265         p.err_and_bump("expected identifier");
266     }
267 }
268
269 fn name_ref_or_index(p: &mut Parser) {
270     assert!(p.at(IDENT) || p.at(INT_NUMBER));
271     let m = p.start();
272     p.bump_any();
273     m.complete(p, NAME_REF);
274 }
275
276 fn lifetime(p: &mut Parser) {
277     assert!(p.at(LIFETIME_IDENT));
278     let m = p.start();
279     p.bump(LIFETIME_IDENT);
280     m.complete(p, LIFETIME);
281 }
282
283 fn error_block(p: &mut Parser, message: &str) {
284     assert!(p.at(T!['{']));
285     let m = p.start();
286     p.error(message);
287     p.bump(T!['{']);
288     expressions::expr_block_contents(p);
289     p.eat(T!['}']);
290     m.complete(p, ERROR);
291 }