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