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