1 //! The main parser interface.
4 use crate::parse::parser::{Parser, emit_unclosed_delims};
5 use crate::parse::token::Nonterminal;
6 use crate::tokenstream::{self, TokenStream, TokenTree};
7 use crate::print::pprust;
8 use crate::sess::ParseSess;
10 use errors::{FatalError, Level, Diagnostic, DiagnosticBuilder};
11 #[cfg(target_arch = "x86_64")]
12 use rustc_data_structures::static_assert_size;
13 use rustc_data_structures::sync::Lrc;
14 use syntax_pos::{Span, SourceFile, FileName};
32 crate mod unescape_error_reporting;
34 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
36 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
37 // (See also the comment on `DiagnosticBuilderInner`.)
38 #[cfg(target_arch = "x86_64")]
39 static_assert_size!(PResult<'_, bool>, 16);
42 pub struct Directory<'a> {
43 pub path: Cow<'a, Path>,
44 pub ownership: DirectoryOwnership,
47 #[derive(Copy, Clone)]
48 pub enum DirectoryOwnership {
50 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`.
51 relative: Option<ast::Ident>,
54 UnownedViaMod(bool /* legacy warnings? */),
57 // A bunch of utility functions of the form `parse_<thing>_from_<source>`
58 // where <thing> includes crate, expr, item, stmt, tts, and one that
59 // uses a HOF to parse anything, and <source> includes file and
62 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
63 let mut parser = new_parser_from_file(sess, input);
64 parser.parse_crate_mod()
67 pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
68 -> PResult<'a, Vec<ast::Attribute>> {
69 let mut parser = new_parser_from_file(sess, input);
70 parser.parse_inner_attributes()
73 pub fn parse_crate_from_source_str(name: FileName, source: String, sess: &ParseSess)
74 -> PResult<'_, ast::Crate> {
75 new_parser_from_source_str(sess, name, source).parse_crate_mod()
78 pub fn parse_crate_attrs_from_source_str(name: FileName, source: String, sess: &ParseSess)
79 -> PResult<'_, Vec<ast::Attribute>> {
80 new_parser_from_source_str(sess, name, source).parse_inner_attributes()
83 pub fn parse_stream_from_source_str(
87 override_span: Option<Span>,
89 let (stream, mut errors) = source_file_to_stream(
91 sess.source_map().new_source_file(name, source),
94 emit_unclosed_delims(&mut errors, &sess.span_diagnostic);
98 /// Creates a new parser from a source string.
99 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
100 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
103 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
105 pub fn maybe_new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
106 -> Result<Parser<'_>, Vec<Diagnostic>>
108 let mut parser = maybe_source_file_to_parser(sess,
109 sess.source_map().new_source_file(name, source))?;
110 parser.recurse_into_file_modules = false;
114 /// Creates a new parser, handling errors as appropriate if the file doesn't exist.
115 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
116 source_file_to_parser(sess, file_to_source_file(sess, path, None))
119 /// Creates a new parser, returning buffered diagnostics if the file doesn't exist,
120 /// or from lexing the initial token stream.
121 pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
122 -> Result<Parser<'a>, Vec<Diagnostic>> {
123 let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
124 maybe_source_file_to_parser(sess, file)
127 /// Given a session, a crate config, a path, and a span, add
128 /// the file at the given path to the `source_map`, and returns a parser.
129 /// On an error, uses the given span as the source of the problem.
130 pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
132 directory_ownership: DirectoryOwnership,
133 module_name: Option<String>,
134 sp: Span) -> Parser<'a> {
135 let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
136 p.directory.ownership = directory_ownership;
137 p.root_module_name = module_name;
141 /// Given a `source_file` and config, returns a parser.
142 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
143 panictry_buffer!(&sess.span_diagnostic,
144 maybe_source_file_to_parser(sess, source_file))
147 /// Given a `source_file` and config, return a parser. Returns any buffered errors from lexing the
148 /// initial token stream.
149 fn maybe_source_file_to_parser(
151 source_file: Lrc<SourceFile>,
152 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
153 let end_pos = source_file.end_pos;
154 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
155 let mut parser = stream_to_parser(sess, stream, None);
156 parser.unclosed_delims = unclosed_delims;
157 if parser.token == token::Eof && parser.token.span.is_dummy() {
158 parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt());
164 // Must preserve old name for now, because `quote!` from the *existing*
165 // compiler expands into it.
166 pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser<'_> {
167 stream_to_parser(sess, tts.into_iter().collect(), crate::MACRO_ARGUMENTS)
173 /// Given a session and a path and an optional span (for error reporting),
174 /// add the path to the session's source_map and return the new source_file or
175 /// error when a file can't be read.
176 fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
177 -> Result<Lrc<SourceFile>, Diagnostic> {
178 sess.source_map().load_file(path)
180 let msg = format!("couldn't read {}: {}", path.display(), e);
181 let mut diag = Diagnostic::new(Level::Fatal, &msg);
182 if let Some(sp) = spanopt {
189 /// Given a session and a path and an optional span (for error reporting),
190 /// adds the path to the session's `source_map` and returns the new `source_file`.
191 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
193 match try_file_to_source_file(sess, path, spanopt) {
194 Ok(source_file) => source_file,
196 sess.span_diagnostic.emit_diagnostic(&d);
202 /// Given a `source_file`, produces a sequence of token trees.
203 pub fn source_file_to_stream(
205 source_file: Lrc<SourceFile>,
206 override_span: Option<Span>,
207 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
208 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
211 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
212 /// parsing the token stream.
213 pub fn maybe_file_to_stream(
215 source_file: Lrc<SourceFile>,
216 override_span: Option<Span>,
217 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
218 let srdr = lexer::StringReader::new(sess, source_file, override_span);
219 let (token_trees, unmatched_braces) = srdr.into_token_trees();
222 Ok(stream) => Ok((stream, unmatched_braces)),
224 let mut buffer = Vec::with_capacity(1);
225 err.buffer(&mut buffer);
226 // Not using `emit_unclosed_delims` to use `db.buffer`
227 for unmatched in unmatched_braces {
228 let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
229 "incorrect close delimiter: `{}`",
230 pprust::token_kind_to_string(&token::CloseDelim(unmatched.found_delim)),
232 db.span_label(unmatched.found_span, "incorrect close delimiter");
233 if let Some(sp) = unmatched.candidate_span {
234 db.span_label(sp, "close delimiter possibly meant for this");
236 if let Some(sp) = unmatched.unclosed_span {
237 db.span_label(sp, "un-closed delimiter");
239 db.buffer(&mut buffer);
246 /// Given a stream and the `ParseSess`, produces a parser.
247 pub fn stream_to_parser<'a>(
250 subparser_name: Option<&'static str>,
252 Parser::new(sess, stream, None, true, false, subparser_name)
255 /// Given a stream, the `ParseSess` and the base directory, produces a parser.
257 /// Use this function when you are creating a parser from the token stream
258 /// and also care about the current working directory of the parser (e.g.,
259 /// you are trying to resolve modules defined inside a macro invocation).
263 /// The main usage of this function is outside of rustc, for those who uses
264 /// libsyntax as a library. Please do not remove this function while refactoring
265 /// just because it is not used in rustc codebase!
266 pub fn stream_to_parser_with_base_dir<'a>(
269 base_dir: Directory<'a>,
271 Parser::new(sess, stream, Some(base_dir), true, false, None)
274 // NOTE(Centril): The following probably shouldn't be here but it acknowledges the
275 // fact that architecturally, we are using parsing (read on below to understand why).
277 pub fn nt_to_tokenstream(nt: &Nonterminal, sess: &ParseSess, span: Span) -> TokenStream {
278 // A `Nonterminal` is often a parsed AST item. At this point we now
279 // need to convert the parsed AST to an actual token stream, e.g.
280 // un-parse it basically.
282 // Unfortunately there's not really a great way to do that in a
283 // guaranteed lossless fashion right now. The fallback here is to just
284 // stringify the AST node and reparse it, but this loses all span
287 // As a result, some AST nodes are annotated with the token stream they
288 // came from. Here we attempt to extract these lossless token streams
289 // before we fall back to the stringification.
290 let tokens = match *nt {
291 Nonterminal::NtItem(ref item) => {
292 prepend_attrs(sess, &item.attrs, item.tokens.as_ref(), span)
294 Nonterminal::NtTraitItem(ref item) => {
295 prepend_attrs(sess, &item.attrs, item.tokens.as_ref(), span)
297 Nonterminal::NtImplItem(ref item) => {
298 prepend_attrs(sess, &item.attrs, item.tokens.as_ref(), span)
300 Nonterminal::NtIdent(ident, is_raw) => {
301 Some(tokenstream::TokenTree::token(token::Ident(ident.name, is_raw), ident.span).into())
303 Nonterminal::NtLifetime(ident) => {
304 Some(tokenstream::TokenTree::token(token::Lifetime(ident.name), ident.span).into())
306 Nonterminal::NtTT(ref tt) => {
307 Some(tt.clone().into())
312 // FIXME(#43081): Avoid this pretty-print + reparse hack
313 let source = pprust::nonterminal_to_string(nt);
314 let filename = FileName::macro_expansion_source_code(&source);
315 let tokens_for_real = parse_stream_from_source_str(filename, source, sess, Some(span));
317 // During early phases of the compiler the AST could get modified
318 // directly (e.g., attributes added or removed) and the internal cache
319 // of tokens my not be invalidated or updated. Consequently if the
320 // "lossless" token stream disagrees with our actual stringification
321 // (which has historically been much more battle-tested) then we go
322 // with the lossy stream anyway (losing span information).
324 // Note that the comparison isn't `==` here to avoid comparing spans,
325 // but it *also* is a "probable" equality which is a pretty weird
326 // definition. We mostly want to catch actual changes to the AST
327 // like a `#[cfg]` being processed or some weird `macro_rules!`
330 // What we *don't* want to catch is the fact that a user-defined
331 // literal like `0xf` is stringified as `15`, causing the cached token
332 // stream to not be literal `==` token-wise (ignoring spans) to the
333 // token stream we got from stringification.
335 // Instead the "probably equal" check here is "does each token
336 // recursively have the same discriminant?" We basically don't look at
337 // the token values here and assume that such fine grained token stream
338 // modifications, including adding/removing typically non-semantic
339 // tokens such as extra braces and commas, don't happen.
340 if let Some(tokens) = tokens {
341 if tokens.probably_equal_for_proc_macro(&tokens_for_real) {
344 info!("cached tokens found, but they're not \"probably equal\", \
345 going with stringified version");
347 return tokens_for_real
352 attrs: &[ast::Attribute],
353 tokens: Option<&tokenstream::TokenStream>,
354 span: syntax_pos::Span
355 ) -> Option<tokenstream::TokenStream> {
356 let tokens = tokens?;
357 if attrs.len() == 0 {
358 return Some(tokens.clone())
360 let mut builder = tokenstream::TokenStreamBuilder::new();
362 assert_eq!(attr.style, ast::AttrStyle::Outer,
363 "inner attributes should prevent cached tokens from existing");
365 let source = pprust::attribute_to_string(attr);
366 let macro_filename = FileName::macro_expansion_source_code(&source);
367 if attr.is_sugared_doc {
368 let stream = parse_stream_from_source_str(macro_filename, source, sess, Some(span));
369 builder.push(stream);
373 // synthesize # [ $path $tokens ] manually here
374 let mut brackets = tokenstream::TokenStreamBuilder::new();
376 // For simple paths, push the identifier directly
377 if attr.path.segments.len() == 1 && attr.path.segments[0].args.is_none() {
378 let ident = attr.path.segments[0].ident;
379 let token = token::Ident(ident.name, ident.as_str().starts_with("r#"));
380 brackets.push(tokenstream::TokenTree::token(token, ident.span));
382 // ... and for more complicated paths, fall back to a reparse hack that
383 // should eventually be removed.
385 let stream = parse_stream_from_source_str(macro_filename, source, sess, Some(span));
386 brackets.push(stream);
389 brackets.push(attr.tokens.clone());
391 // The span we list here for `#` and for `[ ... ]` are both wrong in
392 // that it encompasses more than each token, but it hopefully is "good
393 // enough" for now at least.
394 builder.push(tokenstream::TokenTree::token(token::Pound, attr.span));
395 let delim_span = tokenstream::DelimSpan::from_single(attr.span);
396 builder.push(tokenstream::TokenTree::Delimited(
397 delim_span, token::DelimToken::Bracket, brackets.build().into()));
399 builder.push(tokens.clone());
400 Some(builder.build())