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