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