]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/lexer/tokentrees.rs
use find(x) instead of filter(x).next()
[rust.git] / src / librustc_parse / lexer / tokentrees.rs
1 use super::{StringReader, UnmatchedBrace};
2
3 use rustc_ast_pretty::pprust::token_to_string;
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_errors::PResult;
6 use rustc_span::Span;
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)) =
97                         self.matching_delim_spans.iter().find(|(d, open_sp, close_sp)| {
98                             if let Some(close_padding) = sm.span_to_margin(*close_sp) {
99                                 if let Some(open_padding) = sm.span_to_margin(*open_sp) {
100                                     return delim == d && close_padding != open_padding;
101                                 }
102                             }
103                             false
104                         })
105                     // these are in reverse order as they get inserted on close, but
106                     {
107                         // we want the last open/first close
108                         err.span_label(*open_sp, "this delimiter might not be properly closed...");
109                         err.span_label(
110                             *close_sp,
111                             "...as it matches this but it has different indentation",
112                         );
113                     }
114                 }
115                 Err(err)
116             }
117             token::OpenDelim(delim) => {
118                 // The span for beginning of the delimited section
119                 let pre_span = self.token.span;
120
121                 // Parse the open delimiter.
122                 self.open_braces.push((delim, self.token.span));
123                 self.real_token();
124
125                 // Parse the token trees within the delimiters.
126                 // We stop at any delimiter so we can try to recover if the user
127                 // uses an incorrect delimiter.
128                 let tts = self.parse_token_trees_until_close_delim();
129
130                 // Expand to cover the entire delimited token tree
131                 let delim_span = DelimSpan::from_pair(pre_span, self.token.span);
132
133                 match self.token.kind {
134                     // Correct delimiter.
135                     token::CloseDelim(d) if d == delim => {
136                         let (open_brace, open_brace_span) = self.open_braces.pop().unwrap();
137                         let close_brace_span = self.token.span;
138
139                         if tts.is_empty() {
140                             let empty_block_span = open_brace_span.to(close_brace_span);
141                             self.last_delim_empty_block_spans.insert(delim, empty_block_span);
142                         }
143
144                         if self.open_braces.len() == 0 {
145                             // Clear up these spans to avoid suggesting them as we've found
146                             // properly matched delimiters so far for an entire block.
147                             self.matching_delim_spans.clear();
148                         } else {
149                             self.matching_delim_spans.push((
150                                 open_brace,
151                                 open_brace_span,
152                                 close_brace_span,
153                             ));
154                         }
155                         // Parse the closing delimiter.
156                         self.real_token();
157                     }
158                     // Incorrect delimiter.
159                     token::CloseDelim(other) => {
160                         let mut unclosed_delimiter = None;
161                         let mut candidate = None;
162                         if self.last_unclosed_found_span != Some(self.token.span) {
163                             // do not complain about the same unclosed delimiter multiple times
164                             self.last_unclosed_found_span = Some(self.token.span);
165                             // This is a conservative error: only report the last unclosed
166                             // delimiter. The previous unclosed delimiters could actually be
167                             // closed! The parser just hasn't gotten to them yet.
168                             if let Some(&(_, sp)) = self.open_braces.last() {
169                                 unclosed_delimiter = Some(sp);
170                             };
171                             if let Some(current_padding) = sm.span_to_margin(self.token.span) {
172                                 for (brace, brace_span) in &self.open_braces {
173                                     if let Some(padding) = sm.span_to_margin(*brace_span) {
174                                         // high likelihood of these two corresponding
175                                         if current_padding == padding && brace == &other {
176                                             candidate = Some(*brace_span);
177                                         }
178                                     }
179                                 }
180                             }
181                             let (tok, _) = self.open_braces.pop().unwrap();
182                             self.unmatched_braces.push(UnmatchedBrace {
183                                 expected_delim: tok,
184                                 found_delim: Some(other),
185                                 found_span: self.token.span,
186                                 unclosed_span: unclosed_delimiter,
187                                 candidate_span: candidate,
188                             });
189                         } else {
190                             self.open_braces.pop();
191                         }
192
193                         // If the incorrect delimiter matches an earlier opening
194                         // delimiter, then don't consume it (it can be used to
195                         // close the earlier one). Otherwise, consume it.
196                         // E.g., we try to recover from:
197                         // fn foo() {
198                         //     bar(baz(
199                         // }  // Incorrect delimiter but matches the earlier `{`
200                         if !self.open_braces.iter().any(|&(b, _)| b == other) {
201                             self.real_token();
202                         }
203                     }
204                     token::Eof => {
205                         // Silently recover, the EOF token will be seen again
206                         // and an error emitted then. Thus we don't pop from
207                         // self.open_braces here.
208                     }
209                     _ => {}
210                 }
211
212                 Ok(TokenTree::Delimited(delim_span, delim, tts.into()).into())
213             }
214             token::CloseDelim(delim) => {
215                 // An unexpected closing delimiter (i.e., there is no
216                 // matching opening delimiter).
217                 let token_str = token_to_string(&self.token);
218                 let msg = format!("unexpected closing delimiter: `{}`", token_str);
219                 let mut err =
220                     self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, &msg);
221
222                 if let Some(span) = self.last_delim_empty_block_spans.remove(&delim) {
223                     err.span_label(
224                         span,
225                         "this block is empty, you might have not meant to close it",
226                     );
227                 }
228                 err.span_label(self.token.span, "unexpected closing delimiter");
229                 Err(err)
230             }
231             _ => {
232                 let tt = TokenTree::Token(self.token.take());
233                 self.real_token();
234                 let is_joint = self.joint_to_prev == Joint && self.token.is_op();
235                 Ok((tt, if is_joint { Joint } else { NonJoint }))
236             }
237         }
238     }
239
240     fn real_token(&mut self) {
241         self.joint_to_prev = Joint;
242         loop {
243             let token = self.string_reader.next_token();
244             match token.kind {
245                 token::Whitespace | token::Comment | token::Shebang(_) | token::Unknown(_) => {
246                     self.joint_to_prev = NonJoint;
247                 }
248                 _ => {
249                     self.token = token;
250                     return;
251                 }
252             }
253         }
254     }
255 }
256
257 #[derive(Default)]
258 struct TokenStreamBuilder {
259     buf: Vec<TreeAndJoint>,
260 }
261
262 impl TokenStreamBuilder {
263     fn push(&mut self, (tree, joint): TreeAndJoint) {
264         if let Some((TokenTree::Token(prev_token), Joint)) = self.buf.last() {
265             if let TokenTree::Token(token) = &tree {
266                 if let Some(glued) = prev_token.glue(token) {
267                     self.buf.pop();
268                     self.buf.push((TokenTree::Token(glued), joint));
269                     return;
270                 }
271             }
272         }
273         self.buf.push((tree, joint))
274     }
275
276     fn into_token_stream(self) -> TokenStream {
277         TokenStream::new(self.buf)
278     }
279 }