]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/lexer/tokentrees.rs
Rollup merge of #68033 - ollie27:win_f32, r=dtolnay
[rust.git] / src / librustc_parse / lexer / tokentrees.rs
1 use super::{StringReader, UnmatchedBrace};
2
3 use rustc_data_structures::fx::FxHashMap;
4 use rustc_errors::PResult;
5 use rustc_span::Span;
6 use syntax::print::pprust::token_to_string;
7 use syntax::token::{self, Token};
8 use syntax::tokenstream::{
9     DelimSpan,
10     IsJoint::{self, *},
11     TokenStream, TokenTree, TreeAndJoint,
12 };
13
14 impl<'a> StringReader<'a> {
15     crate fn into_token_trees(self) -> (PResult<'a, TokenStream>, Vec<UnmatchedBrace>) {
16         let mut tt_reader = TokenTreesReader {
17             string_reader: self,
18             token: Token::dummy(),
19             joint_to_prev: Joint,
20             open_braces: Vec::new(),
21             unmatched_braces: Vec::new(),
22             matching_delim_spans: Vec::new(),
23             last_unclosed_found_span: None,
24             last_delim_empty_block_spans: FxHashMap::default(),
25         };
26         let res = tt_reader.parse_all_token_trees();
27         (res, tt_reader.unmatched_braces)
28     }
29 }
30
31 struct TokenTreesReader<'a> {
32     string_reader: StringReader<'a>,
33     token: Token,
34     joint_to_prev: IsJoint,
35     /// Stack of open delimiters and their spans. Used for error message.
36     open_braces: Vec<(token::DelimToken, Span)>,
37     unmatched_braces: Vec<UnmatchedBrace>,
38     /// The type and spans for all braces
39     ///
40     /// Used only for error recovery when arriving to EOF with mismatched braces.
41     matching_delim_spans: Vec<(token::DelimToken, Span, Span)>,
42     last_unclosed_found_span: Option<Span>,
43     last_delim_empty_block_spans: FxHashMap<token::DelimToken, Span>,
44 }
45
46 impl<'a> TokenTreesReader<'a> {
47     // Parse a stream of tokens into a list of `TokenTree`s, up to an `Eof`.
48     fn parse_all_token_trees(&mut self) -> PResult<'a, TokenStream> {
49         let mut buf = TokenStreamBuilder::default();
50
51         self.real_token();
52         while self.token != token::Eof {
53             buf.push(self.parse_token_tree()?);
54         }
55
56         Ok(buf.into_token_stream())
57     }
58
59     // Parse a stream of tokens into a list of `TokenTree`s, up to a `CloseDelim`.
60     fn parse_token_trees_until_close_delim(&mut self) -> TokenStream {
61         let mut buf = TokenStreamBuilder::default();
62         loop {
63             if let token::CloseDelim(..) = self.token.kind {
64                 return buf.into_token_stream();
65             }
66
67             match self.parse_token_tree() {
68                 Ok(tree) => buf.push(tree),
69                 Err(mut e) => {
70                     e.emit();
71                     return buf.into_token_stream();
72                 }
73             }
74         }
75     }
76
77     fn parse_token_tree(&mut self) -> PResult<'a, TreeAndJoint> {
78         let sm = self.string_reader.sess.source_map();
79         match self.token.kind {
80             token::Eof => {
81                 let msg = "this file contains an unclosed delimiter";
82                 let mut err =
83                     self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, msg);
84                 for &(_, sp) in &self.open_braces {
85                     err.span_label(sp, "unclosed delimiter");
86                     self.unmatched_braces.push(UnmatchedBrace {
87                         expected_delim: token::DelimToken::Brace,
88                         found_delim: None,
89                         found_span: self.token.span,
90                         unclosed_span: Some(sp),
91                         candidate_span: None,
92                     });
93                 }
94
95                 if let Some((delim, _)) = self.open_braces.last() {
96                     if let Some((_, open_sp, close_sp)) = self
97                         .matching_delim_spans
98                         .iter()
99                         .filter(|(d, open_sp, close_sp)| {
100                             if let Some(close_padding) = sm.span_to_margin(*close_sp) {
101                                 if let Some(open_padding) = sm.span_to_margin(*open_sp) {
102                                     return delim == d && close_padding != open_padding;
103                                 }
104                             }
105                             false
106                         })
107                         .next()
108                     // these are in reverse order as they get inserted on close, but
109                     {
110                         // we want the last open/first close
111                         err.span_label(*open_sp, "this delimiter might not be properly closed...");
112                         err.span_label(
113                             *close_sp,
114                             "...as it matches this but it has different indentation",
115                         );
116                     }
117                 }
118                 Err(err)
119             }
120             token::OpenDelim(delim) => {
121                 // The span for beginning of the delimited section
122                 let pre_span = self.token.span;
123
124                 // Parse the open delimiter.
125                 self.open_braces.push((delim, self.token.span));
126                 self.real_token();
127
128                 // Parse the token trees within the delimiters.
129                 // We stop at any delimiter so we can try to recover if the user
130                 // uses an incorrect delimiter.
131                 let tts = self.parse_token_trees_until_close_delim();
132
133                 // Expand to cover the entire delimited token tree
134                 let delim_span = DelimSpan::from_pair(pre_span, self.token.span);
135
136                 match self.token.kind {
137                     // Correct delimiter.
138                     token::CloseDelim(d) if d == delim => {
139                         let (open_brace, open_brace_span) = self.open_braces.pop().unwrap();
140                         let close_brace_span = self.token.span;
141
142                         if tts.is_empty() {
143                             let empty_block_span = open_brace_span.to(close_brace_span);
144                             self.last_delim_empty_block_spans.insert(delim, empty_block_span);
145                         }
146
147                         if self.open_braces.len() == 0 {
148                             // Clear up these spans to avoid suggesting them as we've found
149                             // properly matched delimiters so far for an entire block.
150                             self.matching_delim_spans.clear();
151                         } else {
152                             self.matching_delim_spans.push((
153                                 open_brace,
154                                 open_brace_span,
155                                 close_brace_span,
156                             ));
157                         }
158                         // Parse the closing delimiter.
159                         self.real_token();
160                     }
161                     // Incorrect delimiter.
162                     token::CloseDelim(other) => {
163                         let mut unclosed_delimiter = None;
164                         let mut candidate = None;
165                         if self.last_unclosed_found_span != Some(self.token.span) {
166                             // do not complain about the same unclosed delimiter multiple times
167                             self.last_unclosed_found_span = Some(self.token.span);
168                             // This is a conservative error: only report the last unclosed
169                             // delimiter. The previous unclosed delimiters could actually be
170                             // closed! The parser just hasn't gotten to them yet.
171                             if let Some(&(_, sp)) = self.open_braces.last() {
172                                 unclosed_delimiter = Some(sp);
173                             };
174                             if let Some(current_padding) = sm.span_to_margin(self.token.span) {
175                                 for (brace, brace_span) in &self.open_braces {
176                                     if let Some(padding) = sm.span_to_margin(*brace_span) {
177                                         // high likelihood of these two corresponding
178                                         if current_padding == padding && brace == &other {
179                                             candidate = Some(*brace_span);
180                                         }
181                                     }
182                                 }
183                             }
184                             let (tok, _) = self.open_braces.pop().unwrap();
185                             self.unmatched_braces.push(UnmatchedBrace {
186                                 expected_delim: tok,
187                                 found_delim: Some(other),
188                                 found_span: self.token.span,
189                                 unclosed_span: unclosed_delimiter,
190                                 candidate_span: candidate,
191                             });
192                         } else {
193                             self.open_braces.pop();
194                         }
195
196                         // If the incorrect delimiter matches an earlier opening
197                         // delimiter, then don't consume it (it can be used to
198                         // close the earlier one). Otherwise, consume it.
199                         // E.g., we try to recover from:
200                         // fn foo() {
201                         //     bar(baz(
202                         // }  // Incorrect delimiter but matches the earlier `{`
203                         if !self.open_braces.iter().any(|&(b, _)| b == other) {
204                             self.real_token();
205                         }
206                     }
207                     token::Eof => {
208                         // Silently recover, the EOF token will be seen again
209                         // and an error emitted then. Thus we don't pop from
210                         // self.open_braces here.
211                     }
212                     _ => {}
213                 }
214
215                 Ok(TokenTree::Delimited(delim_span, delim, tts.into()).into())
216             }
217             token::CloseDelim(delim) => {
218                 // An unexpected closing delimiter (i.e., there is no
219                 // matching opening delimiter).
220                 let token_str = token_to_string(&self.token);
221                 let msg = format!("unexpected closing delimiter: `{}`", token_str);
222                 let mut err =
223                     self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, &msg);
224
225                 if let Some(span) = self.last_delim_empty_block_spans.remove(&delim) {
226                     err.span_label(
227                         span,
228                         "this block is empty, you might have not meant to close it",
229                     );
230                 }
231                 err.span_label(self.token.span, "unexpected closing delimiter");
232                 Err(err)
233             }
234             _ => {
235                 let tt = TokenTree::Token(self.token.take());
236                 self.real_token();
237                 let is_joint = self.joint_to_prev == Joint && self.token.is_op();
238                 Ok((tt, if is_joint { Joint } else { NonJoint }))
239             }
240         }
241     }
242
243     fn real_token(&mut self) {
244         self.joint_to_prev = Joint;
245         loop {
246             let token = self.string_reader.next_token();
247             match token.kind {
248                 token::Whitespace | token::Comment | token::Shebang(_) | token::Unknown(_) => {
249                     self.joint_to_prev = NonJoint;
250                 }
251                 _ => {
252                     self.token = token;
253                     return;
254                 }
255             }
256         }
257     }
258 }
259
260 #[derive(Default)]
261 struct TokenStreamBuilder {
262     buf: Vec<TreeAndJoint>,
263 }
264
265 impl TokenStreamBuilder {
266     fn push(&mut self, (tree, joint): TreeAndJoint) {
267         if let Some((TokenTree::Token(prev_token), Joint)) = self.buf.last() {
268             if let TokenTree::Token(token) = &tree {
269                 if let Some(glued) = prev_token.glue(token) {
270                     self.buf.pop();
271                     self.buf.push((TokenTree::Token(glued), joint));
272                     return;
273                 }
274             }
275         }
276         self.buf.push((tree, joint))
277     }
278
279     fn into_token_stream(self) -> TokenStream {
280         TokenStream::new(self.buf)
281     }
282 }