1 //! The main parser interface.
3 #![feature(crate_visibility_modifier)]
4 #![feature(bindings_after_at)]
5 #![feature(iter_order_by)]
6 #![feature(or_patterns)]
9 use rustc_ast::token::{self, DelimToken, Nonterminal, Token, TokenKind};
10 use rustc_ast::tokenstream::{self, LazyTokenStream, TokenStream, TokenTree};
11 use rustc_ast_pretty::pprust;
12 use rustc_data_structures::sync::Lrc;
13 use rustc_errors::{Diagnostic, FatalError, Level, PResult};
14 use rustc_session::parse::ParseSess;
15 use rustc_span::{symbol::kw, FileName, SourceFile, Span, DUMMY_SP};
17 use smallvec::SmallVec;
22 use tracing::{debug, info};
24 pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments");
28 use parser::{emit_unclosed_delims, make_unclosed_delims_error, Parser};
30 pub mod validate_attr;
32 // A bunch of utility functions of the form `parse_<thing>_from_<source>`
33 // where <thing> includes crate, expr, item, stmt, tts, and one that
34 // uses a HOF to parse anything, and <source> includes file and
37 /// A variant of 'panictry!' that works on a Vec<Diagnostic> instead of a single DiagnosticBuilder.
38 macro_rules! panictry_buffer {
39 ($handler:expr, $e:expr) => {{
40 use rustc_errors::FatalError;
41 use std::result::Result::{Err, Ok};
46 $handler.emit_diagnostic(&e);
54 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
55 let mut parser = new_parser_from_file(sess, input, None);
56 parser.parse_crate_mod()
59 pub fn parse_crate_attrs_from_file<'a>(
62 ) -> PResult<'a, Vec<ast::Attribute>> {
63 let mut parser = new_parser_from_file(sess, input, None);
64 parser.parse_inner_attributes()
67 pub fn parse_crate_from_source_str(
71 ) -> PResult<'_, ast::Crate> {
72 new_parser_from_source_str(sess, name, source).parse_crate_mod()
75 pub fn parse_crate_attrs_from_source_str(
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) =
90 source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span);
91 emit_unclosed_delims(&mut errors, &sess);
95 /// Creates a new parser from a source string.
96 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
97 panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
100 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
102 pub fn maybe_new_parser_from_source_str(
106 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
107 maybe_source_file_to_parser(sess, sess.source_map().new_source_file(name, source))
110 /// Creates a new parser, handling errors as appropriate if the file doesn't exist.
111 /// If a span is given, that is used on an error as the source of the problem.
112 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path, sp: Option<Span>) -> Parser<'a> {
113 source_file_to_parser(sess, file_to_source_file(sess, path, sp))
116 /// Given a `source_file` and config, returns a parser.
117 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
118 panictry_buffer!(&sess.span_diagnostic, maybe_source_file_to_parser(sess, source_file))
121 /// Given a `source_file` and config, return a parser. Returns any buffered errors from lexing the
122 /// initial token stream.
123 fn maybe_source_file_to_parser(
125 source_file: Lrc<SourceFile>,
126 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
127 let end_pos = source_file.end_pos;
128 let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
129 let mut parser = stream_to_parser(sess, stream, None);
130 parser.unclosed_delims = unclosed_delims;
131 if parser.token == token::Eof {
132 parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt());
140 /// Given a session and a path and an optional span (for error reporting),
141 /// add the path to the session's source_map and return the new source_file or
142 /// error when a file can't be read.
143 fn try_file_to_source_file(
146 spanopt: Option<Span>,
147 ) -> Result<Lrc<SourceFile>, Diagnostic> {
148 sess.source_map().load_file(path).map_err(|e| {
149 let msg = format!("couldn't read {}: {}", path.display(), e);
150 let mut diag = Diagnostic::new(Level::Fatal, &msg);
151 if let Some(sp) = spanopt {
158 /// Given a session and a path and an optional span (for error reporting),
159 /// adds the path to the session's `source_map` and returns the new `source_file`.
160 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) -> Lrc<SourceFile> {
161 match try_file_to_source_file(sess, path, spanopt) {
162 Ok(source_file) => source_file,
164 sess.span_diagnostic.emit_diagnostic(&d);
170 /// Given a `source_file`, produces a sequence of token trees.
171 pub fn source_file_to_stream(
173 source_file: Lrc<SourceFile>,
174 override_span: Option<Span>,
175 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
176 panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
179 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
180 /// parsing the token stream.
181 pub fn maybe_file_to_stream(
183 source_file: Lrc<SourceFile>,
184 override_span: Option<Span>,
185 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
186 let src = source_file.src.as_ref().unwrap_or_else(|| {
188 .bug(&format!("cannot lex `source_file` without source: {}", source_file.name));
191 let (token_trees, unmatched_braces) =
192 lexer::parse_token_trees(sess, src.as_str(), source_file.start_pos, override_span);
195 Ok(stream) => Ok((stream, unmatched_braces)),
197 let mut buffer = Vec::with_capacity(1);
198 err.buffer(&mut buffer);
199 // Not using `emit_unclosed_delims` to use `db.buffer`
200 for unmatched in unmatched_braces {
201 if let Some(err) = make_unclosed_delims_error(unmatched, &sess) {
202 err.buffer(&mut buffer);
210 /// Given a stream and the `ParseSess`, produces a parser.
211 pub fn stream_to_parser<'a>(
214 subparser_name: Option<&'static str>,
216 Parser::new(sess, stream, false, subparser_name)
219 /// Runs the given subparser `f` on the tokens of the given `attr`'s item.
220 pub fn parse_in<'a, T>(
224 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
225 ) -> PResult<'a, T> {
226 let mut parser = Parser::new(sess, tts, false, Some(name));
227 let result = f(&mut parser)?;
228 if parser.token != token::Eof {
229 parser.unexpected()?;
234 // NOTE(Centril): The following probably shouldn't be here but it acknowledges the
235 // fact that architecturally, we are using parsing (read on below to understand why).
237 pub fn nt_to_tokenstream(nt: &Nonterminal, sess: &ParseSess, span: Span) -> TokenStream {
238 // A `Nonterminal` is often a parsed AST item. At this point we now
239 // need to convert the parsed AST to an actual token stream, e.g.
240 // un-parse it basically.
242 // Unfortunately there's not really a great way to do that in a
243 // guaranteed lossless fashion right now. The fallback here is to just
244 // stringify the AST node and reparse it, but this loses all span
247 // As a result, some AST nodes are annotated with the token stream they
248 // came from. Here we attempt to extract these lossless token streams
249 // before we fall back to the stringification.
252 |tokens: &Option<LazyTokenStream>| tokens.as_ref().map(|t| t.create_token_stream());
254 let tokens = match *nt {
255 Nonterminal::NtItem(ref item) => prepend_attrs(&item.attrs, item.tokens.as_ref()),
256 Nonterminal::NtBlock(ref block) => convert_tokens(&block.tokens),
257 Nonterminal::NtStmt(ref stmt) => {
258 // FIXME: We currently only collect tokens for `:stmt`
259 // matchers in `macro_rules!` macros. When we start collecting
260 // tokens for attributes on statements, we will need to prepend
262 convert_tokens(&stmt.tokens)
264 Nonterminal::NtPat(ref pat) => convert_tokens(&pat.tokens),
265 Nonterminal::NtTy(ref ty) => convert_tokens(&ty.tokens),
266 Nonterminal::NtIdent(ident, is_raw) => {
267 Some(tokenstream::TokenTree::token(token::Ident(ident.name, is_raw), ident.span).into())
269 Nonterminal::NtLifetime(ident) => {
270 Some(tokenstream::TokenTree::token(token::Lifetime(ident.name), ident.span).into())
272 Nonterminal::NtMeta(ref attr) => convert_tokens(&attr.tokens),
273 Nonterminal::NtPath(ref path) => convert_tokens(&path.tokens),
274 Nonterminal::NtVis(ref vis) => convert_tokens(&vis.tokens),
275 Nonterminal::NtTT(ref tt) => Some(tt.clone().into()),
276 Nonterminal::NtExpr(ref expr) | Nonterminal::NtLiteral(ref expr) => {
277 if expr.tokens.is_none() {
278 debug!("missing tokens for expr {:?}", expr);
280 prepend_attrs(&expr.attrs, expr.tokens.as_ref())
284 // FIXME(#43081): Avoid this pretty-print + reparse hack
285 // Pretty-print the AST struct without inserting any parenthesis
286 // beyond those explicitly written by the user (e.g. `ExpnKind::Paren`).
287 // The resulting stream may have incorrect precedence, but it's only
288 // ever used for a comparison against the capture tokenstream.
289 let source = pprust::nonterminal_to_string_no_extra_parens(nt);
290 let filename = FileName::macro_expansion_source_code(&source);
291 let reparsed_tokens = parse_stream_from_source_str(filename, source, sess, Some(span));
293 // During early phases of the compiler the AST could get modified
294 // directly (e.g., attributes added or removed) and the internal cache
295 // of tokens my not be invalidated or updated. Consequently if the
296 // "lossless" token stream disagrees with our actual stringification
297 // (which has historically been much more battle-tested) then we go
298 // with the lossy stream anyway (losing span information).
300 // Note that the comparison isn't `==` here to avoid comparing spans,
301 // but it *also* is a "probable" equality which is a pretty weird
302 // definition. We mostly want to catch actual changes to the AST
303 // like a `#[cfg]` being processed or some weird `macro_rules!`
306 // What we *don't* want to catch is the fact that a user-defined
307 // literal like `0xf` is stringified as `15`, causing the cached token
308 // stream to not be literal `==` token-wise (ignoring spans) to the
309 // token stream we got from stringification.
311 // Instead the "probably equal" check here is "does each token
312 // recursively have the same discriminant?" We basically don't look at
313 // the token values here and assume that such fine grained token stream
314 // modifications, including adding/removing typically non-semantic
315 // tokens such as extra braces and commas, don't happen.
316 if let Some(tokens) = tokens {
317 // Compare with a non-relaxed delim match to start.
318 if tokenstream_probably_equal_for_proc_macro(&tokens, &reparsed_tokens, sess, false) {
322 // The check failed. This time, we pretty-print the AST struct with parenthesis
323 // inserted to preserve precedence. This may cause `None`-delimiters in the captured
324 // token stream to match up with inserted parenthesis in the reparsed stream.
325 let source_with_parens = pprust::nonterminal_to_string(nt);
326 let filename_with_parens = FileName::macro_expansion_source_code(&source_with_parens);
327 let reparsed_tokens_with_parens = parse_stream_from_source_str(
328 filename_with_parens,
334 // Compare with a relaxed delim match - we want inserted parenthesis in the
335 // reparsed stream to match `None`-delimiters in the original stream.
336 if tokenstream_probably_equal_for_proc_macro(
338 &reparsed_tokens_with_parens,
346 "cached tokens found, but they're not \"probably equal\", \
347 going with stringified version"
349 info!("cached tokens: {}", pprust::tts_to_string(&tokens));
350 info!("reparsed tokens: {}", pprust::tts_to_string(&reparsed_tokens_with_parens));
352 info!("cached tokens debug: {:?}", tokens);
353 info!("reparsed tokens debug: {:?}", reparsed_tokens_with_parens);
358 // See comments in `Nonterminal::to_tokenstream` for why we care about
359 // *probably* equal here rather than actual equality
361 // This is otherwise the same as `eq_unspanned`, only recursing with a
363 pub fn tokenstream_probably_equal_for_proc_macro(
364 tokens: &TokenStream,
365 reparsed_tokens: &TokenStream,
367 relaxed_delim_match: bool,
369 // When checking for `probably_eq`, we ignore certain tokens that aren't
370 // preserved in the AST. Because they are not preserved, the pretty
371 // printer arbitrarily adds or removes them when printing as token
372 // streams, making a comparison between a token stream generated from an
373 // AST and a token stream which was parsed into an AST more reliable.
374 fn semantic_tree(tree: &TokenTree) -> bool {
375 if let TokenTree::Token(token) = tree {
377 // The pretty printer tends to add trailing commas to
378 // everything, and in particular, after struct fields.
380 // The pretty printer collapses many semicolons into one.
382 // We don't preserve leading `|` tokens in patterns, so
383 // we ignore them entirely
384 | token::BinOp(token::BinOpToken::Or)
385 // We don't preserve trailing '+' tokens in trait bounds,
386 // so we ignore them entirely
387 | token::BinOp(token::BinOpToken::Plus)
388 // The pretty printer can turn `$crate` into `::crate_name`
389 | token::ModSep = token.kind {
396 // When comparing two `TokenStream`s, we ignore the `IsJoint` information.
398 // However, `rustc_parse::lexer::tokentrees::TokenStreamBuilder` will
399 // use `Token.glue` on adjacent tokens with the proper `IsJoint`.
400 // Since we are ignoreing `IsJoint`, a 'glued' token (e.g. `BinOp(Shr)`)
401 // and its 'split'/'unglued' compoenents (e.g. `Gt, Gt`) are equivalent
402 // when determining if two `TokenStream`s are 'probably equal'.
404 // Therefore, we use `break_two_token_op` to convert all tokens
405 // to the 'unglued' form (if it exists). This ensures that two
406 // `TokenStream`s which differ only in how their tokens are glued
407 // will be considered 'probably equal', which allows us to keep spans.
409 // This is important when the original `TokenStream` contained
410 // extra spaces (e.g. `f :: < Vec < _ > > ( ) ;'). These extra spaces
411 // will be omitted when we pretty-print, which can cause the original
412 // and reparsed `TokenStream`s to differ in the assignment of `IsJoint`,
413 // leading to some tokens being 'glued' together in one stream but not
414 // the other. See #68489 for more details.
415 fn break_tokens(tree: TokenTree) -> impl Iterator<Item = TokenTree> {
416 // In almost all cases, we should have either zero or one levels
417 // of 'unglueing'. However, in some unusual cases, we may need
418 // to iterate breaking tokens mutliple times. For example:
419 // '[BinOpEq(Shr)] => [Gt, Ge] -> [Gt, Gt, Eq]'
420 let mut token_trees: SmallVec<[_; 2]>;
421 if let TokenTree::Token(token) = &tree {
422 let mut out = SmallVec::<[_; 2]>::new();
423 out.push(token.clone());
424 // Iterate to fixpoint:
425 // * We start off with 'out' containing our initial token, and `temp` empty
426 // * If we are able to break any tokens in `out`, then `out` will have
427 // at least one more element than 'temp', so we will try to break tokens
429 // * If we cannot break any tokens in 'out', we are done
431 let mut temp = SmallVec::<[_; 2]>::new();
432 let mut changed = false;
434 for token in out.into_iter() {
435 if let Some((first, second)) = token.kind.break_two_token_op() {
436 temp.push(Token::new(first, DUMMY_SP));
437 temp.push(Token::new(second, DUMMY_SP));
448 token_trees = out.into_iter().map(TokenTree::Token).collect();
450 token_trees = SmallVec::new();
451 token_trees.push(tree);
453 token_trees.into_iter()
456 fn expand_token(tree: TokenTree, sess: &ParseSess) -> impl Iterator<Item = TokenTree> {
457 // When checking tokenstreams for 'probable equality', we are comparing
458 // a captured (from parsing) `TokenStream` to a reparsed tokenstream.
459 // The reparsed Tokenstream will never have `None`-delimited groups,
460 // since they are only ever inserted as a result of macro expansion.
461 // Therefore, inserting a `None`-delimtied group here (when we
462 // convert a nested `Nonterminal` to a tokenstream) would cause
463 // a mismatch with the reparsed tokenstream.
465 // Note that we currently do not handle the case where the
466 // reparsed stream has a `Parenthesis`-delimited group
467 // inserted. This will cause a spurious mismatch:
468 // issue #75734 tracks resolving this.
470 let expanded: SmallVec<[_; 1]> =
471 if let TokenTree::Token(Token { kind: TokenKind::Interpolated(nt), span }) = &tree {
472 nt_to_tokenstream(nt, sess, *span)
474 .flat_map(|t| expand_token(t, sess))
477 // Filter before and after breaking tokens,
478 // since we may want to ignore both glued and unglued tokens.
479 std::iter::once(tree)
480 .filter(semantic_tree)
481 .flat_map(break_tokens)
482 .filter(semantic_tree)
488 // Break tokens after we expand any nonterminals, so that we break tokens
489 // that are produced as a result of nonterminal expansion.
490 let tokens = tokens.trees().flat_map(|t| expand_token(t, sess));
491 let reparsed_tokens = reparsed_tokens.trees().flat_map(|t| expand_token(t, sess));
493 tokens.eq_by(reparsed_tokens, |t, rt| {
494 tokentree_probably_equal_for_proc_macro(&t, &rt, sess, relaxed_delim_match)
498 // See comments in `Nonterminal::to_tokenstream` for why we care about
499 // *probably* equal here rather than actual equality
501 // This is otherwise the same as `eq_unspanned`, only recursing with a
503 pub fn tokentree_probably_equal_for_proc_macro(
505 reparsed_token: &TokenTree,
507 relaxed_delim_match: bool,
509 match (token, reparsed_token) {
510 (TokenTree::Token(token), TokenTree::Token(reparsed_token)) => {
511 token_probably_equal_for_proc_macro(token, reparsed_token)
514 TokenTree::Delimited(_, delim, tokens),
515 TokenTree::Delimited(_, reparsed_delim, reparsed_tokens),
516 ) if delim == reparsed_delim => tokenstream_probably_equal_for_proc_macro(
522 (TokenTree::Delimited(_, DelimToken::NoDelim, tokens), reparsed_token) => {
523 if relaxed_delim_match {
524 if let TokenTree::Delimited(_, DelimToken::Paren, reparsed_tokens) = reparsed_token
526 if tokenstream_probably_equal_for_proc_macro(
537 && tokentree_probably_equal_for_proc_macro(
538 &tokens.trees().next().unwrap(),
548 // See comments in `Nonterminal::to_tokenstream` for why we care about
549 // *probably* equal here rather than actual equality
550 fn token_probably_equal_for_proc_macro(first: &Token, other: &Token) -> bool {
551 if mem::discriminant(&first.kind) != mem::discriminant(&other.kind) {
554 use rustc_ast::token::TokenKind::*;
555 match (&first.kind, &other.kind) {
570 | (&DotDotDot, &DotDotDot)
571 | (&DotDotEq, &DotDotEq)
578 | (&FatArrow, &FatArrow)
581 | (&Question, &Question)
582 | (&Eof, &Eof) => true,
584 (&BinOp(a), &BinOp(b)) | (&BinOpEq(a), &BinOpEq(b)) => a == b,
586 (&OpenDelim(a), &OpenDelim(b)) | (&CloseDelim(a), &CloseDelim(b)) => a == b,
588 (&DocComment(a1, a2, a3), &DocComment(b1, b2, b3)) => a1 == b1 && a2 == b2 && a3 == b3,
590 (&Literal(a), &Literal(b)) => a == b,
592 (&Lifetime(a), &Lifetime(b)) => a == b,
593 (&Ident(a, b), &Ident(c, d)) => {
594 b == d && (a == c || a == kw::DollarCrate || c == kw::DollarCrate)
597 (&Interpolated(..), &Interpolated(..)) => panic!("Unexpanded Interpolated!"),
599 _ => panic!("forgot to add a token?"),
604 attrs: &[ast::Attribute],
605 tokens: Option<&tokenstream::LazyTokenStream>,
606 ) -> Option<tokenstream::TokenStream> {
607 let tokens = tokens?.create_token_stream();
608 if attrs.is_empty() {
611 let mut builder = tokenstream::TokenStreamBuilder::new();
613 // FIXME: Correctly handle tokens for inner attributes.
614 // For now, we fall back to reparsing the original AST node
615 if attr.style == ast::AttrStyle::Inner {
618 builder.push(attr.tokens());
620 builder.push(tokens);
621 Some(builder.build())