]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/lib.rs
Auto merge of #78636 - dtolnay:puncteq, r=petrochenkov
[rust.git] / compiler / rustc_parse / src / lib.rs
1 //! The main parser interface.
2
3 #![feature(crate_visibility_modifier)]
4 #![feature(bindings_after_at)]
5 #![feature(iter_order_by)]
6 #![feature(or_patterns)]
7
8 use rustc_ast as ast;
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};
16
17 use smallvec::SmallVec;
18 use std::mem;
19 use std::path::Path;
20 use std::str;
21
22 use tracing::{debug, info};
23
24 pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments");
25
26 #[macro_use]
27 pub mod parser;
28 use parser::{emit_unclosed_delims, make_unclosed_delims_error, Parser};
29 pub mod lexer;
30 pub mod validate_attr;
31
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
35 // `source_str`.
36
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};
42         match $e {
43             Ok(e) => e,
44             Err(errs) => {
45                 for e in errs {
46                     $handler.emit_diagnostic(&e);
47                 }
48                 FatalError.raise()
49             }
50         }
51     }};
52 }
53
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()
57 }
58
59 pub fn parse_crate_attrs_from_file<'a>(
60     input: &Path,
61     sess: &'a ParseSess,
62 ) -> PResult<'a, Vec<ast::Attribute>> {
63     let mut parser = new_parser_from_file(sess, input, None);
64     parser.parse_inner_attributes()
65 }
66
67 pub fn parse_crate_from_source_str(
68     name: FileName,
69     source: String,
70     sess: &ParseSess,
71 ) -> PResult<'_, ast::Crate> {
72     new_parser_from_source_str(sess, name, source).parse_crate_mod()
73 }
74
75 pub fn parse_crate_attrs_from_source_str(
76     name: FileName,
77     source: String,
78     sess: &ParseSess,
79 ) -> PResult<'_, Vec<ast::Attribute>> {
80     new_parser_from_source_str(sess, name, source).parse_inner_attributes()
81 }
82
83 pub fn parse_stream_from_source_str(
84     name: FileName,
85     source: String,
86     sess: &ParseSess,
87     override_span: Option<Span>,
88 ) -> TokenStream {
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);
92     stream
93 }
94
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))
98 }
99
100 /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
101 /// token stream.
102 pub fn maybe_new_parser_from_source_str(
103     sess: &ParseSess,
104     name: FileName,
105     source: String,
106 ) -> Result<Parser<'_>, Vec<Diagnostic>> {
107     maybe_source_file_to_parser(sess, sess.source_map().new_source_file(name, source))
108 }
109
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))
114 }
115
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))
119 }
120
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(
124     sess: &ParseSess,
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());
133     }
134
135     Ok(parser)
136 }
137
138 // Base abstractions
139
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(
144     sess: &ParseSess,
145     path: &Path,
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 {
152             diag.set_span(sp);
153         }
154         diag
155     })
156 }
157
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,
163         Err(d) => {
164             sess.span_diagnostic.emit_diagnostic(&d);
165             FatalError.raise();
166         }
167     }
168 }
169
170 /// Given a `source_file`, produces a sequence of token trees.
171 pub fn source_file_to_stream(
172     sess: &ParseSess,
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))
177 }
178
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(
182     sess: &ParseSess,
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(|| {
187         sess.span_diagnostic
188             .bug(&format!("cannot lex `source_file` without source: {}", source_file.name));
189     });
190
191     let (token_trees, unmatched_braces) =
192         lexer::parse_token_trees(sess, src.as_str(), source_file.start_pos, override_span);
193
194     match token_trees {
195         Ok(stream) => Ok((stream, unmatched_braces)),
196         Err(err) => {
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);
203                 }
204             }
205             Err(buffer)
206         }
207     }
208 }
209
210 /// Given a stream and the `ParseSess`, produces a parser.
211 pub fn stream_to_parser<'a>(
212     sess: &'a ParseSess,
213     stream: TokenStream,
214     subparser_name: Option<&'static str>,
215 ) -> Parser<'a> {
216     Parser::new(sess, stream, false, subparser_name)
217 }
218
219 /// Runs the given subparser `f` on the tokens of the given `attr`'s item.
220 pub fn parse_in<'a, T>(
221     sess: &'a ParseSess,
222     tts: TokenStream,
223     name: &'static str,
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()?;
230     }
231     Ok(result)
232 }
233
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).
236
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.
241     //
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
245     // information.
246     //
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.
250
251     let convert_tokens =
252         |tokens: &Option<LazyTokenStream>| tokens.as_ref().map(|t| t.create_token_stream());
253
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
261             // attributes here
262             convert_tokens(&stmt.tokens)
263         }
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())
268         }
269         Nonterminal::NtLifetime(ident) => {
270             Some(tokenstream::TokenTree::token(token::Lifetime(ident.name), ident.span).into())
271         }
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);
279             }
280             prepend_attrs(&expr.attrs, expr.tokens.as_ref())
281         }
282     };
283
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));
292
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).
299     //
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!`
304     // expansion.
305     //
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.
310     //
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) {
319             return tokens;
320         }
321
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,
329             source_with_parens,
330             sess,
331             Some(span),
332         );
333
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(
337             &tokens,
338             &reparsed_tokens_with_parens,
339             sess,
340             true,
341         ) {
342             return tokens;
343         }
344
345         info!(
346             "cached tokens found, but they're not \"probably equal\", \
347                 going with stringified version"
348         );
349         info!("cached   tokens: {}", pprust::tts_to_string(&tokens));
350         info!("reparsed tokens: {}", pprust::tts_to_string(&reparsed_tokens_with_parens));
351
352         info!("cached   tokens debug: {:?}", tokens);
353         info!("reparsed tokens debug: {:?}", reparsed_tokens_with_parens);
354     }
355     reparsed_tokens
356 }
357
358 // See comments in `Nonterminal::to_tokenstream` for why we care about
359 // *probably* equal here rather than actual equality
360 //
361 // This is otherwise the same as `eq_unspanned`, only recursing with a
362 // different method.
363 pub fn tokenstream_probably_equal_for_proc_macro(
364     tokens: &TokenStream,
365     reparsed_tokens: &TokenStream,
366     sess: &ParseSess,
367     relaxed_delim_match: bool,
368 ) -> 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 {
376             if let
377                 // The pretty printer tends to add trailing commas to
378                 // everything, and in particular, after struct fields.
379                 | token::Comma
380                 // The pretty printer collapses many semicolons into one.
381                 | token::Semi
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 {
390                 return false;
391             }
392         }
393         true
394     }
395
396     // When comparing two `TokenStream`s, we ignore the `IsJoint` information.
397     //
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'.
403     //
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.
408     //
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
428             //   again.
429             // * If we cannot break any tokens in 'out', we are done
430             loop {
431                 let mut temp = SmallVec::<[_; 2]>::new();
432                 let mut changed = false;
433
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));
438                         changed = true;
439                     } else {
440                         temp.push(token);
441                     }
442                 }
443                 out = temp;
444                 if !changed {
445                     break;
446                 }
447             }
448             token_trees = out.into_iter().map(TokenTree::Token).collect();
449         } else {
450             token_trees = SmallVec::new();
451             token_trees.push(tree);
452         }
453         token_trees.into_iter()
454     }
455
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.
464         //
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.
469
470         let expanded: SmallVec<[_; 1]> =
471             if let TokenTree::Token(Token { kind: TokenKind::Interpolated(nt), span }) = &tree {
472                 nt_to_tokenstream(nt, sess, *span)
473                     .into_trees()
474                     .flat_map(|t| expand_token(t, sess))
475                     .collect()
476             } else {
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)
483                     .collect()
484             };
485         expanded.into_iter()
486     }
487
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));
492
493     tokens.eq_by(reparsed_tokens, |t, rt| {
494         tokentree_probably_equal_for_proc_macro(&t, &rt, sess, relaxed_delim_match)
495     })
496 }
497
498 // See comments in `Nonterminal::to_tokenstream` for why we care about
499 // *probably* equal here rather than actual equality
500 //
501 // This is otherwise the same as `eq_unspanned`, only recursing with a
502 // different method.
503 pub fn tokentree_probably_equal_for_proc_macro(
504     token: &TokenTree,
505     reparsed_token: &TokenTree,
506     sess: &ParseSess,
507     relaxed_delim_match: bool,
508 ) -> bool {
509     match (token, reparsed_token) {
510         (TokenTree::Token(token), TokenTree::Token(reparsed_token)) => {
511             token_probably_equal_for_proc_macro(token, reparsed_token)
512         }
513         (
514             TokenTree::Delimited(_, delim, tokens),
515             TokenTree::Delimited(_, reparsed_delim, reparsed_tokens),
516         ) if delim == reparsed_delim => tokenstream_probably_equal_for_proc_macro(
517             tokens,
518             reparsed_tokens,
519             sess,
520             relaxed_delim_match,
521         ),
522         (TokenTree::Delimited(_, DelimToken::NoDelim, tokens), reparsed_token) => {
523             if relaxed_delim_match {
524                 if let TokenTree::Delimited(_, DelimToken::Paren, reparsed_tokens) = reparsed_token
525                 {
526                     if tokenstream_probably_equal_for_proc_macro(
527                         tokens,
528                         reparsed_tokens,
529                         sess,
530                         relaxed_delim_match,
531                     ) {
532                         return true;
533                     }
534                 }
535             }
536             tokens.len() == 1
537                 && tokentree_probably_equal_for_proc_macro(
538                     &tokens.trees().next().unwrap(),
539                     reparsed_token,
540                     sess,
541                     relaxed_delim_match,
542                 )
543         }
544         _ => false,
545     }
546 }
547
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) {
552         return false;
553     }
554     use rustc_ast::token::TokenKind::*;
555     match (&first.kind, &other.kind) {
556         (&Eq, &Eq)
557         | (&Lt, &Lt)
558         | (&Le, &Le)
559         | (&EqEq, &EqEq)
560         | (&Ne, &Ne)
561         | (&Ge, &Ge)
562         | (&Gt, &Gt)
563         | (&AndAnd, &AndAnd)
564         | (&OrOr, &OrOr)
565         | (&Not, &Not)
566         | (&Tilde, &Tilde)
567         | (&At, &At)
568         | (&Dot, &Dot)
569         | (&DotDot, &DotDot)
570         | (&DotDotDot, &DotDotDot)
571         | (&DotDotEq, &DotDotEq)
572         | (&Comma, &Comma)
573         | (&Semi, &Semi)
574         | (&Colon, &Colon)
575         | (&ModSep, &ModSep)
576         | (&RArrow, &RArrow)
577         | (&LArrow, &LArrow)
578         | (&FatArrow, &FatArrow)
579         | (&Pound, &Pound)
580         | (&Dollar, &Dollar)
581         | (&Question, &Question)
582         | (&Eof, &Eof) => true,
583
584         (&BinOp(a), &BinOp(b)) | (&BinOpEq(a), &BinOpEq(b)) => a == b,
585
586         (&OpenDelim(a), &OpenDelim(b)) | (&CloseDelim(a), &CloseDelim(b)) => a == b,
587
588         (&DocComment(a1, a2, a3), &DocComment(b1, b2, b3)) => a1 == b1 && a2 == b2 && a3 == b3,
589
590         (&Literal(a), &Literal(b)) => a == b,
591
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)
595         }
596
597         (&Interpolated(..), &Interpolated(..)) => panic!("Unexpanded Interpolated!"),
598
599         _ => panic!("forgot to add a token?"),
600     }
601 }
602
603 fn prepend_attrs(
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() {
609         return Some(tokens);
610     }
611     let mut builder = tokenstream::TokenStreamBuilder::new();
612     for attr in attrs {
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 {
616             return None;
617         }
618         builder.push(attr.tokens());
619     }
620     builder.push(tokens);
621     Some(builder.build())
622 }