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 #[cfg(target_arch = "x86_64")]
17 use rustc_data_structures::static_assert_size;
18 use rustc_data_structures::sync::{Lrc, Lock, Once};
19 use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
20 use syntax_pos::edition::Edition;
21 use syntax_pos::hygiene::ExpnId;
24 use std::path::{Path, PathBuf};
37 crate mod diagnostics;
39 crate mod unescape_error_reporting;
41 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
43 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
44 // (See also the comment on `DiagnosticBuilderInner`.)
45 #[cfg(target_arch = "x86_64")]
46 static_assert_size!(PResult<'_, bool>, 16);
48 /// Collected spans during parsing for places where a certain feature was
49 /// used and should be feature gated accordingly in `check_crate`.
51 pub struct GatedSpans {
52 /// Spans collected for gating `let_chains`, e.g. `if a && let b = c {}`.
53 pub let_chains: Lock<Vec<Span>>,
54 /// Spans collected for gating `async_closure`, e.g. `async || ..`.
55 pub async_closure: Lock<Vec<Span>>,
56 /// Spans collected for gating `yield e?` expressions (`generators` gate).
57 pub yields: Lock<Vec<Span>>,
58 /// Spans collected for gating `or_patterns`, e.g. `Some(Foo | Bar)`.
59 pub or_patterns: Lock<Vec<Span>>,
62 /// Info about a parsing session.
63 pub struct ParseSess {
64 pub span_diagnostic: Handler,
65 pub unstable_features: UnstableFeatures,
66 pub config: CrateConfig,
68 pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
69 /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
70 pub raw_identifier_spans: Lock<Vec<Span>>,
71 /// Used to determine and report recursive module inclusions.
72 included_mod_stack: Lock<Vec<PathBuf>>,
73 source_map: Lrc<SourceMap>,
74 pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
75 /// Contains the spans of block expressions that could have been incomplete based on the
76 /// operation token that followed it, but that the parser cannot identify without further
78 pub ambiguous_block_expr_parse: Lock<FxHashMap<Span, Span>>,
79 pub injected_crate_name: Once<Symbol>,
80 pub gated_spans: GatedSpans,
84 pub fn new(file_path_mapping: FilePathMapping) -> Self {
85 let cm = Lrc::new(SourceMap::new(file_path_mapping));
86 let handler = Handler::with_tty_emitter(
92 ParseSess::with_span_handler(handler, cm)
95 pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> Self {
97 span_diagnostic: handler,
98 unstable_features: UnstableFeatures::from_environment(),
99 config: FxHashSet::default(),
100 edition: ExpnId::root().expn_data().edition,
101 missing_fragment_specifiers: Lock::new(FxHashSet::default()),
102 raw_identifier_spans: Lock::new(Vec::new()),
103 included_mod_stack: Lock::new(vec![]),
105 buffered_lints: Lock::new(vec![]),
106 ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
107 injected_crate_name: Once::new(),
108 gated_spans: GatedSpans::default(),
113 pub fn source_map(&self) -> &SourceMap {
117 pub fn buffer_lint<S: Into<MultiSpan>>(&self,
118 lint_id: BufferedEarlyLintId,
123 self.buffered_lints.with_lock(|buffered_lints| {
124 buffered_lints.push(BufferedEarlyLint{
133 /// Extend an error with a suggestion to wrap an expression with parentheses to allow the
134 /// parser to continue parsing the following operation as part of the same expression.
135 pub fn expr_parentheses_needed(
137 err: &mut DiagnosticBuilder<'_>,
139 alt_snippet: Option<String>,
141 if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
144 "parentheses are required to parse this as an expression",
145 format!("({})", snippet),
146 Applicability::MachineApplicable,
153 pub struct Directory<'a> {
154 pub path: Cow<'a, Path>,
155 pub ownership: DirectoryOwnership,
158 #[derive(Copy, Clone)]
159 pub enum DirectoryOwnership {
161 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`.
162 relative: Option<ast::Ident>,
165 UnownedViaMod(bool /* legacy warnings? */),
168 // A bunch of utility functions of the form `parse_<thing>_from_<source>`
169 // where <thing> includes crate, expr, item, stmt, tts, and one that
170 // uses a HOF to parse anything, and <source> includes file and
173 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
174 let mut parser = new_parser_from_file(sess, input);
175 parser.parse_crate_mod()
178 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
179 -> PResult<'a, Vec<ast::Attribute>> {
180 let mut parser = new_parser_from_file(sess, input);
181 parser.parse_inner_attributes()
184 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
185 -> PResult<'_, ast::Crate> {
186 new_parser_from_source_str(sess, name, source).parse_crate_mod()
189 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
190 -> PResult<'_, Vec<ast::Attribute>> {
191 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
194 pub fn parse_stream_from_source_str(
198 override_span: Option<Span>,
200 let (stream, mut errors) = source_file_to_stream(
202 sess.source_map().new_source_file(name, source),
205 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
209 /// Creates a new parser from a source string.
210 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
211 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
214 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
216 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
217 -> Result<Parser<'_>, Vec<Diagnostic>>
219 let mut parser = maybe_source_file_to_parser(sess,
220 sess.source_map().new_source_file(name, source))?;
221 parser.recurse_into_file_modules = false;
225 /// Creates a new parser, handling errors as appropriate if the file doesn't exist.
226 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
227 source_file_to_parser(sess, file_to_source_file(sess, path, None))
230 /// Creates a new parser, returning buffered diagnostics if the file doesn't exist,
231 /// or from lexing the initial token stream.
232 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
233 -> Result<Parser<'a>, Vec<Diagnostic>> {
234 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
235 maybe_source_file_to_parser(sess, file)
238 /// Given a session, a crate config, a path, and a span, add
239 /// the file at the given path to the `source_map`, and returns a parser.
240 /// On an error, uses the given span as the source of the problem.
241 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
243 directory_ownership: DirectoryOwnership,
244 module_name: Option<String>,
245 sp: Span) -> Parser<'a> {
246 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
247 p.directory.ownership = directory_ownership;
248 p.root_module_name = module_name;
252 /// Given a `source_file` and config, returns a parser.
253 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
254 panictry_buffer!(&sess.span_diagnostic,
255 maybe_source_file_to_parser(sess, source_file))
258 /// Given a `source_file` and config, return a parser. Returns any buffered errors from lexing the
259 /// initial token stream.
260 fn maybe_source_file_to_parser(
262 source_file: Lrc<SourceFile>,
263 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
264 let end_pos = source_file.end_pos;
265 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
266 let mut parser = stream_to_parser(sess, stream, None);
267 parser.unclosed_delims = unclosed_delims;
268 if parser.token == token::Eof && parser.token.span.is_dummy() {
269 parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt());
275 // Must preserve old name for now, because `quote!` from the *existing*
276 // compiler expands into it.
277 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
278 stream_to_parser(sess, tts.into_iter().collect(), crate::MACRO_ARGUMENTS)
284 /// Given a session and a path and an optional span (for error reporting),
285 /// add the path to the session's source_map and return the new source_file or
286 /// error when a file can't be read.
287 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
288 -> Result<Lrc<SourceFile>, Diagnostic> {
289 sess.source_map().load_file(path)
291 let msg = format!("couldn't read {}: {}", path.display(), e);
292 let mut diag = Diagnostic::new(Level::Fatal, &msg);
293 if let Some(sp) = spanopt {
300 /// Given a session and a path and an optional span (for error reporting),
301 /// adds the path to the session's `source_map` and returns the new `source_file`.
302 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
304 match try_file_to_source_file(sess, path, spanopt) {
305 Ok(source_file) => source_file,
307 sess.span_diagnostic.emit_diagnostic(&d);
313 /// Given a `source_file`, produces a sequence of token trees.
314 pub fn source_file_to_stream(
316 source_file: Lrc<SourceFile>,
317 override_span: Option<Span>,
318 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
319 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
322 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
323 /// parsing the token stream.
324 pub fn maybe_file_to_stream(
326 source_file: Lrc<SourceFile>,
327 override_span: Option<Span>,
328 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
329 let srdr = lexer::StringReader::new(sess, source_file, override_span);
330 let (token_trees, unmatched_braces) = srdr.into_token_trees();
333 Ok(stream) => Ok((stream, unmatched_braces)),
335 let mut buffer = Vec::with_capacity(1);
336 err.buffer(&mut buffer);
337 // Not using `emit_unclosed_delims` to use `db.buffer`
338 for unmatched in unmatched_braces {
339 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
340 "incorrect close delimiter: `{}`",
341 pprust::token_kind_to_string(&token::CloseDelim(unmatched.found_delim)),
343 db.span_label(unmatched.found_span, "incorrect close delimiter");
344 if let Some(sp) = unmatched.candidate_span {
345 db.span_label(sp, "close delimiter possibly meant for this");
347 if let Some(sp) = unmatched.unclosed_span {
348 db.span_label(sp, "un-closed delimiter");
350 db.buffer(&mut buffer);
357 /// Given a stream and the `ParseSess`, produces a parser.
358 pub fn stream_to_parser<'a>(
361 subparser_name: Option<&'static str>,
363 Parser::new(sess, stream, None, true, false, subparser_name)
366 /// Given a stream, the `ParseSess` and the base directory, produces a parser.
368 /// Use this function when you are creating a parser from the token stream
369 /// and also care about the current working directory of the parser (e.g.,
370 /// you are trying to resolve modules defined inside a macro invocation).
374 /// The main usage of this function is outside of rustc, for those who uses
375 /// libsyntax as a library. Please do not remove this function while refactoring
376 /// just because it is not used in rustc codebase!
377 pub fn stream_to_parser_with_base_dir<'a>(
380 base_dir: Directory<'a>,
382 Parser::new(sess, stream, Some(base_dir), true, false, None)
385 /// A sequence separator.
387 /// The separator token.
388 pub sep: Option<TokenKind>,
389 /// `true` if a trailing separator is allowed.
390 pub trailing_sep_allowed: bool,
394 pub fn trailing_allowed(t: TokenKind) -> SeqSep {
397 trailing_sep_allowed: true,
401 pub fn none() -> SeqSep {
404 trailing_sep_allowed: false,