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