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