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