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