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 /// Info about a parsing session.
43 pub struct ParseSess {
44 pub span_diagnostic: Handler,
45 pub unstable_features: UnstableFeatures,
46 pub config: CrateConfig,
48 pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
49 /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
50 pub raw_identifier_spans: Lock<Vec<Span>>,
51 /// The registered diagnostics codes.
52 crate registered_diagnostics: Lock<ErrorMap>,
53 /// Used to determine and report recursive module inclusions.
54 included_mod_stack: Lock<Vec<PathBuf>>,
55 source_map: Lrc<SourceMap>,
56 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
57 /// Contains the spans of block expressions that could have been incomplete based on the
58 /// operation token that followed it, but that the parser cannot identify without further
60 pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
61 pub param_attr_spans: Lock<Vec<Span>>,
62 // Places where `let` exprs were used and should be feature gated according to `let_chains`.
63 pub let_chains_spans: Lock<Vec<Span>>,
64 // Places where `async || ..` exprs were used and should be feature gated.
65 pub async_closure_spans: Lock<Vec<Span>>,
66 pub injected_crate_name: Once<Symbol>,
70 pub fn new(file_path_mapping: FilePathMapping) -> Self {
71 let cm = Lrc::new(SourceMap::new(file_path_mapping));
72 let handler = Handler::with_tty_emitter(ColorConfig::Auto,
76 ParseSess::with_span_handler(handler, cm)
79 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
81 span_diagnostic: handler,
82 unstable_features: UnstableFeatures::from_environment(),
83 config: FxHashSet::default(),
84 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
85 raw_identifier_spans: Lock::new(Vec::new()),
86 registered_diagnostics: Lock::new(ErrorMap::new()),
87 included_mod_stack: Lock::new(vec![]),
89 buffered_lints: Lock::new(vec![]),
90 edition: ExpnId::root().expn_data().edition,
91 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
92 param_attr_spans: Lock::new(Vec::new()),
93 let_chains_spans: Lock::new(Vec::new()),
94 async_closure_spans: Lock::new(Vec::new()),
95 injected_crate_name: Once::new(),
100 pub fn source_map(&self) -> &SourceMap {
104 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
105 lint_id: BufferedEarlyLintId,
110 self.buffered_lints.with_lock(|buffered_lints| {
111 buffered_lints.push(BufferedEarlyLint{
120 /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
121 /// parser to continue parsing the following operation as part of the same expression.
122 pub fn expr_parentheses_needed(
124 err: &mut DiagnosticBuilder<'_>,
126 alt_snippet: Option<String>,
128 if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
131 "parentheses are required to parse this as an expression",
132 format!("({})", snippet),
133 Applicability::MachineApplicable,
140 pub struct Directory<'a> {
141 pub path: Cow<'a, Path>,
142 pub ownership: DirectoryOwnership,
145 #[derive(Copy, Clone)]
146 pub enum DirectoryOwnership {
148 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`
149 relative: Option<ast::Ident>,
152 UnownedViaMod(bool /* legacy warnings? */),
155 // a bunch of utility functions of the form parse_<thing>_from_<source>
156 // where <thing> includes crate, expr, item, stmt, tts, and one that
157 // uses a HOF to parse anything, and <source> includes file and
160 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
161 let mut parser = new_parser_from_file(sess, input);
162 parser.parse_crate_mod()
165 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
166 -> PResult<'a, Vec<ast::Attribute>> {
167 let mut parser = new_parser_from_file(sess, input);
168 parser.parse_inner_attributes()
171 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
172 -> PResult<'_, ast::Crate> {
173 new_parser_from_source_str(sess, name, source).parse_crate_mod()
176 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
177 -> PResult<'_, Vec<ast::Attribute>> {
178 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
181 pub fn parse_stream_from_source_str(
185 override_span: Option<Span>,
187 let (stream, mut errors) = source_file_to_stream(
189 sess.source_map().new_source_file(name, source),
192 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
196 /// Creates a new parser from a source string.
197 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
198 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
201 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
203 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
204 -> Result<Parser<'_>, Vec<Diagnostic>>
206 let mut parser = maybe_source_file_to_parser(sess,
207 sess.source_map().new_source_file(name, source))?;
208 parser.recurse_into_file_modules = false;
212 /// Creates a new parser, handling errors as appropriate
213 /// if the file doesn't exist
214 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
215 source_file_to_parser(sess, file_to_source_file(sess, path, None))
218 /// Creates a new parser, returning buffered diagnostics if the file doesn't
219 /// exist or from lexing the initial token stream.
220 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
221 -> Result<Parser<'a>, Vec<Diagnostic>> {
222 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
223 maybe_source_file_to_parser(sess, file)
226 /// Given a session, a crate config, a path, and a span, add
227 /// the file at the given path to the source_map, and return a parser.
228 /// On an error, use the given span as the source of the problem.
229 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
231 directory_ownership: DirectoryOwnership,
232 module_name: Option<String>,
233 sp: Span) -> Parser<'a> {
234 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
235 p.directory.ownership = directory_ownership;
236 p.root_module_name = module_name;
240 /// Given a source_file and config, return a parser
241 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
242 panictry_buffer!(&sess.span_diagnostic,
243 maybe_source_file_to_parser(sess, source_file))
246 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
247 /// initial token stream.
248 fn maybe_source_file_to_parser(
250 source_file: Lrc<SourceFile>,
251 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
252 let end_pos = source_file.end_pos;
253 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
254 let mut parser = stream_to_parser(sess, stream, None);
255 parser.unclosed_delims = unclosed_delims;
256 if parser.token == token::Eof && parser.token.span.is_dummy() {
257 parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt());
263 // must preserve old name for now, because quote! from the *existing*
264 // compiler expands into it
265 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
266 stream_to_parser(sess, tts.into_iter().collect(), crate::MACRO_ARGUMENTS)
272 /// Given a session and a path and an optional span (for error reporting),
273 /// add the path to the session's source_map and return the new source_file or
274 /// error when a file can't be read.
275 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
276 -> Result<Lrc<SourceFile>, Diagnostic> {
277 sess.source_map().load_file(path)
279 let msg = format!("couldn't read {}: {}", path.display(), e);
280 let mut diag = Diagnostic::new(Level::Fatal, &msg);
281 if let Some(sp) = spanopt {
288 /// Given a session and a path and an optional span (for error reporting),
289 /// add the path to the session's `source_map` and return the new `source_file`.
290 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
292 match try_file_to_source_file(sess, path, spanopt) {
293 Ok(source_file) => source_file,
295 DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
301 /// Given a source_file, produces a sequence of token trees.
302 pub fn source_file_to_stream(
304 source_file: Lrc<SourceFile>,
305 override_span: Option<Span>,
306 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
307 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
310 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
311 /// parsing the token stream.
312 pub fn maybe_file_to_stream(
314 source_file: Lrc<SourceFile>,
315 override_span: Option<Span>,
316 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
317 let srdr = lexer::StringReader::new(sess, source_file, override_span);
318 let (token_trees, unmatched_braces) = srdr.into_token_trees();
321 Ok(stream) => Ok((stream, unmatched_braces)),
323 let mut buffer = Vec::with_capacity(1);
324 err.buffer(&mut buffer);
325 // Not using `emit_unclosed_delims` to use `db.buffer`
326 for unmatched in unmatched_braces {
327 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
328 "incorrect close delimiter: `{}`",
329 pprust::token_kind_to_string(&token::CloseDelim(unmatched.found_delim)),
331 db.span_label(unmatched.found_span, "incorrect close delimiter");
332 if let Some(sp) = unmatched.candidate_span {
333 db.span_label(sp, "close delimiter possibly meant for this");
335 if let Some(sp) = unmatched.unclosed_span {
336 db.span_label(sp, "un-closed delimiter");
338 db.buffer(&mut buffer);
345 /// Given stream and the `ParseSess`, produces a parser.
346 pub fn stream_to_parser<'a>(
349 subparser_name: Option<&'static str>,
351 Parser::new(sess, stream, None, true, false, subparser_name)
354 /// Given stream, the `ParseSess` and the base directory, produces a parser.
356 /// Use this function when you are creating a parser from the token stream
357 /// and also care about the current working directory of the parser (e.g.,
358 /// you are trying to resolve modules defined inside a macro invocation).
362 /// The main usage of this function is outside of rustc, for those who uses
363 /// libsyntax as a library. Please do not remove this function while refactoring
364 /// just because it is not used in rustc codebase!
365 pub fn stream_to_parser_with_base_dir<'a>(
368 base_dir: Directory<'a>,
370 Parser::new(sess, stream, Some(base_dir), true, false, None)
373 /// A sequence separator.
375 /// The separator token.
376 pub sep: Option<TokenKind>,
377 /// `true` if a trailing separator is allowed.
378 pub trailing_sep_allowed: bool,
382 pub fn trailing_allowed(t: TokenKind) -> SeqSep {
385 trailing_sep_allowed: true,
389 pub fn none() -> SeqSep {
392 trailing_sep_allowed: false,