]> git.lizzy.rs Git - rust.git/blob - crates/parser/src/grammar.rs
Merge #6963
[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` to learn about API, available to the grammar,
10 //! and see docs for `Event` to learn how this actually manages to
11 //! 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 xtask codegen` 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 mod attributes;
31 mod expressions;
32 mod items;
33 mod params;
34 mod paths;
35 mod patterns;
36 mod type_args;
37 mod type_params;
38 mod types;
39
40 use crate::{
41     parser::{CompletedMarker, Marker, Parser},
42     SyntaxKind::{self, *},
43     TokenSet,
44 };
45
46 pub(crate) fn root(p: &mut Parser) {
47     let m = p.start();
48     p.eat(SHEBANG);
49     items::mod_contents(p, false);
50     m.complete(p, SOURCE_FILE);
51 }
52
53 /// Various pieces of syntax that can be parsed by macros by example
54 pub(crate) mod fragments {
55     use super::*;
56
57     pub(crate) use super::{
58         expressions::block_expr, paths::type_path as path, patterns::pattern_single, types::type_,
59     };
60
61     pub(crate) fn expr(p: &mut Parser) {
62         let _ = expressions::expr(p);
63     }
64
65     pub(crate) fn stmt(p: &mut Parser) {
66         expressions::stmt(p, expressions::StmtWithSemi::No)
67     }
68
69     pub(crate) fn opt_visibility(p: &mut Parser) {
70         let _ = super::opt_visibility(p);
71     }
72
73     // Parse a meta item , which excluded [], e.g : #[ MetaItem ]
74     pub(crate) fn meta_item(p: &mut Parser) {
75         fn is_delimiter(p: &mut Parser) -> bool {
76             matches!(p.current(), T!['{'] | T!['('] | T!['['])
77         }
78
79         if is_delimiter(p) {
80             items::token_tree(p);
81             return;
82         }
83
84         let m = p.start();
85         while !p.at(EOF) {
86             if is_delimiter(p) {
87                 items::token_tree(p);
88                 break;
89             } else {
90                 // https://doc.rust-lang.org/reference/attributes.html
91                 // https://doc.rust-lang.org/reference/paths.html#simple-paths
92                 // The start of an meta must be a simple path
93                 match p.current() {
94                     IDENT | T![::] | T![super] | T![self] | T![crate] => p.bump_any(),
95                     T![=] => {
96                         p.bump_any();
97                         match p.current() {
98                             c if c.is_literal() => p.bump_any(),
99                             T![true] | T![false] => p.bump_any(),
100                             _ => {}
101                         }
102                         break;
103                     }
104                     _ => break,
105                 }
106             }
107         }
108
109         m.complete(p, TOKEN_TREE);
110     }
111
112     pub(crate) fn item(p: &mut Parser) {
113         items::item_or_macro(p, true)
114     }
115
116     pub(crate) fn macro_items(p: &mut Parser) {
117         let m = p.start();
118         items::mod_contents(p, false);
119         m.complete(p, MACRO_ITEMS);
120     }
121
122     pub(crate) fn macro_stmts(p: &mut Parser) {
123         let m = p.start();
124
125         while !p.at(EOF) {
126             if p.at(T![;]) {
127                 p.bump(T![;]);
128                 continue;
129             }
130
131             expressions::stmt(p, expressions::StmtWithSemi::Optional);
132         }
133
134         m.complete(p, MACRO_STMTS);
135     }
136
137     pub(crate) fn attr(p: &mut Parser) {
138         attributes::outer_attrs(p)
139     }
140 }
141
142 pub(crate) fn reparser(
143     node: SyntaxKind,
144     first_child: Option<SyntaxKind>,
145     parent: Option<SyntaxKind>,
146 ) -> Option<fn(&mut Parser)> {
147     let res = match node {
148         BLOCK_EXPR => expressions::block_expr,
149         RECORD_FIELD_LIST => items::record_field_list,
150         RECORD_EXPR_FIELD_LIST => items::record_expr_field_list,
151         VARIANT_LIST => items::variant_list,
152         MATCH_ARM_LIST => items::match_arm_list,
153         USE_TREE_LIST => items::use_tree_list,
154         EXTERN_ITEM_LIST => items::extern_item_list,
155         TOKEN_TREE if first_child? == T!['{'] => items::token_tree,
156         ASSOC_ITEM_LIST => match parent? {
157             IMPL => items::assoc_item_list,
158             TRAIT => items::assoc_item_list,
159             _ => return None,
160         },
161         ITEM_LIST => items::item_list,
162         _ => return None,
163     };
164     Some(res)
165 }
166
167 #[derive(Clone, Copy, PartialEq, Eq)]
168 enum BlockLike {
169     Block,
170     NotBlock,
171 }
172
173 impl BlockLike {
174     fn is_block(self) -> bool {
175         self == BlockLike::Block
176     }
177 }
178
179 fn opt_visibility(p: &mut Parser) -> bool {
180     match p.current() {
181         T![pub] => {
182             let m = p.start();
183             p.bump(T![pub]);
184             if p.at(T!['(']) {
185                 match p.nth(1) {
186                     // test crate_visibility
187                     // pub(crate) struct S;
188                     // pub(self) struct S;
189                     // pub(self) struct S;
190                     // pub(self) struct S;
191
192                     // test pub_parens_typepath
193                     // struct B(pub (super::A));
194                     // struct B(pub (crate::A,));
195                     T![crate] | T![self] | T![super] if p.nth(2) != T![:] => {
196                         p.bump_any();
197                         p.bump_any();
198                         p.expect(T![')']);
199                     }
200                     T![in] => {
201                         p.bump_any();
202                         p.bump_any();
203                         paths::use_path(p);
204                         p.expect(T![')']);
205                     }
206                     _ => (),
207                 }
208             }
209             m.complete(p, VISIBILITY);
210         }
211         // test crate_keyword_vis
212         // crate fn main() { }
213         // struct S { crate field: u32 }
214         // struct T(crate u32);
215         //
216         // test crate_keyword_path
217         // fn foo() { crate::foo(); }
218         T![crate] if !p.nth_at(1, T![::]) => {
219             let m = p.start();
220             p.bump(T![crate]);
221             m.complete(p, VISIBILITY);
222         }
223         _ => return false,
224     }
225     true
226 }
227
228 fn opt_rename(p: &mut Parser) {
229     if p.at(T![as]) {
230         let m = p.start();
231         p.bump(T![as]);
232         if !p.eat(T![_]) {
233             name(p);
234         }
235         m.complete(p, RENAME);
236     }
237 }
238
239 fn abi(p: &mut Parser) {
240     assert!(p.at(T![extern]));
241     let abi = p.start();
242     p.bump(T![extern]);
243     p.eat(STRING);
244     abi.complete(p, ABI);
245 }
246
247 fn opt_ret_type(p: &mut Parser) -> bool {
248     if p.at(T![->]) {
249         let m = p.start();
250         p.bump(T![->]);
251         types::type_no_bounds(p);
252         m.complete(p, RET_TYPE);
253         true
254     } else {
255         false
256     }
257 }
258
259 fn name_r(p: &mut Parser, recovery: TokenSet) {
260     if p.at(IDENT) {
261         let m = p.start();
262         p.bump(IDENT);
263         m.complete(p, NAME);
264     } else {
265         p.err_recover("expected a name", recovery);
266     }
267 }
268
269 fn name(p: &mut Parser) {
270     name_r(p, TokenSet::EMPTY)
271 }
272
273 fn name_ref(p: &mut Parser) {
274     if p.at(IDENT) {
275         let m = p.start();
276         p.bump(IDENT);
277         m.complete(p, NAME_REF);
278     } else {
279         p.err_and_bump("expected identifier");
280     }
281 }
282
283 fn name_ref_or_index(p: &mut Parser) {
284     assert!(p.at(IDENT) || p.at(INT_NUMBER));
285     let m = p.start();
286     p.bump_any();
287     m.complete(p, NAME_REF);
288 }
289
290 fn lifetime(p: &mut Parser) {
291     assert!(p.at(LIFETIME_IDENT));
292     let m = p.start();
293     p.bump(LIFETIME_IDENT);
294     m.complete(p, LIFETIME);
295 }
296
297 fn error_block(p: &mut Parser, message: &str) {
298     assert!(p.at(T!['{']));
299     let m = p.start();
300     p.error(message);
301     p.bump(T!['{']);
302     expressions::expr_block_contents(p);
303     p.eat(T!['}']);
304     m.complete(p, ERROR);
305 }