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::print::pprust;
12 use crate::symbol::Symbol;
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;
22 use std::path::{Path, PathBuf};
35 crate mod diagnostics;
37 crate mod unescape_error_reporting;
39 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
41 /// Collected spans during parsing for places where a certain feature was
42 /// used and should be feature gated accordingly in `check_crate`.
44 pub struct GatedSpans {
45 /// Spans collected for gating `param_attrs`, e.g. `fn foo(#[attr] x: u8) {}`.
46 pub param_attrs: Lock<Vec<Span>>,
47 /// Spans collected for gating `let_chains`, e.g. `if a && let b = c {}`.
48 pub let_chains: Lock<Vec<Span>>,
49 /// Spans collected for gating `async_closure`, e.g. `async || ..`.
50 pub async_closure: Lock<Vec<Span>>,
51 /// Spans collected for gating `yield e?` expressions (`generators` gate).
52 pub yields: Lock<Vec<Span>>,
53 /// Spans collected for gating `or_patterns`, e.g. `Some(Foo | Bar)`.
54 pub or_patterns: Lock<Vec<Span>>,
57 /// Info about a parsing session.
58 pub struct ParseSess {
59 pub span_diagnostic: Handler,
60 pub unstable_features: UnstableFeatures,
61 pub config: CrateConfig,
63 pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
64 /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
65 pub raw_identifier_spans: Lock<Vec<Span>>,
66 /// Used to determine and report recursive module inclusions.
67 included_mod_stack: Lock<Vec<PathBuf>>,
68 source_map: Lrc<SourceMap>,
69 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
70 /// Contains the spans of block expressions that could have been incomplete based on the
71 /// operation token that followed it, but that the parser cannot identify without further
73 pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
74 pub injected_crate_name: Once<Symbol>,
75 pub gated_spans: GatedSpans,
79 pub fn new(file_path_mapping: FilePathMapping) -> Self {
80 let cm = Lrc::new(SourceMap::new(file_path_mapping));
81 let handler = Handler::with_tty_emitter(
87 ParseSess::with_span_handler(handler, cm)
90 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> Self {
92 span_diagnostic: handler,
93 unstable_features: UnstableFeatures::from_environment(),
94 config: FxHashSet::default(),
95 edition: ExpnId::root().expn_data().edition,
96 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
97 raw_identifier_spans: Lock::new(Vec::new()),
98 included_mod_stack: Lock::new(vec![]),
100 buffered_lints: Lock::new(vec![]),
101 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
102 injected_crate_name: Once::new(),
103 gated_spans: GatedSpans::default(),
108 pub fn source_map(&self) -> &SourceMap {
112 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
113 lint_id: BufferedEarlyLintId,
118 self.buffered_lints.with_lock(|buffered_lints| {
119 buffered_lints.push(BufferedEarlyLint{
128 /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
129 /// parser to continue parsing the following operation as part of the same expression.
130 pub fn expr_parentheses_needed(
132 err: &mut DiagnosticBuilder<'_>,
134 alt_snippet: Option<String>,
136 if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
139 "parentheses are required to parse this as an expression",
140 format!("({})", snippet),
141 Applicability::MachineApplicable,
148 pub struct Directory<'a> {
149 pub path: Cow<'a, Path>,
150 pub ownership: DirectoryOwnership,
153 #[derive(Copy, Clone)]
154 pub enum DirectoryOwnership {
156 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`.
157 relative: Option<ast::Ident>,
160 UnownedViaMod(bool /* legacy warnings? */),
163 // A bunch of utility functions of the form `parse_<thing>_from_<source>`
164 // where <thing> includes crate, expr, item, stmt, tts, and one that
165 // uses a HOF to parse anything, and <source> includes file and
168 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
169 let mut parser = new_parser_from_file(sess, input);
170 parser.parse_crate_mod()
173 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
174 -> PResult<'a, Vec<ast::Attribute>> {
175 let mut parser = new_parser_from_file(sess, input);
176 parser.parse_inner_attributes()
179 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
180 -> PResult<'_, ast::Crate> {
181 new_parser_from_source_str(sess, name, source).parse_crate_mod()
184 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
185 -> PResult<'_, Vec<ast::Attribute>> {
186 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
189 pub fn parse_stream_from_source_str(
193 override_span: Option<Span>,
195 let (stream, mut errors) = source_file_to_stream(
197 sess.source_map().new_source_file(name, source),
200 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
204 /// Creates a new parser from a source string.
205 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
206 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
209 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
211 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
212 -> Result<Parser<'_>, Vec<Diagnostic>>
214 let mut parser = maybe_source_file_to_parser(sess,
215 sess.source_map().new_source_file(name, source))?;
216 parser.recurse_into_file_modules = false;
220 /// Creates a new parser, handling errors as appropriate if the file doesn't exist.
221 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
222 source_file_to_parser(sess, file_to_source_file(sess, path, None))
225 /// Creates a new parser, returning buffered diagnostics if the file doesn't exist,
226 /// or from lexing the initial token stream.
227 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
228 -> Result<Parser<'a>, Vec<Diagnostic>> {
229 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
230 maybe_source_file_to_parser(sess, file)
233 /// Given a session, a crate config, a path, and a span, add
234 /// the file at the given path to the `source_map`, and returns a parser.
235 /// On an error, uses the given span as the source of the problem.
236 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
238 directory_ownership: DirectoryOwnership,
239 module_name: Option<String>,
240 sp: Span) -> Parser<'a> {
241 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
242 p.directory.ownership = directory_ownership;
243 p.root_module_name = module_name;
247 /// Given a `source_file` and config, returns a parser.
248 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
249 panictry_buffer!(&sess.span_diagnostic,
250 maybe_source_file_to_parser(sess, source_file))
253 /// Given a `source_file` and config, return a parser. Returns any buffered errors from lexing the
254 /// initial token stream.
255 fn maybe_source_file_to_parser(
257 source_file: Lrc<SourceFile>,
258 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
259 let end_pos = source_file.end_pos;
260 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
261 let mut parser = stream_to_parser(sess, stream, None);
262 parser.unclosed_delims = unclosed_delims;
263 if parser.token == token::Eof && parser.token.span.is_dummy() {
264 parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt());
270 // Must preserve old name for now, because `quote!` from the *existing*
271 // compiler expands into it.
272 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
273 stream_to_parser(sess, tts.into_iter().collect(), crate::MACRO_ARGUMENTS)
279 /// Given a session and a path and an optional span (for error reporting),
280 /// add the path to the session's source_map and return the new source_file or
281 /// error when a file can't be read.
282 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
283 -> Result<Lrc<SourceFile>, Diagnostic> {
284 sess.source_map().load_file(path)
286 let msg = format!("couldn't read {}: {}", path.display(), e);
287 let mut diag = Diagnostic::new(Level::Fatal, &msg);
288 if let Some(sp) = spanopt {
295 /// Given a session and a path and an optional span (for error reporting),
296 /// adds the path to the session's `source_map` and returns the new `source_file`.
297 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
299 match try_file_to_source_file(sess, path, spanopt) {
300 Ok(source_file) => source_file,
302 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
308 /// Given a `source_file`, produces a sequence of token trees.
309 pub fn source_file_to_stream(
311 source_file: Lrc<SourceFile>,
312 override_span: Option<Span>,
313 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
314 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
317 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
318 /// parsing the token stream.
319 pub fn maybe_file_to_stream(
321 source_file: Lrc<SourceFile>,
322 override_span: Option<Span>,
323 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
324 let srdr = lexer::StringReader::new(sess, source_file, override_span);
325 let (token_trees, unmatched_braces) = srdr.into_token_trees();
328 Ok(stream) => Ok((stream, unmatched_braces)),
330 let mut buffer = Vec::with_capacity(1);
331 err.buffer(&mut buffer);
332 // Not using `emit_unclosed_delims` to use `db.buffer`
333 for unmatched in unmatched_braces {
334 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
335 "incorrect close delimiter: `{}`",
336 pprust::token_kind_to_string(&token::CloseDelim(unmatched.found_delim)),
338 db.span_label(unmatched.found_span, "incorrect close delimiter");
339 if let Some(sp) = unmatched.candidate_span {
340 db.span_label(sp, "close delimiter possibly meant for this");
342 if let Some(sp) = unmatched.unclosed_span {
343 db.span_label(sp, "un-closed delimiter");
345 db.buffer(&mut buffer);
352 /// Given a stream and the `ParseSess`, produces a parser.
353 pub fn stream_to_parser<'a>(
356 subparser_name: Option<&'static str>,
358 Parser::new(sess, stream, None, true, false, subparser_name)
361 /// Given a stream, the `ParseSess` and the base directory, produces a parser.
363 /// Use this function when you are creating a parser from the token stream
364 /// and also care about the current working directory of the parser (e.g.,
365 /// you are trying to resolve modules defined inside a macro invocation).
369 /// The main usage of this function is outside of rustc, for those who uses
370 /// libsyntax as a library. Please do not remove this function while refactoring
371 /// just because it is not used in rustc codebase!
372 pub fn stream_to_parser_with_base_dir<'a>(
375 base_dir: Directory<'a>,
377 Parser::new(sess, stream, Some(base_dir), true, false, None)
380 /// A sequence separator.
382 /// The separator token.
383 pub sep: Option<TokenKind>,
384 /// `true` if a trailing separator is allowed.
385 pub trailing_sep_allowed: bool,
389 pub fn trailing_allowed(t: TokenKind) -> SeqSep {
392 trailing_sep_allowed: true,
396 pub fn none() -> SeqSep {
399 trailing_sep_allowed: false,