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