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::sync::{Lrc, Lock, Once};
17 use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
18 use syntax_pos::edition::Edition;
19 use syntax_pos::hygiene::ExpnId;
21 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
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(ColorConfig::Auto,
88 ParseSess::with_span_handler(handler, cm)
91 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
93 span_diagnostic: handler,
94 unstable_features: UnstableFeatures::from_environment(),
95 config: FxHashSet::default(),
96 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
97 raw_identifier_spans: Lock::new(Vec::new()),
98 registered_diagnostics: Lock::new(ErrorMap::new()),
99 included_mod_stack: Lock::new(vec![]),
101 buffered_lints: Lock::new(vec![]),
102 edition: ExpnId::root().expn_data().edition,
103 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
104 injected_crate_name: Once::new(),
105 gated_spans: GatedSpans::default(),
110 pub fn source_map(&self) -> &SourceMap {
114 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
115 lint_id: BufferedEarlyLintId,
120 self.buffered_lints.with_lock(|buffered_lints| {
121 buffered_lints.push(BufferedEarlyLint{
130 /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
131 /// parser to continue parsing the following operation as part of the same expression.
132 pub fn expr_parentheses_needed(
134 err: &mut DiagnosticBuilder<'_>,
136 alt_snippet: Option<String>,
138 if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
141 "parentheses are required to parse this as an expression",
142 format!("({})", snippet),
143 Applicability::MachineApplicable,
150 pub struct Directory<'a> {
151 pub path: Cow<'a, Path>,
152 pub ownership: DirectoryOwnership,
155 #[derive(Copy, Clone)]
156 pub enum DirectoryOwnership {
158 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
159 relative: Option<ast::Ident>,
162 UnownedViaMod(bool /* legacy warnings? */),
165 // a bunch of utility functions of the form parse_<thing>_from_<source>
166 // where <thing> includes crate, expr, item, stmt, tts, and one that
167 // uses a HOF to parse anything, and <source> includes file and
170 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
171 let mut parser = new_parser_from_file(sess, input);
172 parser.parse_crate_mod()
175 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
176 -> PResult<'a, Vec<ast::Attribute>> {
177 let mut parser = new_parser_from_file(sess, input);
178 parser.parse_inner_attributes()
181 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
182 -> PResult<'_, ast::Crate> {
183 new_parser_from_source_str(sess, name, source).parse_crate_mod()
186 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
187 -> PResult<'_, Vec<ast::Attribute>> {
188 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
191 pub fn parse_stream_from_source_str(
195 override_span: Option<Span>,
197 let (stream, mut errors) = source_file_to_stream(
199 sess.source_map().new_source_file(name, source),
202 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
206 /// Creates a new parser from a source string.
207 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
208 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
211 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
213 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
214 -> Result<Parser<'_>, Vec<Diagnostic>>
216 let mut parser = maybe_source_file_to_parser(sess,
217 sess.source_map().new_source_file(name, source))?;
218 parser.recurse_into_file_modules = false;
222 /// Creates a new parser, handling errors as appropriate
223 /// if the file doesn't exist
224 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
225 source_file_to_parser(sess, file_to_source_file(sess, path, None))
228 /// Creates a new parser, returning buffered diagnostics if the file doesn't
229 /// exist or from lexing the initial token stream.
230 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
231 -> Result<Parser<'a>, Vec<Diagnostic>> {
232 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
233 maybe_source_file_to_parser(sess, file)
236 /// Given a session, a crate config, a path, and a span, add
237 /// the file at the given path to the source_map, and return a parser.
238 /// On an error, use the given span as the source of the problem.
239 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
241 directory_ownership: DirectoryOwnership,
242 module_name: Option<String>,
243 sp: Span) -> Parser<'a> {
244 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
245 p.directory.ownership = directory_ownership;
246 p.root_module_name = module_name;
250 /// Given a source_file and config, return a parser
251 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
252 panictry_buffer!(&sess.span_diagnostic,
253 maybe_source_file_to_parser(sess, source_file))
256 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
257 /// initial token stream.
258 fn maybe_source_file_to_parser(
260 source_file: Lrc<SourceFile>,
261 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
262 let end_pos = source_file.end_pos;
263 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
264 let mut parser = stream_to_parser(sess, stream, None);
265 parser.unclosed_delims = unclosed_delims;
266 if parser.token == token::Eof && parser.token.span.is_dummy() {
267 parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt());
273 // must preserve old name for now, because quote! from the *existing*
274 // compiler expands into it
275 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
276 stream_to_parser(sess, tts.into_iter().collect(), crate::MACRO_ARGUMENTS)
282 /// Given a session and a path and an optional span (for error reporting),
283 /// add the path to the session's source_map and return the new source_file or
284 /// error when a file can't be read.
285 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
286 -> Result<Lrc<SourceFile>, Diagnostic> {
287 sess.source_map().load_file(path)
289 let msg = format!("couldn't read {}: {}", path.display(), e);
290 let mut diag = Diagnostic::new(Level::Fatal, &msg);
291 if let Some(sp) = spanopt {
298 /// Given a session and a path and an optional span (for error reporting),
299 /// add the path to the session's `source_map` and return the new `source_file`.
300 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
302 match try_file_to_source_file(sess, path, spanopt) {
303 Ok(source_file) => source_file,
305 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
311 /// Given a source_file, produces a sequence of token trees.
312 pub fn source_file_to_stream(
314 source_file: Lrc<SourceFile>,
315 override_span: Option<Span>,
316 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
317 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
320 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
321 /// parsing the token stream.
322 pub fn maybe_file_to_stream(
324 source_file: Lrc<SourceFile>,
325 override_span: Option<Span>,
326 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
327 let srdr = lexer::StringReader::new(sess, source_file, override_span);
328 let (token_trees, unmatched_braces) = srdr.into_token_trees();
331 Ok(stream) => Ok((stream, unmatched_braces)),
333 let mut buffer = Vec::with_capacity(1);
334 err.buffer(&mut buffer);
335 // Not using `emit_unclosed_delims` to use `db.buffer`
336 for unmatched in unmatched_braces {
337 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
338 "incorrect close delimiter: `{}`",
339 pprust::token_kind_to_string(&token::CloseDelim(unmatched.found_delim)),
341 db.span_label(unmatched.found_span, "incorrect close delimiter");
342 if let Some(sp) = unmatched.candidate_span {
343 db.span_label(sp, "close delimiter possibly meant for this");
345 if let Some(sp) = unmatched.unclosed_span {
346 db.span_label(sp, "un-closed delimiter");
348 db.buffer(&mut buffer);
355 /// Given stream and the `ParseSess`, produces a parser.
356 pub fn stream_to_parser<'a>(
359 subparser_name: Option<&'static str>,
361 Parser::new(sess, stream, None, true, false, subparser_name)
364 /// Given stream, the `ParseSess` and the base directory, produces a parser.
366 /// Use this function when you are creating a parser from the token stream
367 /// and also care about the current working directory of the parser (e.g.,
368 /// you are trying to resolve modules defined inside a macro invocation).
372 /// The main usage of this function is outside of rustc, for those who uses
373 /// libsyntax as a library. Please do not remove this function while refactoring
374 /// just because it is not used in rustc codebase!
375 pub fn stream_to_parser_with_base_dir<'a>(
378 base_dir: Directory<'a>,
380 Parser::new(sess, stream, Some(base_dir), true, false, None)
383 /// A sequence separator.
385 /// The separator token.
386 pub sep: Option<TokenKind>,
387 /// `true` if a trailing separator is allowed.
388 pub trailing_sep_allowed: bool,
392 pub fn trailing_allowed(t: TokenKind) -> SeqSep {
395 trailing_sep_allowed: true,
399 pub fn none() -> SeqSep {
402 trailing_sep_allowed: false,