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