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;
20 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
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 /// Info about a parsing session.
42 pub struct ParseSess {
43 pub span_diagnostic: Handler,
44 pub unstable_features: UnstableFeatures,
45 pub config: CrateConfig,
47 pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
48 /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
49 pub raw_identifier_spans: Lock<Vec<Span>>,
50 /// The registered diagnostics codes.
51 crate registered_diagnostics: Lock<ErrorMap>,
52 /// Used to determine and report recursive module inclusions.
53 included_mod_stack: Lock<Vec<PathBuf>>,
54 source_map: Lrc<SourceMap>,
55 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
56 /// Contains the spans of block expressions that could have been incomplete based on the
57 /// operation token that followed it, but that the parser cannot identify without further
59 pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
60 pub param_attr_spans: Lock<Vec<Span>>,
61 // Places where `let` exprs were used and should be feature gated according to `let_chains`.
62 pub let_chains_spans: Lock<Vec<Span>>,
63 // Places where `async || ..` exprs were used and should be feature gated.
64 pub async_closure_spans: Lock<Vec<Span>>,
65 pub injected_crate_name: Once<Symbol>,
69 pub fn new(file_path_mapping: FilePathMapping) -> Self {
70 let cm = Lrc::new(SourceMap::new(file_path_mapping));
71 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
75 ParseSess::with_span_handler(handler, cm)
78 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
80 span_diagnostic: handler,
81 unstable_features: UnstableFeatures::from_environment(),
82 config: FxHashSet::default(),
83 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
84 raw_identifier_spans: Lock::new(Vec::new()),
85 registered_diagnostics: Lock::new(ErrorMap::new()),
86 included_mod_stack: Lock::new(vec![]),
88 buffered_lints: Lock::new(vec![]),
89 edition: Edition::from_session(),
90 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
91 param_attr_spans: Lock::new(Vec::new()),
92 let_chains_spans: Lock::new(Vec::new()),
93 async_closure_spans: Lock::new(Vec::new()),
94 injected_crate_name: Once::new(),
99 pub fn source_map(&self) -> &SourceMap {
103 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
104 lint_id: BufferedEarlyLintId,
109 self.buffered_lints.with_lock(|buffered_lints| {
110 buffered_lints.push(BufferedEarlyLint{
119 /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
120 /// parser to continue parsing the following operation as part of the same expression.
121 pub fn expr_parentheses_needed(
123 err: &mut DiagnosticBuilder<'_>,
125 alt_snippet: Option<String>,
127 if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
130 "parentheses are required to parse this as an expression",
131 format!("({})", snippet),
132 Applicability::MachineApplicable,
139 pub struct Directory<'a> {
140 pub path: Cow<'a, Path>,
141 pub ownership: DirectoryOwnership,
144 #[derive(Copy, Clone)]
145 pub enum DirectoryOwnership {
147 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
148 relative: Option<ast::Ident>,
151 UnownedViaMod(bool /* legacy warnings? */),
154 // a bunch of utility functions of the form parse_<thing>_from_<source>
155 // where <thing> includes crate, expr, item, stmt, tts, and one that
156 // uses a HOF to parse anything, and <source> includes file and
159 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
160 let mut parser = new_parser_from_file(sess, input);
161 parser.parse_crate_mod()
164 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
165 -> PResult<'a, Vec<ast::Attribute>> {
166 let mut parser = new_parser_from_file(sess, input);
167 parser.parse_inner_attributes()
170 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
171 -> PResult<'_, ast::Crate> {
172 new_parser_from_source_str(sess, name, source).parse_crate_mod()
175 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
176 -> PResult<'_, Vec<ast::Attribute>> {
177 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
180 pub fn parse_stream_from_source_str(
184 override_span: Option<Span>,
186 let (stream, mut errors) = source_file_to_stream(
188 sess.source_map().new_source_file(name, source),
191 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
195 /// Creates a new parser from a source string.
196 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
197 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
200 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
202 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
203 -> Result<Parser<'_>, Vec<Diagnostic>>
205 let mut parser = maybe_source_file_to_parser(sess,
206 sess.source_map().new_source_file(name, source))?;
207 parser.recurse_into_file_modules = false;
211 /// Creates a new parser, handling errors as appropriate
212 /// if the file doesn't exist
213 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
214 source_file_to_parser(sess, file_to_source_file(sess, path, None))
217 /// Creates a new parser, returning buffered diagnostics if the file doesn't
218 /// exist or from lexing the initial token stream.
219 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
220 -> Result<Parser<'a>, Vec<Diagnostic>> {
221 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
222 maybe_source_file_to_parser(sess, file)
225 /// Given a session, a crate config, a path, and a span, add
226 /// the file at the given path to the source_map, and return a parser.
227 /// On an error, use the given span as the source of the problem.
228 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
230 directory_ownership: DirectoryOwnership,
231 module_name: Option<String>,
232 sp: Span) -> Parser<'a> {
233 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
234 p.directory.ownership = directory_ownership;
235 p.root_module_name = module_name;
239 /// Given a source_file and config, return a parser
240 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
241 panictry_buffer!(&sess.span_diagnostic,
242 maybe_source_file_to_parser(sess, source_file))
245 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
246 /// initial token stream.
247 fn maybe_source_file_to_parser(
249 source_file: Lrc<SourceFile>,
250 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
251 let end_pos = source_file.end_pos;
252 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
253 let mut parser = stream_to_parser(sess, stream, None);
254 parser.unclosed_delims = unclosed_delims;
255 if parser.token == token::Eof && parser.token.span.is_dummy() {
256 parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt());
262 // must preserve old name for now, because quote! from the *existing*
263 // compiler expands into it
264 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
265 stream_to_parser(sess, tts.into_iter().collect(), crate::MACRO_ARGUMENTS)
271 /// Given a session and a path and an optional span (for error reporting),
272 /// add the path to the session's source_map and return the new source_file or
273 /// error when a file can't be read.
274 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
275 -> Result<Lrc<SourceFile>, Diagnostic> {
276 sess.source_map().load_file(path)
278 let msg = format!("couldn't read {}: {}", path.display(), e);
279 let mut diag = Diagnostic::new(Level::Fatal, &msg);
280 if let Some(sp) = spanopt {
287 /// Given a session and a path and an optional span (for error reporting),
288 /// add the path to the session's `source_map` and return the new `source_file`.
289 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
291 match try_file_to_source_file(sess, path, spanopt) {
292 Ok(source_file) => source_file,
294 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
300 /// Given a source_file, produces a sequence of token trees.
301 pub fn source_file_to_stream(
303 source_file: Lrc<SourceFile>,
304 override_span: Option<Span>,
305 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
306 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
309 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
310 /// parsing the token stream.
311 pub fn maybe_file_to_stream(
313 source_file: Lrc<SourceFile>,
314 override_span: Option<Span>,
315 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
316 let srdr = lexer::StringReader::new(sess, source_file, override_span);
317 let (token_trees, unmatched_braces) = srdr.into_token_trees();
320 Ok(stream) => Ok((stream, unmatched_braces)),
322 let mut buffer = Vec::with_capacity(1);
323 err.buffer(&mut buffer);
324 // Not using `emit_unclosed_delims` to use `db.buffer`
325 for unmatched in unmatched_braces {
326 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
327 "incorrect close delimiter: `{}`",
328 pprust::token_kind_to_string(&token::CloseDelim(unmatched.found_delim)),
330 db.span_label(unmatched.found_span, "incorrect close delimiter");
331 if let Some(sp) = unmatched.candidate_span {
332 db.span_label(sp, "close delimiter possibly meant for this");
334 if let Some(sp) = unmatched.unclosed_span {
335 db.span_label(sp, "un-closed delimiter");
337 db.buffer(&mut buffer);
344 /// Given stream and the `ParseSess`, produces a parser.
345 pub fn stream_to_parser<'a>(
348 subparser_name: Option<&'static str>,
350 Parser::new(sess, stream, None, true, false, subparser_name)
353 /// Given stream, the `ParseSess` and the base directory, produces a parser.
355 /// Use this function when you are creating a parser from the token stream
356 /// and also care about the current working directory of the parser (e.g.,
357 /// you are trying to resolve modules defined inside a macro invocation).
361 /// The main usage of this function is outside of rustc, for those who uses
362 /// libsyntax as a library. Please do not remove this function while refactoring
363 /// just because it is not used in rustc codebase!
364 pub fn stream_to_parser_with_base_dir<'a>(
367 base_dir: Directory<'a>,
369 Parser::new(sess, stream, Some(base_dir), true, false, None)
372 /// A sequence separator.
374 /// The separator token.
375 pub sep: Option<TokenKind>,
376 /// `true` if a trailing separator is allowed.
377 pub trailing_sep_allowed: bool,
381 pub fn trailing_allowed(t: TokenKind) -> SeqSep {
384 trailing_sep_allowed: true,
388 pub fn none() -> SeqSep {
391 trailing_sep_allowed: false,