]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/mod.rs
Rollup merge of #62205 - timvermeulen:iter_order_by, r=KodrAus
[rust.git] / src / libsyntax / parse / mod.rs
1 //! The main parser interface.
2
3 use crate::ast::{self, CrateConfig, NodeId};
4 use crate::early_buffered_lints::{BufferedEarlyLint, BufferedEarlyLintId};
5 use crate::source_map::{SourceMap, FilePathMapping};
6 use crate::feature_gate::UnstableFeatures;
7 use crate::parse::parser::Parser;
8 use crate::parse::parser::emit_unclosed_delims;
9 use crate::parse::token::TokenKind;
10 use crate::tokenstream::{TokenStream, TokenTree};
11 use crate::print::pprust;
12 use crate::symbol::Symbol;
13
14 use errors::{Applicability, FatalError, Level, Handler, ColorConfig, Diagnostic, DiagnosticBuilder};
15 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
16 use rustc_data_structures::sync::{Lrc, Lock, Once};
17 use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
18 use syntax_pos::edition::Edition;
19 use syntax_pos::hygiene::ExpnId;
20
21 use std::borrow::Cow;
22 use std::path::{Path, PathBuf};
23 use std::str;
24
25 #[cfg(test)]
26 mod tests;
27
28 #[macro_use]
29 pub mod parser;
30 pub mod attr;
31 pub mod lexer;
32 pub mod token;
33
34 crate mod classify;
35 crate mod diagnostics;
36 crate mod literal;
37 crate mod unescape_error_reporting;
38
39 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
40
41 /// Collected spans during parsing for places where a certain feature was
42 /// used and should be feature gated accordingly in `check_crate`.
43 #[derive(Default)]
44 pub struct GatedSpans {
45     /// Spans collected for gating `param_attrs`, e.g. `fn foo(#[attr] x: u8) {}`.
46     pub param_attrs: Lock<Vec<Span>>,
47     /// Spans collected for gating `let_chains`, e.g. `if a && let b = c {}`.
48     pub let_chains: Lock<Vec<Span>>,
49     /// Spans collected for gating `async_closure`, e.g. `async || ..`.
50     pub async_closure: Lock<Vec<Span>>,
51     /// Spans collected for gating `yield e?` expressions (`generators` gate).
52     pub yields: Lock<Vec<Span>>,
53     /// Spans collected for gating `or_patterns`, e.g. `Some(Foo | Bar)`.
54     pub or_patterns: Lock<Vec<Span>>,
55 }
56
57 /// Info about a parsing session.
58 pub struct ParseSess {
59     pub span_diagnostic: Handler,
60     pub unstable_features: UnstableFeatures,
61     pub config: CrateConfig,
62     pub edition: Edition,
63     pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
64     /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
65     pub raw_identifier_spans: Lock<Vec<Span>>,
66     /// Used to determine and report recursive module inclusions.
67     included_mod_stack: Lock<Vec<PathBuf>>,
68     source_map: Lrc<SourceMap>,
69     pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
70     /// Contains the spans of block expressions that could have been incomplete based on the
71     /// operation token that followed it, but that the parser cannot identify without further
72     /// analysis.
73     pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
74     pub injected_crate_name: Once<Symbol>,
75     pub gated_spans: GatedSpans,
76 }
77
78 impl ParseSess {
79     pub fn new(file_path_mapping: FilePathMapping) -> Self {
80         let cm = Lrc::new(SourceMap::new(file_path_mapping));
81         let handler = Handler::with_tty_emitter(
82             ColorConfig::Auto,
83             true,
84             None,
85             Some(cm.clone()),
86         );
87         ParseSess::with_span_handler(handler, cm)
88     }
89
90     pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> Self {
91         Self {
92             span_diagnostic: handler,
93             unstable_features: UnstableFeatures::from_environment(),
94             config: FxHashSet::default(),
95             edition: ExpnId::root().expn_data().edition,
96             missing_fragment_specifiers: Lock::new(FxHashSet::default()),
97             raw_identifier_spans: Lock::new(Vec::new()),
98             included_mod_stack: Lock::new(vec![]),
99             source_map,
100             buffered_lints: Lock::new(vec![]),
101             ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
102             injected_crate_name: Once::new(),
103             gated_spans: GatedSpans::default(),
104         }
105     }
106
107     #[inline]
108     pub fn source_map(&self) -> &SourceMap {
109         &self.source_map
110     }
111
112     pub fn buffer_lint<S: Into<MultiSpan>>(&self,
113         lint_id: BufferedEarlyLintId,
114         span: S,
115         id: NodeId,
116         msg: &str,
117     ) {
118         self.buffered_lints.with_lock(|buffered_lints| {
119             buffered_lints.push(BufferedEarlyLint{
120                 span: span.into(),
121                 id,
122                 msg: msg.into(),
123                 lint_id,
124             });
125         });
126     }
127
128     /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
129     /// parser to continue parsing the following operation as part of the same expression.
130     pub fn expr_parentheses_needed(
131         &self,
132         err: &mut DiagnosticBuilder<'_>,
133         span: Span,
134         alt_snippet: Option<String>,
135     ) {
136         if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
137             err.span_suggestion(
138                 span,
139                 "parentheses are required to parse this as an expression",
140                 format!("({})", snippet),
141                 Applicability::MachineApplicable,
142             );
143         }
144     }
145 }
146
147 #[derive(Clone)]
148 pub struct Directory<'a> {
149     pub path: Cow<'a, Path>,
150     pub ownership: DirectoryOwnership,
151 }
152
153 #[derive(Copy, Clone)]
154 pub enum DirectoryOwnership {
155     Owned {
156         // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`.
157         relative: Option<ast::Ident>,
158     },
159     UnownedViaBlock,
160     UnownedViaMod(bool /* legacy warnings? */),
161 }
162
163 // A bunch of utility functions of the form `parse_<thing>_from_<source>`
164 // where <thing> includes crate, expr, item, stmt, tts, and one that
165 // uses a HOF to parse anything, and <source> includes file and
166 // `source_str`.
167
168 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
169     let mut parser = new_parser_from_file(sess, input);
170     parser.parse_crate_mod()
171 }
172
173 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
174                                        -> PResult<'a, Vec<ast::Attribute>> {
175     let mut parser = new_parser_from_file(sess, input);
176     parser.parse_inner_attributes()
177 }
178
179 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
180                                        -> PResult<'_, ast::Crate> {
181     new_parser_from_source_str(sess, name, source).parse_crate_mod()
182 }
183
184 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
185                                              -> PResult<'_, Vec<ast::Attribute>> {
186     new_parser_from_source_str(sess, name, source).parse_inner_attributes()
187 }
188
189 pub fn parse_stream_from_source_str(
190     name: FileName,
191     source: String,
192     sess: &ParseSess,
193     override_span: Option<Span>,
194 ) -> TokenStream {
195     let (stream, mut errors) = source_file_to_stream(
196         sess,
197         sess.source_map().new_source_file(name, source),
198         override_span,
199     );
200     emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
201     stream
202 }
203
204 /// Creates a new parser from a source string.
205 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
206     panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
207 }
208
209 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
210 /// token stream.
211 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
212     -> Result<Parser<'_>, Vec<Diagnostic>>
213 {
214     let mut parser = maybe_source_file_to_parser(sess,
215                                                  sess.source_map().new_source_file(name, source))?;
216     parser.recurse_into_file_modules = false;
217     Ok(parser)
218 }
219
220 /// Creates a new parser, handling errors as appropriate if the file doesn't exist.
221 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
222     source_file_to_parser(sess, file_to_source_file(sess, path, None))
223 }
224
225 /// Creates a new parser, returning buffered diagnostics if the file doesn't exist,
226 /// or from lexing the initial token stream.
227 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
228     -> Result<Parser<'a>, Vec<Diagnostic>> {
229     let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
230     maybe_source_file_to_parser(sess, file)
231 }
232
233 /// Given a session, a crate config, a path, and a span, add
234 /// the file at the given path to the `source_map`, and returns a parser.
235 /// On an error, uses the given span as the source of the problem.
236 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
237                                     path: &Path,
238                                     directory_ownership: DirectoryOwnership,
239                                     module_name: Option<String>,
240                                     sp: Span) -> Parser<'a> {
241     let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
242     p.directory.ownership = directory_ownership;
243     p.root_module_name = module_name;
244     p
245 }
246
247 /// Given a `source_file` and config, returns a parser.
248 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
249     panictry_buffer!(&sess.span_diagnostic,
250                      maybe_source_file_to_parser(sess, source_file))
251 }
252
253 /// Given a `source_file` and config, return a parser. Returns any buffered errors from lexing the
254 /// initial token stream.
255 fn maybe_source_file_to_parser(
256     sess: &ParseSess,
257     source_file: Lrc<SourceFile>,
258 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
259     let end_pos = source_file.end_pos;
260     let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
261     let mut parser = stream_to_parser(sess, stream, None);
262     parser.unclosed_delims = unclosed_delims;
263     if parser.token == token::Eof && parser.token.span.is_dummy() {
264         parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt());
265     }
266
267     Ok(parser)
268 }
269
270 // Must preserve old name for now, because `quote!` from the *existing*
271 // compiler expands into it.
272 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
273     stream_to_parser(sess, tts.into_iter().collect(), crate::MACRO_ARGUMENTS)
274 }
275
276
277 // Base abstractions
278
279 /// Given a session and a path and an optional span (for error reporting),
280 /// add the path to the session's source_map and return the new source_file or
281 /// error when a file can't be read.
282 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
283                    -> Result<Lrc<SourceFile>, Diagnostic> {
284     sess.source_map().load_file(path)
285     .map_err(|e| {
286         let msg = format!("couldn't read {}: {}", path.display(), e);
287         let mut diag = Diagnostic::new(Level::Fatal, &msg);
288         if let Some(sp) = spanopt {
289             diag.set_span(sp);
290         }
291         diag
292     })
293 }
294
295 /// Given a session and a path and an optional span (for error reporting),
296 /// adds the path to the session's `source_map` and returns the new `source_file`.
297 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
298                    -> Lrc<SourceFile> {
299     match try_file_to_source_file(sess, path, spanopt) {
300         Ok(source_file) => source_file,
301         Err(d) => {
302             DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
303             FatalError.raise();
304         }
305     }
306 }
307
308 /// Given a `source_file`, produces a sequence of token trees.
309 pub fn source_file_to_stream(
310     sess: &ParseSess,
311     source_file: Lrc<SourceFile>,
312     override_span: Option<Span>,
313 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
314     panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
315 }
316
317 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
318 /// parsing the token stream.
319 pub fn maybe_file_to_stream(
320     sess: &ParseSess,
321     source_file: Lrc<SourceFile>,
322     override_span: Option<Span>,
323 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
324     let srdr = lexer::StringReader::new(sess, source_file, override_span);
325     let (token_trees, unmatched_braces) = srdr.into_token_trees();
326
327     match token_trees {
328         Ok(stream) => Ok((stream, unmatched_braces)),
329         Err(err) => {
330             let mut buffer = Vec::with_capacity(1);
331             err.buffer(&mut buffer);
332             // Not using `emit_unclosed_delims` to use `db.buffer`
333             for unmatched in unmatched_braces {
334                 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
335                     "incorrect close delimiter: `{}`",
336                     pprust::token_kind_to_string(&token::CloseDelim(unmatched.found_delim)),
337                 ));
338                 db.span_label(unmatched.found_span, "incorrect close delimiter");
339                 if let Some(sp) = unmatched.candidate_span {
340                     db.span_label(sp, "close delimiter possibly meant for this");
341                 }
342                 if let Some(sp) = unmatched.unclosed_span {
343                     db.span_label(sp, "un-closed delimiter");
344                 }
345                 db.buffer(&mut buffer);
346             }
347             Err(buffer)
348         }
349     }
350 }
351
352 /// Given a stream and the `ParseSess`, produces a parser.
353 pub fn stream_to_parser<'a>(
354     sess: &'a ParseSess,
355     stream: TokenStream,
356     subparser_name: Option<&'static str>,
357 ) -> Parser<'a> {
358     Parser::new(sess, stream, None, true, false, subparser_name)
359 }
360
361 /// Given a stream, the `ParseSess` and the base directory, produces a parser.
362 ///
363 /// Use this function when you are creating a parser from the token stream
364 /// and also care about the current working directory of the parser (e.g.,
365 /// you are trying to resolve modules defined inside a macro invocation).
366 ///
367 /// # Note
368 ///
369 /// The main usage of this function is outside of rustc, for those who uses
370 /// libsyntax as a library. Please do not remove this function while refactoring
371 /// just because it is not used in rustc codebase!
372 pub fn stream_to_parser_with_base_dir<'a>(
373     sess: &'a ParseSess,
374     stream: TokenStream,
375     base_dir: Directory<'a>,
376 ) -> Parser<'a> {
377     Parser::new(sess, stream, Some(base_dir), true, false, None)
378 }
379
380 /// A sequence separator.
381 pub struct SeqSep {
382     /// The separator token.
383     pub sep: Option<TokenKind>,
384     /// `true` if a trailing separator is allowed.
385     pub trailing_sep_allowed: bool,
386 }
387
388 impl SeqSep {
389     pub fn trailing_allowed(t: TokenKind) -> SeqSep {
390         SeqSep {
391             sep: Some(t),
392             trailing_sep_allowed: true,
393         }
394     }
395
396     pub fn none() -> SeqSep {
397         SeqSep {
398             sep: None,
399             trailing_sep_allowed: false,
400         }
401     }
402 }