]> git.lizzy.rs Git - rust.git/blob - crates/parser/src/grammar.rs
move ty
[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     }
73 }
74
75 pub(crate) mod entry_points {
76     use super::*;
77
78     pub(crate) fn source_file(p: &mut Parser) {
79         let m = p.start();
80         p.eat(SHEBANG);
81         items::mod_contents(p, false);
82         m.complete(p, SOURCE_FILE);
83     }
84
85     pub(crate) use paths::type_path as path;
86
87     pub(crate) fn expr(p: &mut Parser) {
88         let _ = expressions::expr(p);
89     }
90
91     pub(crate) fn stmt_optional_semi(p: &mut Parser) {
92         expressions::stmt(p, expressions::StmtWithSemi::Optional, false);
93     }
94
95     // Parse a meta item , which excluded [], e.g : #[ MetaItem ]
96     pub(crate) fn meta_item(p: &mut Parser) {
97         attributes::meta(p);
98     }
99
100     pub(crate) fn item(p: &mut Parser) {
101         items::item_or_macro(p, true);
102     }
103
104     pub(crate) fn macro_items(p: &mut Parser) {
105         let m = p.start();
106         items::mod_contents(p, false);
107         m.complete(p, MACRO_ITEMS);
108     }
109
110     pub(crate) fn macro_stmts(p: &mut Parser) {
111         let m = p.start();
112
113         while !p.at(EOF) {
114             if p.at(T![;]) {
115                 p.bump(T![;]);
116                 continue;
117             }
118
119             expressions::stmt(p, expressions::StmtWithSemi::Optional, true);
120         }
121
122         m.complete(p, MACRO_STMTS);
123     }
124
125     pub(crate) fn attr(p: &mut Parser) {
126         attributes::outer_attrs(p);
127     }
128 }
129
130 pub(crate) fn reparser(
131     node: SyntaxKind,
132     first_child: Option<SyntaxKind>,
133     parent: Option<SyntaxKind>,
134 ) -> Option<fn(&mut Parser)> {
135     let res = match node {
136         BLOCK_EXPR => expressions::block_expr,
137         RECORD_FIELD_LIST => items::record_field_list,
138         RECORD_EXPR_FIELD_LIST => items::record_expr_field_list,
139         VARIANT_LIST => items::variant_list,
140         MATCH_ARM_LIST => items::match_arm_list,
141         USE_TREE_LIST => items::use_tree_list,
142         EXTERN_ITEM_LIST => items::extern_item_list,
143         TOKEN_TREE if first_child? == T!['{'] => items::token_tree,
144         ASSOC_ITEM_LIST => match parent? {
145             IMPL | TRAIT => items::assoc_item_list,
146             _ => return None,
147         },
148         ITEM_LIST => items::item_list,
149         _ => return None,
150     };
151     Some(res)
152 }
153
154 #[derive(Clone, Copy, PartialEq, Eq)]
155 enum BlockLike {
156     Block,
157     NotBlock,
158 }
159
160 impl BlockLike {
161     fn is_block(self) -> bool {
162         self == BlockLike::Block
163     }
164 }
165
166 fn opt_visibility(p: &mut Parser, in_tuple_field: bool) -> bool {
167     match p.current() {
168         T![pub] => {
169             let m = p.start();
170             p.bump(T![pub]);
171             if p.at(T!['(']) {
172                 match p.nth(1) {
173                     // test crate_visibility
174                     // pub(crate) struct S;
175                     // pub(self) struct S;
176                     // pub(super) struct S;
177
178                     // test pub_parens_typepath
179                     // struct B(pub (super::A));
180                     // struct B(pub (crate::A,));
181                     T![crate] | T![self] | T![super] | T![ident] if p.nth(2) != T![:] => {
182                         // If we are in a tuple struct, then the parens following `pub`
183                         // might be an tuple field, not part of the visibility. So in that
184                         // case we don't want to consume an identifier.
185
186                         // test pub_tuple_field
187                         // struct MyStruct(pub (u32, u32));
188                         if !(in_tuple_field && matches!(p.nth(1), T![ident])) {
189                             p.bump(T!['(']);
190                             paths::use_path(p);
191                             p.expect(T![')']);
192                         }
193                     }
194                     // test crate_visibility_in
195                     // pub(in super::A) struct S;
196                     // pub(in crate) struct S;
197                     T![in] => {
198                         p.bump(T!['(']);
199                         p.bump(T![in]);
200                         paths::use_path(p);
201                         p.expect(T![')']);
202                     }
203                     _ => (),
204                 }
205             }
206             m.complete(p, VISIBILITY);
207             true
208         }
209         // test crate_keyword_vis
210         // crate fn main() { }
211         // struct S { crate field: u32 }
212         // struct T(crate u32);
213         T![crate] => {
214             if p.nth_at(1, T![::]) {
215                 // test crate_keyword_path
216                 // fn foo() { crate::foo(); }
217                 return false;
218             }
219             let m = p.start();
220             p.bump(T![crate]);
221             m.complete(p, VISIBILITY);
222             true
223         }
224         _ => false,
225     }
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 }