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