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