]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/lib.rs
Rollup merge of #77739 - est31:remove_unused_code, r=petrochenkov,varkor
[rust.git] / compiler / rustc_parse / src / lib.rs
1 //! The main parser interface.
2
3 #![feature(bool_to_option)]
4 #![feature(crate_visibility_modifier)]
5 #![feature(bindings_after_at)]
6 #![feature(iter_order_by)]
7 #![feature(or_patterns)]
8
9 use rustc_ast as ast;
10 use rustc_ast::token::{self, DelimToken, Nonterminal, Token, TokenKind};
11 use rustc_ast::tokenstream::{self, TokenStream, TokenTree};
12 use rustc_ast_pretty::pprust;
13 use rustc_data_structures::sync::Lrc;
14 use rustc_errors::{Diagnostic, FatalError, Level, PResult};
15 use rustc_session::parse::ParseSess;
16 use rustc_span::{symbol::kw, FileName, SourceFile, Span, DUMMY_SP};
17
18 use smallvec::SmallVec;
19 use std::mem;
20 use std::path::Path;
21 use std::str;
22
23 use tracing::{debug, info};
24
25 pub const MACRO_ARGUMENTS: Option<&'static str> = Some("macro arguments");
26
27 #[macro_use]
28 pub mod parser;
29 use parser::{emit_unclosed_delims, make_unclosed_delims_error, Parser};
30 pub mod lexer;
31 pub mod validate_attr;
32
33 // A bunch of utility functions of the form `parse_<thing>_from_<source>`
34 // where <thing> includes crate, expr, item, stmt, tts, and one that
35 // uses a HOF to parse anything, and <source> includes file and
36 // `source_str`.
37
38 /// A variant of 'panictry!' that works on a Vec<Diagnostic> instead of a single DiagnosticBuilder.
39 macro_rules! panictry_buffer {
40     ($handler:expr, $e:expr) => {{
41         use rustc_errors::FatalError;
42         use std::result::Result::{Err, Ok};
43         match $e {
44             Ok(e) => e,
45             Err(errs) => {
46                 for e in errs {
47                     $handler.emit_diagnostic(&e);
48                 }
49                 FatalError.raise()
50             }
51         }
52     }};
53 }
54
55 pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
56     let mut parser = new_parser_from_file(sess, input, None);
57     parser.parse_crate_mod()
58 }
59
60 pub fn parse_crate_attrs_from_file<'a>(
61     input: &Path,
62     sess: &'a ParseSess,
63 ) -> PResult<'a, Vec<ast::Attribute>> {
64     let mut parser = new_parser_from_file(sess, input, None);
65     parser.parse_inner_attributes()
66 }
67
68 pub fn parse_crate_from_source_str(
69     name: FileName,
70     source: String,
71     sess: &ParseSess,
72 ) -> PResult<'_, ast::Crate> {
73     new_parser_from_source_str(sess, name, source).parse_crate_mod()
74 }
75
76 pub fn parse_crate_attrs_from_source_str(
77     name: FileName,
78     source: String,
79     sess: &ParseSess,
80 ) -> PResult<'_, Vec<ast::Attribute>> {
81     new_parser_from_source_str(sess, name, source).parse_inner_attributes()
82 }
83
84 pub fn parse_stream_from_source_str(
85     name: FileName,
86     source: String,
87     sess: &ParseSess,
88     override_span: Option<Span>,
89 ) -> TokenStream {
90     let (stream, mut errors) =
91         source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span);
92     emit_unclosed_delims(&mut errors, &sess);
93     stream
94 }
95
96 /// Creates a new parser from a source string.
97 pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
98     panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
99 }
100
101 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
102 /// token stream.
103 pub fn maybe_new_parser_from_source_str(
104     sess: &ParseSess,
105     name: FileName,
106     source: String,
107 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
108     maybe_source_file_to_parser(sess, sess.source_map().new_source_file(name, source))
109 }
110
111 /// Creates a new parser, handling errors as appropriate if the file doesn't exist.
112 /// If a span is given, that is used on an error as the source of the problem.
113 pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path, sp: Option<Span>) -> Parser<'a> {
114     source_file_to_parser(sess, file_to_source_file(sess, path, sp))
115 }
116
117 /// Given a `source_file` and config, returns a parser.
118 fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
119     panictry_buffer!(&sess.span_diagnostic, maybe_source_file_to_parser(sess, source_file))
120 }
121
122 /// Given a `source_file` and config, return a parser. Returns any buffered errors from lexing the
123 /// initial token stream.
124 fn maybe_source_file_to_parser(
125     sess: &ParseSess,
126     source_file: Lrc<SourceFile>,
127 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
128     let end_pos = source_file.end_pos;
129     let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
130     let mut parser = stream_to_parser(sess, stream, None);
131     parser.unclosed_delims = unclosed_delims;
132     if parser.token == token::Eof {
133         parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt());
134     }
135
136     Ok(parser)
137 }
138
139 // Base abstractions
140
141 /// Given a session and a path and an optional span (for error reporting),
142 /// add the path to the session's source_map and return the new source_file or
143 /// error when a file can't be read.
144 fn try_file_to_source_file(
145     sess: &ParseSess,
146     path: &Path,
147     spanopt: Option<Span>,
148 ) -> Result<Lrc<SourceFile>, Diagnostic> {
149     sess.source_map().load_file(path).map_err(|e| {
150         let msg = format!("couldn't read {}: {}", path.display(), e);
151         let mut diag = Diagnostic::new(Level::Fatal, &msg);
152         if let Some(sp) = spanopt {
153             diag.set_span(sp);
154         }
155         diag
156     })
157 }
158
159 /// Given a session and a path and an optional span (for error reporting),
160 /// adds the path to the session's `source_map` and returns the new `source_file`.
161 fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) -> Lrc<SourceFile> {
162     match try_file_to_source_file(sess, path, spanopt) {
163         Ok(source_file) => source_file,
164         Err(d) => {
165             sess.span_diagnostic.emit_diagnostic(&d);
166             FatalError.raise();
167         }
168     }
169 }
170
171 /// Given a `source_file`, produces a sequence of token trees.
172 pub fn source_file_to_stream(
173     sess: &ParseSess,
174     source_file: Lrc<SourceFile>,
175     override_span: Option<Span>,
176 ) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
177     panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
178 }
179
180 /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
181 /// parsing the token stream.
182 pub fn maybe_file_to_stream(
183     sess: &ParseSess,
184     source_file: Lrc<SourceFile>,
185     override_span: Option<Span>,
186 ) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
187     let src = source_file.src.as_ref().unwrap_or_else(|| {
188         sess.span_diagnostic
189             .bug(&format!("cannot lex `source_file` without source: {}", source_file.name));
190     });
191
192     let (token_trees, unmatched_braces) =
193         lexer::parse_token_trees(sess, src.as_str(), source_file.start_pos, override_span);
194
195     match token_trees {
196         Ok(stream) => Ok((stream, unmatched_braces)),
197         Err(err) => {
198             let mut buffer = Vec::with_capacity(1);
199             err.buffer(&mut buffer);
200             // Not using `emit_unclosed_delims` to use `db.buffer`
201             for unmatched in unmatched_braces {
202                 if let Some(err) = make_unclosed_delims_error(unmatched, &sess) {
203                     err.buffer(&mut buffer);
204                 }
205             }
206             Err(buffer)
207         }
208     }
209 }
210
211 /// Given a stream and the `ParseSess`, produces a parser.
212 pub fn stream_to_parser<'a>(
213     sess: &'a ParseSess,
214     stream: TokenStream,
215     subparser_name: Option<&'static str>,
216 ) -> Parser<'a> {
217     Parser::new(sess, stream, false, subparser_name)
218 }
219
220 /// Runs the given subparser `f` on the tokens of the given `attr`'s item.
221 pub fn parse_in<'a, T>(
222     sess: &'a ParseSess,
223     tts: TokenStream,
224     name: &'static str,
225     mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
226 ) -> PResult<'a, T> {
227     let mut parser = Parser::new(sess, tts, false, Some(name));
228     let result = f(&mut parser)?;
229     if parser.token != token::Eof {
230         parser.unexpected()?;
231     }
232     Ok(result)
233 }
234
235 // NOTE(Centril): The following probably shouldn't be here but it acknowledges the
236 // fact that architecturally, we are using parsing (read on below to understand why).
237
238 pub fn nt_to_tokenstream(nt: &Nonterminal, sess: &ParseSess, span: Span) -> TokenStream {
239     // A `Nonterminal` is often a parsed AST item. At this point we now
240     // need to convert the parsed AST to an actual token stream, e.g.
241     // un-parse it basically.
242     //
243     // Unfortunately there's not really a great way to do that in a
244     // guaranteed lossless fashion right now. The fallback here is to just
245     // stringify the AST node and reparse it, but this loses all span
246     // information.
247     //
248     // As a result, some AST nodes are annotated with the token stream they
249     // came from. Here we attempt to extract these lossless token streams
250     // before we fall back to the stringification.
251     let tokens = match *nt {
252         Nonterminal::NtItem(ref item) => {
253             prepend_attrs(sess, &item.attrs, item.tokens.as_ref(), span)
254         }
255         Nonterminal::NtBlock(ref block) => block.tokens.clone(),
256         Nonterminal::NtStmt(ref stmt) => {
257             // FIXME: We currently only collect tokens for `:stmt`
258             // matchers in `macro_rules!` macros. When we start collecting
259             // tokens for attributes on statements, we will need to prepend
260             // attributes here
261             stmt.tokens.clone()
262         }
263         Nonterminal::NtPat(ref pat) => pat.tokens.clone(),
264         Nonterminal::NtTy(ref ty) => ty.tokens.clone(),
265         Nonterminal::NtIdent(ident, is_raw) => {
266             Some(tokenstream::TokenTree::token(token::Ident(ident.name, is_raw), ident.span).into())
267         }
268         Nonterminal::NtLifetime(ident) => {
269             Some(tokenstream::TokenTree::token(token::Lifetime(ident.name), ident.span).into())
270         }
271         Nonterminal::NtMeta(ref attr) => attr.tokens.clone(),
272         Nonterminal::NtPath(ref path) => path.tokens.clone(),
273         Nonterminal::NtVis(ref vis) => vis.tokens.clone(),
274         Nonterminal::NtTT(ref tt) => Some(tt.clone().into()),
275         Nonterminal::NtExpr(ref expr) | Nonterminal::NtLiteral(ref expr) => {
276             if expr.tokens.is_none() {
277                 debug!("missing tokens for expr {:?}", expr);
278             }
279             prepend_attrs(sess, &expr.attrs, expr.tokens.as_ref(), span)
280         }
281     };
282
283     // FIXME(#43081): Avoid this pretty-print + reparse hack
284     // Pretty-print the AST struct without inserting any parenthesis
285     // beyond those explicitly written by the user (e.g. `ExpnKind::Paren`).
286     // The resulting stream may have incorrect precedence, but it's only
287     // ever used for a comparison against the capture tokenstream.
288     let source = pprust::nonterminal_to_string_no_extra_parens(nt);
289     let filename = FileName::macro_expansion_source_code(&source);
290     let reparsed_tokens = parse_stream_from_source_str(filename, source, sess, Some(span));
291
292     // During early phases of the compiler the AST could get modified
293     // directly (e.g., attributes added or removed) and the internal cache
294     // of tokens my not be invalidated or updated. Consequently if the
295     // "lossless" token stream disagrees with our actual stringification
296     // (which has historically been much more battle-tested) then we go
297     // with the lossy stream anyway (losing span information).
298     //
299     // Note that the comparison isn't `==` here to avoid comparing spans,
300     // but it *also* is a "probable" equality which is a pretty weird
301     // definition. We mostly want to catch actual changes to the AST
302     // like a `#[cfg]` being processed or some weird `macro_rules!`
303     // expansion.
304     //
305     // What we *don't* want to catch is the fact that a user-defined
306     // literal like `0xf` is stringified as `15`, causing the cached token
307     // stream to not be literal `==` token-wise (ignoring spans) to the
308     // token stream we got from stringification.
309     //
310     // Instead the "probably equal" check here is "does each token
311     // recursively have the same discriminant?" We basically don't look at
312     // the token values here and assume that such fine grained token stream
313     // modifications, including adding/removing typically non-semantic
314     // tokens such as extra braces and commas, don't happen.
315     if let Some(tokens) = tokens {
316         // Compare with a non-relaxed delim match to start.
317         if tokenstream_probably_equal_for_proc_macro(&tokens, &reparsed_tokens, sess, false) {
318             return tokens;
319         }
320
321         // The check failed. This time, we pretty-print the AST struct with parenthesis
322         // inserted to preserve precedence. This may cause `None`-delimiters in the captured
323         // token stream to match up with inserted parenthesis in the reparsed stream.
324         let source_with_parens = pprust::nonterminal_to_string(nt);
325         let filename_with_parens = FileName::macro_expansion_source_code(&source_with_parens);
326         let reparsed_tokens_with_parens = parse_stream_from_source_str(
327             filename_with_parens,
328             source_with_parens,
329             sess,
330             Some(span),
331         );
332
333         // Compare with a relaxed delim match - we want inserted parenthesis in the
334         // reparsed stream to match `None`-delimiters in the original stream.
335         if tokenstream_probably_equal_for_proc_macro(
336             &tokens,
337             &reparsed_tokens_with_parens,
338             sess,
339             true,
340         ) {
341             return tokens;
342         }
343
344         info!(
345             "cached tokens found, but they're not \"probably equal\", \
346                 going with stringified version"
347         );
348         info!("cached   tokens: {}", pprust::tts_to_string(&tokens));
349         info!("reparsed tokens: {}", pprust::tts_to_string(&reparsed_tokens_with_parens));
350
351         info!("cached   tokens debug: {:?}", tokens);
352         info!("reparsed tokens debug: {:?}", reparsed_tokens_with_parens);
353     }
354     reparsed_tokens
355 }
356
357 // See comments in `Nonterminal::to_tokenstream` for why we care about
358 // *probably* equal here rather than actual equality
359 //
360 // This is otherwise the same as `eq_unspanned`, only recursing with a
361 // different method.
362 pub fn tokenstream_probably_equal_for_proc_macro(
363     tokens: &TokenStream,
364     reparsed_tokens: &TokenStream,
365     sess: &ParseSess,
366     relaxed_delim_match: bool,
367 ) -> bool {
368     // When checking for `probably_eq`, we ignore certain tokens that aren't
369     // preserved in the AST. Because they are not preserved, the pretty
370     // printer arbitrarily adds or removes them when printing as token
371     // streams, making a comparison between a token stream generated from an
372     // AST and a token stream which was parsed into an AST more reliable.
373     fn semantic_tree(tree: &TokenTree) -> bool {
374         if let TokenTree::Token(token) = tree {
375             if let
376                 // The pretty printer tends to add trailing commas to
377                 // everything, and in particular, after struct fields.
378                 | token::Comma
379                 // The pretty printer collapses many semicolons into one.
380                 | token::Semi
381                 // We don't preserve leading `|` tokens in patterns, so
382                 // we ignore them entirely
383                 | token::BinOp(token::BinOpToken::Or)
384                 // We don't preserve trailing '+' tokens in trait bounds,
385                 // so we ignore them entirely
386                 | token::BinOp(token::BinOpToken::Plus)
387                 // The pretty printer can turn `$crate` into `::crate_name`
388                 | token::ModSep = token.kind {
389                 return false;
390             }
391         }
392         true
393     }
394
395     // When comparing two `TokenStream`s, we ignore the `IsJoint` information.
396     //
397     // However, `rustc_parse::lexer::tokentrees::TokenStreamBuilder` will
398     // use `Token.glue` on adjacent tokens with the proper `IsJoint`.
399     // Since we are ignoreing `IsJoint`, a 'glued' token (e.g. `BinOp(Shr)`)
400     // and its 'split'/'unglued' compoenents (e.g. `Gt, Gt`) are equivalent
401     // when determining if two `TokenStream`s are 'probably equal'.
402     //
403     // Therefore, we use `break_two_token_op` to convert all tokens
404     // to the 'unglued' form (if it exists). This ensures that two
405     // `TokenStream`s which differ only in how their tokens are glued
406     // will be considered 'probably equal', which allows us to keep spans.
407     //
408     // This is important when the original `TokenStream` contained
409     // extra spaces (e.g. `f :: < Vec < _ > > ( ) ;'). These extra spaces
410     // will be omitted when we pretty-print, which can cause the original
411     // and reparsed `TokenStream`s to differ in the assignment of `IsJoint`,
412     // leading to some tokens being 'glued' together in one stream but not
413     // the other. See #68489 for more details.
414     fn break_tokens(tree: TokenTree) -> impl Iterator<Item = TokenTree> {
415         // In almost all cases, we should have either zero or one levels
416         // of 'unglueing'. However, in some unusual cases, we may need
417         // to iterate breaking tokens mutliple times. For example:
418         // '[BinOpEq(Shr)] => [Gt, Ge] -> [Gt, Gt, Eq]'
419         let mut token_trees: SmallVec<[_; 2]>;
420         if let TokenTree::Token(token) = &tree {
421             let mut out = SmallVec::<[_; 2]>::new();
422             out.push(token.clone());
423             // Iterate to fixpoint:
424             // * We start off with 'out' containing our initial token, and `temp` empty
425             // * If we are able to break any tokens in `out`, then `out` will have
426             //   at least one more element than 'temp', so we will try to break tokens
427             //   again.
428             // * If we cannot break any tokens in 'out', we are done
429             loop {
430                 let mut temp = SmallVec::<[_; 2]>::new();
431                 let mut changed = false;
432
433                 for token in out.into_iter() {
434                     if let Some((first, second)) = token.kind.break_two_token_op() {
435                         temp.push(Token::new(first, DUMMY_SP));
436                         temp.push(Token::new(second, DUMMY_SP));
437                         changed = true;
438                     } else {
439                         temp.push(token);
440                     }
441                 }
442                 out = temp;
443                 if !changed {
444                     break;
445                 }
446             }
447             token_trees = out.into_iter().map(TokenTree::Token).collect();
448         } else {
449             token_trees = SmallVec::new();
450             token_trees.push(tree);
451         }
452         token_trees.into_iter()
453     }
454
455     fn expand_token(tree: TokenTree, sess: &ParseSess) -> impl Iterator<Item = TokenTree> {
456         // When checking tokenstreams for 'probable equality', we are comparing
457         // a captured (from parsing) `TokenStream` to a reparsed tokenstream.
458         // The reparsed Tokenstream will never have `None`-delimited groups,
459         // since they are only ever inserted as a result of macro expansion.
460         // Therefore, inserting a `None`-delimtied group here (when we
461         // convert a nested `Nonterminal` to a tokenstream) would cause
462         // a mismatch with the reparsed tokenstream.
463         //
464         // Note that we currently do not handle the case where the
465         // reparsed stream has a `Parenthesis`-delimited group
466         // inserted. This will cause a spurious mismatch:
467         // issue #75734 tracks resolving this.
468
469         let expanded: SmallVec<[_; 1]> =
470             if let TokenTree::Token(Token { kind: TokenKind::Interpolated(nt), span }) = &tree {
471                 nt_to_tokenstream(nt, sess, *span)
472                     .into_trees()
473                     .flat_map(|t| expand_token(t, sess))
474                     .collect()
475             } else {
476                 // Filter before and after breaking tokens,
477                 // since we may want to ignore both glued and unglued tokens.
478                 std::iter::once(tree)
479                     .filter(semantic_tree)
480                     .flat_map(break_tokens)
481                     .filter(semantic_tree)
482                     .collect()
483             };
484         expanded.into_iter()
485     }
486
487     // Break tokens after we expand any nonterminals, so that we break tokens
488     // that are produced as a result of nonterminal expansion.
489     let tokens = tokens.trees().flat_map(|t| expand_token(t, sess));
490     let reparsed_tokens = reparsed_tokens.trees().flat_map(|t| expand_token(t, sess));
491
492     tokens.eq_by(reparsed_tokens, |t, rt| {
493         tokentree_probably_equal_for_proc_macro(&t, &rt, sess, relaxed_delim_match)
494     })
495 }
496
497 // See comments in `Nonterminal::to_tokenstream` for why we care about
498 // *probably* equal here rather than actual equality
499 //
500 // This is otherwise the same as `eq_unspanned`, only recursing with a
501 // different method.
502 pub fn tokentree_probably_equal_for_proc_macro(
503     token: &TokenTree,
504     reparsed_token: &TokenTree,
505     sess: &ParseSess,
506     relaxed_delim_match: bool,
507 ) -> bool {
508     match (token, reparsed_token) {
509         (TokenTree::Token(token), TokenTree::Token(reparsed_token)) => {
510             token_probably_equal_for_proc_macro(token, reparsed_token)
511         }
512         (
513             TokenTree::Delimited(_, delim, tokens),
514             TokenTree::Delimited(_, reparsed_delim, reparsed_tokens),
515         ) if delim == reparsed_delim => tokenstream_probably_equal_for_proc_macro(
516             tokens,
517             reparsed_tokens,
518             sess,
519             relaxed_delim_match,
520         ),
521         (TokenTree::Delimited(_, DelimToken::NoDelim, tokens), reparsed_token) => {
522             if relaxed_delim_match {
523                 if let TokenTree::Delimited(_, DelimToken::Paren, reparsed_tokens) = reparsed_token
524                 {
525                     if tokenstream_probably_equal_for_proc_macro(
526                         tokens,
527                         reparsed_tokens,
528                         sess,
529                         relaxed_delim_match,
530                     ) {
531                         return true;
532                     }
533                 }
534             }
535             tokens.len() == 1
536                 && tokentree_probably_equal_for_proc_macro(
537                     &tokens.trees().next().unwrap(),
538                     reparsed_token,
539                     sess,
540                     relaxed_delim_match,
541                 )
542         }
543         _ => false,
544     }
545 }
546
547 // See comments in `Nonterminal::to_tokenstream` for why we care about
548 // *probably* equal here rather than actual equality
549 fn token_probably_equal_for_proc_macro(first: &Token, other: &Token) -> bool {
550     if mem::discriminant(&first.kind) != mem::discriminant(&other.kind) {
551         return false;
552     }
553     use rustc_ast::token::TokenKind::*;
554     match (&first.kind, &other.kind) {
555         (&Eq, &Eq)
556         | (&Lt, &Lt)
557         | (&Le, &Le)
558         | (&EqEq, &EqEq)
559         | (&Ne, &Ne)
560         | (&Ge, &Ge)
561         | (&Gt, &Gt)
562         | (&AndAnd, &AndAnd)
563         | (&OrOr, &OrOr)
564         | (&Not, &Not)
565         | (&Tilde, &Tilde)
566         | (&At, &At)
567         | (&Dot, &Dot)
568         | (&DotDot, &DotDot)
569         | (&DotDotDot, &DotDotDot)
570         | (&DotDotEq, &DotDotEq)
571         | (&Comma, &Comma)
572         | (&Semi, &Semi)
573         | (&Colon, &Colon)
574         | (&ModSep, &ModSep)
575         | (&RArrow, &RArrow)
576         | (&LArrow, &LArrow)
577         | (&FatArrow, &FatArrow)
578         | (&Pound, &Pound)
579         | (&Dollar, &Dollar)
580         | (&Question, &Question)
581         | (&Eof, &Eof) => true,
582
583         (&BinOp(a), &BinOp(b)) | (&BinOpEq(a), &BinOpEq(b)) => a == b,
584
585         (&OpenDelim(a), &OpenDelim(b)) | (&CloseDelim(a), &CloseDelim(b)) => a == b,
586
587         (&DocComment(a1, a2, a3), &DocComment(b1, b2, b3)) => a1 == b1 && a2 == b2 && a3 == b3,
588
589         (&Literal(a), &Literal(b)) => a == b,
590
591         (&Lifetime(a), &Lifetime(b)) => a == b,
592         (&Ident(a, b), &Ident(c, d)) => {
593             b == d && (a == c || a == kw::DollarCrate || c == kw::DollarCrate)
594         }
595
596         (&Interpolated(..), &Interpolated(..)) => panic!("Unexpanded Interpolated!"),
597
598         _ => panic!("forgot to add a token?"),
599     }
600 }
601
602 fn prepend_attrs(
603     sess: &ParseSess,
604     attrs: &[ast::Attribute],
605     tokens: Option<&tokenstream::TokenStream>,
606     span: rustc_span::Span,
607 ) -> Option<tokenstream::TokenStream> {
608     let tokens = tokens?;
609     if attrs.is_empty() {
610         return Some(tokens.clone());
611     }
612     let mut builder = tokenstream::TokenStreamBuilder::new();
613     for attr in attrs {
614         assert_eq!(
615             attr.style,
616             ast::AttrStyle::Outer,
617             "inner attributes should prevent cached tokens from existing"
618         );
619
620         let source = pprust::attribute_to_string(attr);
621         let macro_filename = FileName::macro_expansion_source_code(&source);
622
623         let item = match attr.kind {
624             ast::AttrKind::Normal(ref item) => item,
625             ast::AttrKind::DocComment(..) => {
626                 let stream = parse_stream_from_source_str(macro_filename, source, sess, Some(span));
627                 builder.push(stream);
628                 continue;
629             }
630         };
631
632         // synthesize # [ $path $tokens ] manually here
633         let mut brackets = tokenstream::TokenStreamBuilder::new();
634
635         // For simple paths, push the identifier directly
636         if item.path.segments.len() == 1 && item.path.segments[0].args.is_none() {
637             let ident = item.path.segments[0].ident;
638             let token = token::Ident(ident.name, ident.as_str().starts_with("r#"));
639             brackets.push(tokenstream::TokenTree::token(token, ident.span));
640
641         // ... and for more complicated paths, fall back to a reparse hack that
642         // should eventually be removed.
643         } else {
644             let stream = parse_stream_from_source_str(macro_filename, source, sess, Some(span));
645             brackets.push(stream);
646         }
647
648         brackets.push(item.args.outer_tokens());
649
650         // The span we list here for `#` and for `[ ... ]` are both wrong in
651         // that it encompasses more than each token, but it hopefully is "good
652         // enough" for now at least.
653         builder.push(tokenstream::TokenTree::token(token::Pound, attr.span));
654         let delim_span = tokenstream::DelimSpan::from_single(attr.span);
655         builder.push(tokenstream::TokenTree::Delimited(
656             delim_span,
657             token::DelimToken::Bracket,
658             brackets.build(),
659         ));
660     }
661     builder.push(tokens.clone());
662     Some(builder.build())
663 }