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