1 //! The main parser interface.
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;
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;
23 use std::path::{Path, PathBuf};
36 crate mod diagnostics;
38 crate mod unescape_error_reporting;
40 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
42 /// Collected spans during parsing for places where a certain feature was
43 /// used and should be feature gated accordingly in `check_crate`.
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>>,
58 /// Info about a parsing session.
59 pub struct ParseSess {
60 pub span_diagnostic: Handler,
61 pub unstable_features: UnstableFeatures,
62 pub config: CrateConfig,
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
76 pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
77 pub injected_crate_name: Once<Symbol>,
78 pub gated_spans: GatedSpans,
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(
90 ParseSess::with_span_handler(handler, cm)
93 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> 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![]),
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(),
112 pub fn source_map(&self) -> &SourceMap {
116 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
117 lint_id: BufferedEarlyLintId,
122 self.buffered_lints.with_lock(|buffered_lints| {
123 buffered_lints.push(BufferedEarlyLint{
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(
136 err: &mut DiagnosticBuilder<'_>,
138 alt_snippet: Option<String>,
140 if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
143 "parentheses are required to parse this as an expression",
144 format!("({})", snippet),
145 Applicability::MachineApplicable,
152 pub struct Directory<'a> {
153 pub path: Cow<'a, Path>,
154 pub ownership: DirectoryOwnership,
157 #[derive(Copy, Clone)]
158 pub enum DirectoryOwnership {
160 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`.
161 relative: Option<ast::Ident>,
164 UnownedViaMod(bool /* legacy warnings? */),
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
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()
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()
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()
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()
193 pub fn parse_stream_from_source_str(
197 override_span: Option<Span>,
199 let (stream, mut errors) = source_file_to_stream(
201 sess.source_map().new_source_file(name, source),
204 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
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))
213 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
215 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
216 -> Result<Parser<'_>, Vec<Diagnostic>>
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;
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))
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)
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,
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;
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))
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(
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());
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)
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)
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 {
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>)
303 match try_file_to_source_file(sess, path, spanopt) {
304 Ok(source_file) => source_file,
306 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
312 /// Given a `source_file`, produces a sequence of token trees.
313 pub fn source_file_to_stream(
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))
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(
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();
332 Ok(stream) => Ok((stream, unmatched_braces)),
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)),
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");
346 if let Some(sp) = unmatched.unclosed_span {
347 db.span_label(sp, "un-closed delimiter");
349 db.buffer(&mut buffer);
356 /// Given a stream and the `ParseSess`, produces a parser.
357 pub fn stream_to_parser<'a>(
360 subparser_name: Option<&'static str>,
362 Parser::new(sess, stream, None, true, false, subparser_name)
365 /// Given a stream, the `ParseSess` and the base directory, produces a parser.
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).
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>(
379 base_dir: Directory<'a>,
381 Parser::new(sess, stream, Some(base_dir), true, false, None)
384 /// A sequence separator.
386 /// The separator token.
387 pub sep: Option<TokenKind>,
388 /// `true` if a trailing separator is allowed.
389 pub trailing_sep_allowed: bool,
393 pub fn trailing_allowed(t: TokenKind) -> SeqSep {
396 trailing_sep_allowed: true,
400 pub fn none() -> SeqSep {
403 trailing_sep_allowed: false,