]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/base.rs
Rollup merge of #105423 - oli-obk:symbols, r=jackh726
[rust.git] / compiler / rustc_expand / src / base.rs
1 use crate::expand::{self, AstFragment, Invocation};
2 use crate::module::DirOwnership;
3
4 use rustc_ast::attr::MarkedAttrs;
5 use rustc_ast::ptr::P;
6 use rustc_ast::token::{self, Nonterminal};
7 use rustc_ast::tokenstream::TokenStream;
8 use rustc_ast::visit::{AssocCtxt, Visitor};
9 use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind};
10 use rustc_attr::{self as attr, Deprecation, Stability};
11 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
12 use rustc_data_structures::sync::{self, Lrc};
13 use rustc_errors::{
14     Applicability, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic, MultiSpan, PResult,
15 };
16 use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
17 use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics};
18 use rustc_parse::{self, parser, MACRO_ARGUMENTS};
19 use rustc_session::errors::report_lit_error;
20 use rustc_session::{parse::ParseSess, Limit, Session};
21 use rustc_span::def_id::{CrateNum, DefId, LocalDefId};
22 use rustc_span::edition::Edition;
23 use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId};
24 use rustc_span::source_map::SourceMap;
25 use rustc_span::symbol::{kw, sym, Ident, Symbol};
26 use rustc_span::{BytePos, FileName, RealFileName, Span, DUMMY_SP};
27 use smallvec::{smallvec, SmallVec};
28
29 use std::default::Default;
30 use std::iter;
31 use std::path::PathBuf;
32 use std::rc::Rc;
33
34 pub(crate) use rustc_span::hygiene::MacroKind;
35
36 // When adding new variants, make sure to
37 // adjust the `visit_*` / `flat_map_*` calls in `InvocationCollector`
38 // to use `assign_id!`
39 #[derive(Debug, Clone)]
40 pub enum Annotatable {
41     Item(P<ast::Item>),
42     TraitItem(P<ast::AssocItem>),
43     ImplItem(P<ast::AssocItem>),
44     ForeignItem(P<ast::ForeignItem>),
45     Stmt(P<ast::Stmt>),
46     Expr(P<ast::Expr>),
47     Arm(ast::Arm),
48     ExprField(ast::ExprField),
49     PatField(ast::PatField),
50     GenericParam(ast::GenericParam),
51     Param(ast::Param),
52     FieldDef(ast::FieldDef),
53     Variant(ast::Variant),
54     Crate(ast::Crate),
55 }
56
57 impl Annotatable {
58     pub fn span(&self) -> Span {
59         match *self {
60             Annotatable::Item(ref item) => item.span,
61             Annotatable::TraitItem(ref trait_item) => trait_item.span,
62             Annotatable::ImplItem(ref impl_item) => impl_item.span,
63             Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
64             Annotatable::Stmt(ref stmt) => stmt.span,
65             Annotatable::Expr(ref expr) => expr.span,
66             Annotatable::Arm(ref arm) => arm.span,
67             Annotatable::ExprField(ref field) => field.span,
68             Annotatable::PatField(ref fp) => fp.pat.span,
69             Annotatable::GenericParam(ref gp) => gp.ident.span,
70             Annotatable::Param(ref p) => p.span,
71             Annotatable::FieldDef(ref sf) => sf.span,
72             Annotatable::Variant(ref v) => v.span,
73             Annotatable::Crate(ref c) => c.spans.inner_span,
74         }
75     }
76
77     pub fn visit_attrs(&mut self, f: impl FnOnce(&mut AttrVec)) {
78         match self {
79             Annotatable::Item(item) => item.visit_attrs(f),
80             Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
81             Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
82             Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
83             Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
84             Annotatable::Expr(expr) => expr.visit_attrs(f),
85             Annotatable::Arm(arm) => arm.visit_attrs(f),
86             Annotatable::ExprField(field) => field.visit_attrs(f),
87             Annotatable::PatField(fp) => fp.visit_attrs(f),
88             Annotatable::GenericParam(gp) => gp.visit_attrs(f),
89             Annotatable::Param(p) => p.visit_attrs(f),
90             Annotatable::FieldDef(sf) => sf.visit_attrs(f),
91             Annotatable::Variant(v) => v.visit_attrs(f),
92             Annotatable::Crate(c) => c.visit_attrs(f),
93         }
94     }
95
96     pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
97         match self {
98             Annotatable::Item(item) => visitor.visit_item(item),
99             Annotatable::TraitItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Trait),
100             Annotatable::ImplItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Impl),
101             Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
102             Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
103             Annotatable::Expr(expr) => visitor.visit_expr(expr),
104             Annotatable::Arm(arm) => visitor.visit_arm(arm),
105             Annotatable::ExprField(field) => visitor.visit_expr_field(field),
106             Annotatable::PatField(fp) => visitor.visit_pat_field(fp),
107             Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
108             Annotatable::Param(p) => visitor.visit_param(p),
109             Annotatable::FieldDef(sf) => visitor.visit_field_def(sf),
110             Annotatable::Variant(v) => visitor.visit_variant(v),
111             Annotatable::Crate(c) => visitor.visit_crate(c),
112         }
113     }
114
115     pub fn to_tokens(&self) -> TokenStream {
116         match self {
117             Annotatable::Item(node) => TokenStream::from_ast(node),
118             Annotatable::TraitItem(node) | Annotatable::ImplItem(node) => {
119                 TokenStream::from_ast(node)
120             }
121             Annotatable::ForeignItem(node) => TokenStream::from_ast(node),
122             Annotatable::Stmt(node) => {
123                 assert!(!matches!(node.kind, ast::StmtKind::Empty));
124                 TokenStream::from_ast(node)
125             }
126             Annotatable::Expr(node) => TokenStream::from_ast(node),
127             Annotatable::Arm(..)
128             | Annotatable::ExprField(..)
129             | Annotatable::PatField(..)
130             | Annotatable::GenericParam(..)
131             | Annotatable::Param(..)
132             | Annotatable::FieldDef(..)
133             | Annotatable::Variant(..)
134             | Annotatable::Crate(..) => panic!("unexpected annotatable"),
135         }
136     }
137
138     pub fn expect_item(self) -> P<ast::Item> {
139         match self {
140             Annotatable::Item(i) => i,
141             _ => panic!("expected Item"),
142         }
143     }
144
145     pub fn expect_trait_item(self) -> P<ast::AssocItem> {
146         match self {
147             Annotatable::TraitItem(i) => i,
148             _ => panic!("expected Item"),
149         }
150     }
151
152     pub fn expect_impl_item(self) -> P<ast::AssocItem> {
153         match self {
154             Annotatable::ImplItem(i) => i,
155             _ => panic!("expected Item"),
156         }
157     }
158
159     pub fn expect_foreign_item(self) -> P<ast::ForeignItem> {
160         match self {
161             Annotatable::ForeignItem(i) => i,
162             _ => panic!("expected foreign item"),
163         }
164     }
165
166     pub fn expect_stmt(self) -> ast::Stmt {
167         match self {
168             Annotatable::Stmt(stmt) => stmt.into_inner(),
169             _ => panic!("expected statement"),
170         }
171     }
172
173     pub fn expect_expr(self) -> P<ast::Expr> {
174         match self {
175             Annotatable::Expr(expr) => expr,
176             _ => panic!("expected expression"),
177         }
178     }
179
180     pub fn expect_arm(self) -> ast::Arm {
181         match self {
182             Annotatable::Arm(arm) => arm,
183             _ => panic!("expected match arm"),
184         }
185     }
186
187     pub fn expect_expr_field(self) -> ast::ExprField {
188         match self {
189             Annotatable::ExprField(field) => field,
190             _ => panic!("expected field"),
191         }
192     }
193
194     pub fn expect_pat_field(self) -> ast::PatField {
195         match self {
196             Annotatable::PatField(fp) => fp,
197             _ => panic!("expected field pattern"),
198         }
199     }
200
201     pub fn expect_generic_param(self) -> ast::GenericParam {
202         match self {
203             Annotatable::GenericParam(gp) => gp,
204             _ => panic!("expected generic parameter"),
205         }
206     }
207
208     pub fn expect_param(self) -> ast::Param {
209         match self {
210             Annotatable::Param(param) => param,
211             _ => panic!("expected parameter"),
212         }
213     }
214
215     pub fn expect_field_def(self) -> ast::FieldDef {
216         match self {
217             Annotatable::FieldDef(sf) => sf,
218             _ => panic!("expected struct field"),
219         }
220     }
221
222     pub fn expect_variant(self) -> ast::Variant {
223         match self {
224             Annotatable::Variant(v) => v,
225             _ => panic!("expected variant"),
226         }
227     }
228
229     pub fn expect_crate(self) -> ast::Crate {
230         match self {
231             Annotatable::Crate(krate) => krate,
232             _ => panic!("expected krate"),
233         }
234     }
235 }
236
237 /// Result of an expansion that may need to be retried.
238 /// Consider using this for non-`MultiItemModifier` expanders as well.
239 pub enum ExpandResult<T, U> {
240     /// Expansion produced a result (possibly dummy).
241     Ready(T),
242     /// Expansion could not produce a result and needs to be retried.
243     Retry(U),
244 }
245
246 pub trait MultiItemModifier {
247     /// `meta_item` is the attribute, and `item` is the item being modified.
248     fn expand(
249         &self,
250         ecx: &mut ExtCtxt<'_>,
251         span: Span,
252         meta_item: &ast::MetaItem,
253         item: Annotatable,
254         is_derive_const: bool,
255     ) -> ExpandResult<Vec<Annotatable>, Annotatable>;
256 }
257
258 impl<F> MultiItemModifier for F
259 where
260     F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> Vec<Annotatable>,
261 {
262     fn expand(
263         &self,
264         ecx: &mut ExtCtxt<'_>,
265         span: Span,
266         meta_item: &ast::MetaItem,
267         item: Annotatable,
268         _is_derive_const: bool,
269     ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
270         ExpandResult::Ready(self(ecx, span, meta_item, item))
271     }
272 }
273
274 pub trait BangProcMacro {
275     fn expand<'cx>(
276         &self,
277         ecx: &'cx mut ExtCtxt<'_>,
278         span: Span,
279         ts: TokenStream,
280     ) -> Result<TokenStream, ErrorGuaranteed>;
281 }
282
283 impl<F> BangProcMacro for F
284 where
285     F: Fn(TokenStream) -> TokenStream,
286 {
287     fn expand<'cx>(
288         &self,
289         _ecx: &'cx mut ExtCtxt<'_>,
290         _span: Span,
291         ts: TokenStream,
292     ) -> Result<TokenStream, ErrorGuaranteed> {
293         // FIXME setup implicit context in TLS before calling self.
294         Ok(self(ts))
295     }
296 }
297
298 pub trait AttrProcMacro {
299     fn expand<'cx>(
300         &self,
301         ecx: &'cx mut ExtCtxt<'_>,
302         span: Span,
303         annotation: TokenStream,
304         annotated: TokenStream,
305     ) -> Result<TokenStream, ErrorGuaranteed>;
306 }
307
308 impl<F> AttrProcMacro for F
309 where
310     F: Fn(TokenStream, TokenStream) -> TokenStream,
311 {
312     fn expand<'cx>(
313         &self,
314         _ecx: &'cx mut ExtCtxt<'_>,
315         _span: Span,
316         annotation: TokenStream,
317         annotated: TokenStream,
318     ) -> Result<TokenStream, ErrorGuaranteed> {
319         // FIXME setup implicit context in TLS before calling self.
320         Ok(self(annotation, annotated))
321     }
322 }
323
324 /// Represents a thing that maps token trees to Macro Results
325 pub trait TTMacroExpander {
326     fn expand<'cx>(
327         &self,
328         ecx: &'cx mut ExtCtxt<'_>,
329         span: Span,
330         input: TokenStream,
331     ) -> Box<dyn MacResult + 'cx>;
332 }
333
334 pub type MacroExpanderFn =
335     for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>;
336
337 impl<F> TTMacroExpander for F
338 where
339     F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>,
340 {
341     fn expand<'cx>(
342         &self,
343         ecx: &'cx mut ExtCtxt<'_>,
344         span: Span,
345         input: TokenStream,
346     ) -> Box<dyn MacResult + 'cx> {
347         self(ecx, span, input)
348     }
349 }
350
351 // Use a macro because forwarding to a simple function has type system issues
352 macro_rules! make_stmts_default {
353     ($me:expr) => {
354         $me.make_expr().map(|e| {
355             smallvec![ast::Stmt {
356                 id: ast::DUMMY_NODE_ID,
357                 span: e.span,
358                 kind: ast::StmtKind::Expr(e),
359             }]
360         })
361     };
362 }
363
364 /// The result of a macro expansion. The return values of the various
365 /// methods are spliced into the AST at the callsite of the macro.
366 pub trait MacResult {
367     /// Creates an expression.
368     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
369         None
370     }
371
372     /// Creates zero or more items.
373     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
374         None
375     }
376
377     /// Creates zero or more impl items.
378     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
379         None
380     }
381
382     /// Creates zero or more trait items.
383     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
384         None
385     }
386
387     /// Creates zero or more items in an `extern {}` block
388     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
389         None
390     }
391
392     /// Creates a pattern.
393     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
394         None
395     }
396
397     /// Creates zero or more statements.
398     ///
399     /// By default this attempts to create an expression statement,
400     /// returning None if that fails.
401     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
402         make_stmts_default!(self)
403     }
404
405     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
406         None
407     }
408
409     fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
410         None
411     }
412
413     fn make_expr_fields(self: Box<Self>) -> Option<SmallVec<[ast::ExprField; 1]>> {
414         None
415     }
416
417     fn make_pat_fields(self: Box<Self>) -> Option<SmallVec<[ast::PatField; 1]>> {
418         None
419     }
420
421     fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
422         None
423     }
424
425     fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
426         None
427     }
428
429     fn make_field_defs(self: Box<Self>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
430         None
431     }
432
433     fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
434         None
435     }
436
437     fn make_crate(self: Box<Self>) -> Option<ast::Crate> {
438         // Fn-like macros cannot produce a crate.
439         unreachable!()
440     }
441 }
442
443 macro_rules! make_MacEager {
444     ( $( $fld:ident: $t:ty, )* ) => {
445         /// `MacResult` implementation for the common case where you've already
446         /// built each form of AST that you might return.
447         #[derive(Default)]
448         pub struct MacEager {
449             $(
450                 pub $fld: Option<$t>,
451             )*
452         }
453
454         impl MacEager {
455             $(
456                 pub fn $fld(v: $t) -> Box<dyn MacResult> {
457                     Box::new(MacEager {
458                         $fld: Some(v),
459                         ..Default::default()
460                     })
461                 }
462             )*
463         }
464     }
465 }
466
467 make_MacEager! {
468     expr: P<ast::Expr>,
469     pat: P<ast::Pat>,
470     items: SmallVec<[P<ast::Item>; 1]>,
471     impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
472     trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
473     foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
474     stmts: SmallVec<[ast::Stmt; 1]>,
475     ty: P<ast::Ty>,
476 }
477
478 impl MacResult for MacEager {
479     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
480         self.expr
481     }
482
483     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
484         self.items
485     }
486
487     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
488         self.impl_items
489     }
490
491     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
492         self.trait_items
493     }
494
495     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
496         self.foreign_items
497     }
498
499     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
500         match self.stmts.as_ref().map_or(0, |s| s.len()) {
501             0 => make_stmts_default!(self),
502             _ => self.stmts,
503         }
504     }
505
506     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
507         if let Some(p) = self.pat {
508             return Some(p);
509         }
510         if let Some(e) = self.expr {
511             if matches!(e.kind, ast::ExprKind::Lit(_) | ast::ExprKind::IncludedBytes(_)) {
512                 return Some(P(ast::Pat {
513                     id: ast::DUMMY_NODE_ID,
514                     span: e.span,
515                     kind: PatKind::Lit(e),
516                     tokens: None,
517                 }));
518             }
519         }
520         None
521     }
522
523     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
524         self.ty
525     }
526 }
527
528 /// Fill-in macro expansion result, to allow compilation to continue
529 /// after hitting errors.
530 #[derive(Copy, Clone)]
531 pub struct DummyResult {
532     is_error: bool,
533     span: Span,
534 }
535
536 impl DummyResult {
537     /// Creates a default MacResult that can be anything.
538     ///
539     /// Use this as a return value after hitting any errors and
540     /// calling `span_err`.
541     pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
542         Box::new(DummyResult { is_error: true, span })
543     }
544
545     /// Same as `any`, but must be a valid fragment, not error.
546     pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
547         Box::new(DummyResult { is_error: false, span })
548     }
549
550     /// A plain dummy expression.
551     pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
552         P(ast::Expr {
553             id: ast::DUMMY_NODE_ID,
554             kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
555             span: sp,
556             attrs: ast::AttrVec::new(),
557             tokens: None,
558         })
559     }
560
561     /// A plain dummy pattern.
562     pub fn raw_pat(sp: Span) -> ast::Pat {
563         ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp, tokens: None }
564     }
565
566     /// A plain dummy type.
567     pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
568         P(ast::Ty {
569             id: ast::DUMMY_NODE_ID,
570             kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
571             span: sp,
572             tokens: None,
573         })
574     }
575 }
576
577 impl MacResult for DummyResult {
578     fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
579         Some(DummyResult::raw_expr(self.span, self.is_error))
580     }
581
582     fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
583         Some(P(DummyResult::raw_pat(self.span)))
584     }
585
586     fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
587         Some(SmallVec::new())
588     }
589
590     fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
591         Some(SmallVec::new())
592     }
593
594     fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
595         Some(SmallVec::new())
596     }
597
598     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
599         Some(SmallVec::new())
600     }
601
602     fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
603         Some(smallvec![ast::Stmt {
604             id: ast::DUMMY_NODE_ID,
605             kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
606             span: self.span,
607         }])
608     }
609
610     fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
611         Some(DummyResult::raw_ty(self.span, self.is_error))
612     }
613
614     fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
615         Some(SmallVec::new())
616     }
617
618     fn make_expr_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::ExprField; 1]>> {
619         Some(SmallVec::new())
620     }
621
622     fn make_pat_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::PatField; 1]>> {
623         Some(SmallVec::new())
624     }
625
626     fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
627         Some(SmallVec::new())
628     }
629
630     fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
631         Some(SmallVec::new())
632     }
633
634     fn make_field_defs(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
635         Some(SmallVec::new())
636     }
637
638     fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
639         Some(SmallVec::new())
640     }
641 }
642
643 /// A syntax extension kind.
644 pub enum SyntaxExtensionKind {
645     /// A token-based function-like macro.
646     Bang(
647         /// An expander with signature TokenStream -> TokenStream.
648         Box<dyn BangProcMacro + sync::Sync + sync::Send>,
649     ),
650
651     /// An AST-based function-like macro.
652     LegacyBang(
653         /// An expander with signature TokenStream -> AST.
654         Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
655     ),
656
657     /// A token-based attribute macro.
658     Attr(
659         /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
660         /// The first TokenSteam is the attribute itself, the second is the annotated item.
661         /// The produced TokenSteam replaces the input TokenSteam.
662         Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
663     ),
664
665     /// An AST-based attribute macro.
666     LegacyAttr(
667         /// An expander with signature (AST, AST) -> AST.
668         /// The first AST fragment is the attribute itself, the second is the annotated item.
669         /// The produced AST fragment replaces the input AST fragment.
670         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
671     ),
672
673     /// A trivial attribute "macro" that does nothing,
674     /// only keeps the attribute and marks it as inert,
675     /// thus making it ineligible for further expansion.
676     NonMacroAttr,
677
678     /// A token-based derive macro.
679     Derive(
680         /// An expander with signature TokenStream -> TokenStream.
681         /// The produced TokenSteam is appended to the input TokenSteam.
682         ///
683         /// FIXME: The text above describes how this should work. Currently it
684         /// is handled identically to `LegacyDerive`. It should be migrated to
685         /// a token-based representation like `Bang` and `Attr`, instead of
686         /// using `MultiItemModifier`.
687         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
688     ),
689
690     /// An AST-based derive macro.
691     LegacyDerive(
692         /// An expander with signature AST -> AST.
693         /// The produced AST fragment is appended to the input AST fragment.
694         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
695     ),
696 }
697
698 /// A struct representing a macro definition in "lowered" form ready for expansion.
699 pub struct SyntaxExtension {
700     /// A syntax extension kind.
701     pub kind: SyntaxExtensionKind,
702     /// Span of the macro definition.
703     pub span: Span,
704     /// List of unstable features that are treated as stable inside this macro.
705     pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
706     /// The macro's stability info.
707     pub stability: Option<Stability>,
708     /// The macro's deprecation info.
709     pub deprecation: Option<Deprecation>,
710     /// Names of helper attributes registered by this macro.
711     pub helper_attrs: Vec<Symbol>,
712     /// Edition of the crate in which this macro is defined.
713     pub edition: Edition,
714     /// Built-in macros have a couple of special properties like availability
715     /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
716     pub builtin_name: Option<Symbol>,
717     /// Suppresses the `unsafe_code` lint for code produced by this macro.
718     pub allow_internal_unsafe: bool,
719     /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
720     pub local_inner_macros: bool,
721     /// Should debuginfo for the macro be collapsed to the outermost expansion site (in other
722     /// words, was the macro definition annotated with `#[collapse_debuginfo]`)?
723     pub collapse_debuginfo: bool,
724 }
725
726 impl SyntaxExtension {
727     /// Returns which kind of macro calls this syntax extension.
728     pub fn macro_kind(&self) -> MacroKind {
729         match self.kind {
730             SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
731             SyntaxExtensionKind::Attr(..)
732             | SyntaxExtensionKind::LegacyAttr(..)
733             | SyntaxExtensionKind::NonMacroAttr => MacroKind::Attr,
734             SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
735                 MacroKind::Derive
736             }
737         }
738     }
739
740     /// Constructs a syntax extension with default properties.
741     pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
742         SyntaxExtension {
743             span: DUMMY_SP,
744             allow_internal_unstable: None,
745             stability: None,
746             deprecation: None,
747             helper_attrs: Vec::new(),
748             edition,
749             builtin_name: None,
750             kind,
751             allow_internal_unsafe: false,
752             local_inner_macros: false,
753             collapse_debuginfo: false,
754         }
755     }
756
757     /// Constructs a syntax extension with the given properties
758     /// and other properties converted from attributes.
759     pub fn new(
760         sess: &Session,
761         kind: SyntaxExtensionKind,
762         span: Span,
763         helper_attrs: Vec<Symbol>,
764         edition: Edition,
765         name: Symbol,
766         attrs: &[ast::Attribute],
767     ) -> SyntaxExtension {
768         let allow_internal_unstable =
769             attr::allow_internal_unstable(sess, &attrs).collect::<Vec<Symbol>>();
770
771         let allow_internal_unsafe = sess.contains_name(attrs, sym::allow_internal_unsafe);
772         let local_inner_macros = sess
773             .find_by_name(attrs, sym::macro_export)
774             .and_then(|macro_export| macro_export.meta_item_list())
775             .map_or(false, |l| attr::list_contains_name(&l, sym::local_inner_macros));
776         let collapse_debuginfo = sess.contains_name(attrs, sym::collapse_debuginfo);
777         tracing::debug!(?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe);
778
779         let (builtin_name, helper_attrs) = sess
780             .find_by_name(attrs, sym::rustc_builtin_macro)
781             .map(|attr| {
782                 // Override `helper_attrs` passed above if it's a built-in macro,
783                 // marking `proc_macro_derive` macros as built-in is not a realistic use case.
784                 parse_macro_name_and_helper_attrs(sess.diagnostic(), attr, "built-in").map_or_else(
785                     || (Some(name), Vec::new()),
786                     |(name, helper_attrs)| (Some(name), helper_attrs),
787                 )
788             })
789             .unwrap_or_else(|| (None, helper_attrs));
790         let (stability, const_stability, body_stability) = attr::find_stability(&sess, attrs, span);
791         if let Some((_, sp)) = const_stability {
792             sess.parse_sess
793                 .span_diagnostic
794                 .struct_span_err(sp, "macros cannot have const stability attributes")
795                 .span_label(sp, "invalid const stability attribute")
796                 .span_label(
797                     sess.source_map().guess_head_span(span),
798                     "const stability attribute affects this macro",
799                 )
800                 .emit();
801         }
802         if let Some((_, sp)) = body_stability {
803             sess.parse_sess
804                 .span_diagnostic
805                 .struct_span_err(sp, "macros cannot have body stability attributes")
806                 .span_label(sp, "invalid body stability attribute")
807                 .span_label(
808                     sess.source_map().guess_head_span(span),
809                     "body stability attribute affects this macro",
810                 )
811                 .emit();
812         }
813
814         SyntaxExtension {
815             kind,
816             span,
817             allow_internal_unstable: (!allow_internal_unstable.is_empty())
818                 .then(|| allow_internal_unstable.into()),
819             stability: stability.map(|(s, _)| s),
820             deprecation: attr::find_deprecation(&sess, attrs).map(|(d, _)| d),
821             helper_attrs,
822             edition,
823             builtin_name,
824             allow_internal_unsafe,
825             local_inner_macros,
826             collapse_debuginfo,
827         }
828     }
829
830     pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
831         fn expander<'cx>(
832             _: &'cx mut ExtCtxt<'_>,
833             span: Span,
834             _: TokenStream,
835         ) -> Box<dyn MacResult + 'cx> {
836             DummyResult::any(span)
837         }
838         SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
839     }
840
841     pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
842         fn expander(
843             _: &mut ExtCtxt<'_>,
844             _: Span,
845             _: &ast::MetaItem,
846             _: Annotatable,
847         ) -> Vec<Annotatable> {
848             Vec::new()
849         }
850         SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
851     }
852
853     pub fn non_macro_attr(edition: Edition) -> SyntaxExtension {
854         SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr, edition)
855     }
856
857     pub fn expn_data(
858         &self,
859         parent: LocalExpnId,
860         call_site: Span,
861         descr: Symbol,
862         macro_def_id: Option<DefId>,
863         parent_module: Option<DefId>,
864     ) -> ExpnData {
865         ExpnData::new(
866             ExpnKind::Macro(self.macro_kind(), descr),
867             parent.to_expn_id(),
868             call_site,
869             self.span,
870             self.allow_internal_unstable.clone(),
871             self.edition,
872             macro_def_id,
873             parent_module,
874             self.allow_internal_unsafe,
875             self.local_inner_macros,
876             self.collapse_debuginfo,
877         )
878     }
879 }
880
881 /// Error type that denotes indeterminacy.
882 pub struct Indeterminate;
883
884 pub type DeriveResolutions = Vec<(ast::Path, Annotatable, Option<Lrc<SyntaxExtension>>, bool)>;
885
886 pub trait ResolverExpand {
887     fn next_node_id(&mut self) -> NodeId;
888     fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId;
889
890     fn resolve_dollar_crates(&mut self);
891     fn visit_ast_fragment_with_placeholders(
892         &mut self,
893         expn_id: LocalExpnId,
894         fragment: &AstFragment,
895     );
896     fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind);
897
898     fn expansion_for_ast_pass(
899         &mut self,
900         call_site: Span,
901         pass: AstPass,
902         features: &[Symbol],
903         parent_module_id: Option<NodeId>,
904     ) -> LocalExpnId;
905
906     fn resolve_imports(&mut self);
907
908     fn resolve_macro_invocation(
909         &mut self,
910         invoc: &Invocation,
911         eager_expansion_root: LocalExpnId,
912         force: bool,
913     ) -> Result<Lrc<SyntaxExtension>, Indeterminate>;
914
915     fn record_macro_rule_usage(&mut self, mac_id: NodeId, rule_index: usize);
916
917     fn check_unused_macros(&mut self);
918
919     // Resolver interfaces for specific built-in macros.
920     /// Does `#[derive(...)]` attribute with the given `ExpnId` have built-in `Copy` inside it?
921     fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool;
922     /// Resolve paths inside the `#[derive(...)]` attribute with the given `ExpnId`.
923     fn resolve_derives(
924         &mut self,
925         expn_id: LocalExpnId,
926         force: bool,
927         derive_paths: &dyn Fn() -> DeriveResolutions,
928     ) -> Result<(), Indeterminate>;
929     /// Take resolutions for paths inside the `#[derive(...)]` attribute with the given `ExpnId`
930     /// back from resolver.
931     fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions>;
932     /// Path resolution logic for `#[cfg_accessible(path)]`.
933     fn cfg_accessible(
934         &mut self,
935         expn_id: LocalExpnId,
936         path: &ast::Path,
937     ) -> Result<bool, Indeterminate>;
938
939     /// Decodes the proc-macro quoted span in the specified crate, with the specified id.
940     /// No caching is performed.
941     fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span;
942
943     /// The order of items in the HIR is unrelated to the order of
944     /// items in the AST. However, we generate proc macro harnesses
945     /// based on the AST order, and later refer to these harnesses
946     /// from the HIR. This field keeps track of the order in which
947     /// we generated proc macros harnesses, so that we can map
948     /// HIR proc macros items back to their harness items.
949     fn declare_proc_macro(&mut self, id: NodeId);
950
951     /// Tools registered with `#![register_tool]` and used by tool attributes and lints.
952     fn registered_tools(&self) -> &FxHashSet<Ident>;
953 }
954
955 pub trait LintStoreExpand {
956     fn pre_expansion_lint(
957         &self,
958         sess: &Session,
959         registered_tools: &FxHashSet<Ident>,
960         node_id: NodeId,
961         attrs: &[Attribute],
962         items: &[P<Item>],
963         name: Symbol,
964     );
965 }
966
967 type LintStoreExpandDyn<'a> = Option<&'a (dyn LintStoreExpand + 'a)>;
968
969 #[derive(Clone, Default)]
970 pub struct ModuleData {
971     /// Path to the module starting from the crate name, like `my_crate::foo::bar`.
972     pub mod_path: Vec<Ident>,
973     /// Stack of paths to files loaded by out-of-line module items,
974     /// used to detect and report recursive module inclusions.
975     pub file_path_stack: Vec<PathBuf>,
976     /// Directory to search child module files in,
977     /// often (but not necessarily) the parent of the top file path on the `file_path_stack`.
978     pub dir_path: PathBuf,
979 }
980
981 impl ModuleData {
982     pub fn with_dir_path(&self, dir_path: PathBuf) -> ModuleData {
983         ModuleData {
984             mod_path: self.mod_path.clone(),
985             file_path_stack: self.file_path_stack.clone(),
986             dir_path,
987         }
988     }
989 }
990
991 #[derive(Clone)]
992 pub struct ExpansionData {
993     pub id: LocalExpnId,
994     pub depth: usize,
995     pub module: Rc<ModuleData>,
996     pub dir_ownership: DirOwnership,
997     pub prior_type_ascription: Option<(Span, bool)>,
998     /// Some parent node that is close to this macro call
999     pub lint_node_id: NodeId,
1000     pub is_trailing_mac: bool,
1001 }
1002
1003 /// One of these is made during expansion and incrementally updated as we go;
1004 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
1005 /// -> expn_data` of their expansion context stored into their span.
1006 pub struct ExtCtxt<'a> {
1007     pub sess: &'a Session,
1008     pub ecfg: expand::ExpansionConfig<'a>,
1009     pub reduced_recursion_limit: Option<Limit>,
1010     pub root_path: PathBuf,
1011     pub resolver: &'a mut dyn ResolverExpand,
1012     pub current_expansion: ExpansionData,
1013     /// Error recovery mode entered when expansion is stuck
1014     /// (or during eager expansion, but that's a hack).
1015     pub force_mode: bool,
1016     pub expansions: FxIndexMap<Span, Vec<String>>,
1017     /// Used for running pre-expansion lints on freshly loaded modules.
1018     pub(super) lint_store: LintStoreExpandDyn<'a>,
1019     /// Used for storing lints generated during expansion, like `NAMED_ARGUMENTS_USED_POSITIONALLY`
1020     pub buffered_early_lint: Vec<BufferedEarlyLint>,
1021     /// When we 'expand' an inert attribute, we leave it
1022     /// in the AST, but insert it here so that we know
1023     /// not to expand it again.
1024     pub(super) expanded_inert_attrs: MarkedAttrs,
1025 }
1026
1027 impl<'a> ExtCtxt<'a> {
1028     pub fn new(
1029         sess: &'a Session,
1030         ecfg: expand::ExpansionConfig<'a>,
1031         resolver: &'a mut dyn ResolverExpand,
1032         lint_store: LintStoreExpandDyn<'a>,
1033     ) -> ExtCtxt<'a> {
1034         ExtCtxt {
1035             sess,
1036             ecfg,
1037             reduced_recursion_limit: None,
1038             resolver,
1039             lint_store,
1040             root_path: PathBuf::new(),
1041             current_expansion: ExpansionData {
1042                 id: LocalExpnId::ROOT,
1043                 depth: 0,
1044                 module: Default::default(),
1045                 dir_ownership: DirOwnership::Owned { relative: None },
1046                 prior_type_ascription: None,
1047                 lint_node_id: ast::CRATE_NODE_ID,
1048                 is_trailing_mac: false,
1049             },
1050             force_mode: false,
1051             expansions: FxIndexMap::default(),
1052             expanded_inert_attrs: MarkedAttrs::new(),
1053             buffered_early_lint: vec![],
1054         }
1055     }
1056
1057     /// Returns a `Folder` for deeply expanding all macros in an AST node.
1058     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1059         expand::MacroExpander::new(self, false)
1060     }
1061
1062     /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
1063     /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
1064     pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1065         expand::MacroExpander::new(self, true)
1066     }
1067     pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
1068         rustc_parse::stream_to_parser(&self.sess.parse_sess, stream, MACRO_ARGUMENTS)
1069     }
1070     pub fn source_map(&self) -> &'a SourceMap {
1071         self.sess.parse_sess.source_map()
1072     }
1073     pub fn parse_sess(&self) -> &'a ParseSess {
1074         &self.sess.parse_sess
1075     }
1076     pub fn call_site(&self) -> Span {
1077         self.current_expansion.id.expn_data().call_site
1078     }
1079
1080     /// Returns the current expansion kind's description.
1081     pub(crate) fn expansion_descr(&self) -> String {
1082         let expn_data = self.current_expansion.id.expn_data();
1083         expn_data.kind.descr()
1084     }
1085
1086     /// Equivalent of `Span::def_site` from the proc macro API,
1087     /// except that the location is taken from the span passed as an argument.
1088     pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1089         span.with_def_site_ctxt(self.current_expansion.id.to_expn_id())
1090     }
1091
1092     /// Equivalent of `Span::call_site` from the proc macro API,
1093     /// except that the location is taken from the span passed as an argument.
1094     pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1095         span.with_call_site_ctxt(self.current_expansion.id.to_expn_id())
1096     }
1097
1098     /// Equivalent of `Span::mixed_site` from the proc macro API,
1099     /// except that the location is taken from the span passed as an argument.
1100     pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1101         span.with_mixed_site_ctxt(self.current_expansion.id.to_expn_id())
1102     }
1103
1104     /// Returns span for the macro which originally caused the current expansion to happen.
1105     ///
1106     /// Stops backtracing at include! boundary.
1107     pub fn expansion_cause(&self) -> Option<Span> {
1108         self.current_expansion.id.expansion_cause()
1109     }
1110
1111     #[rustc_lint_diagnostics]
1112     pub fn struct_span_err<S: Into<MultiSpan>>(
1113         &self,
1114         sp: S,
1115         msg: &str,
1116     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1117         self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1118     }
1119
1120     pub fn create_err(
1121         &self,
1122         err: impl IntoDiagnostic<'a>,
1123     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1124         self.sess.create_err(err)
1125     }
1126
1127     pub fn emit_err(&self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
1128         self.sess.emit_err(err)
1129     }
1130
1131     /// Emit `msg` attached to `sp`, without immediately stopping
1132     /// compilation.
1133     ///
1134     /// Compilation will be stopped in the near future (at the end of
1135     /// the macro expansion phase).
1136     #[rustc_lint_diagnostics]
1137     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1138         self.sess.parse_sess.span_diagnostic.span_err(sp, msg);
1139     }
1140     #[rustc_lint_diagnostics]
1141     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1142         self.sess.parse_sess.span_diagnostic.span_warn(sp, msg);
1143     }
1144     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1145         self.sess.parse_sess.span_diagnostic.span_bug(sp, msg);
1146     }
1147     pub fn trace_macros_diag(&mut self) {
1148         for (sp, notes) in self.expansions.iter() {
1149             let mut db = self.sess.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1150             for note in notes {
1151                 db.note(note);
1152             }
1153             db.emit();
1154         }
1155         // Fixme: does this result in errors?
1156         self.expansions.clear();
1157     }
1158     pub fn bug(&self, msg: &str) -> ! {
1159         self.sess.parse_sess.span_diagnostic.bug(msg);
1160     }
1161     pub fn trace_macros(&self) -> bool {
1162         self.ecfg.trace_mac
1163     }
1164     pub fn set_trace_macros(&mut self, x: bool) {
1165         self.ecfg.trace_mac = x
1166     }
1167     pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1168         let def_site = self.with_def_site_ctxt(DUMMY_SP);
1169         iter::once(Ident::new(kw::DollarCrate, def_site))
1170             .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1171             .collect()
1172     }
1173     pub fn def_site_path(&self, components: &[Symbol]) -> Vec<Ident> {
1174         let def_site = self.with_def_site_ctxt(DUMMY_SP);
1175         components.iter().map(|&s| Ident::new(s, def_site)).collect()
1176     }
1177
1178     pub fn check_unused_macros(&mut self) {
1179         self.resolver.check_unused_macros();
1180     }
1181 }
1182
1183 /// Resolves a `path` mentioned inside Rust code, returning an absolute path.
1184 ///
1185 /// This unifies the logic used for resolving `include_X!`.
1186 pub fn resolve_path(
1187     parse_sess: &ParseSess,
1188     path: impl Into<PathBuf>,
1189     span: Span,
1190 ) -> PResult<'_, PathBuf> {
1191     let path = path.into();
1192
1193     // Relative paths are resolved relative to the file in which they are found
1194     // after macro expansion (that is, they are unhygienic).
1195     if !path.is_absolute() {
1196         let callsite = span.source_callsite();
1197         let mut result = match parse_sess.source_map().span_to_filename(callsite) {
1198             FileName::Real(name) => name
1199                 .into_local_path()
1200                 .expect("attempting to resolve a file path in an external file"),
1201             FileName::DocTest(path, _) => path,
1202             other => {
1203                 return Err(parse_sess.span_diagnostic.struct_span_err(
1204                     span,
1205                     &format!(
1206                         "cannot resolve relative path in non-file source `{}`",
1207                         parse_sess.source_map().filename_for_diagnostics(&other)
1208                     ),
1209                 ));
1210             }
1211         };
1212         result.pop();
1213         result.push(path);
1214         Ok(result)
1215     } else {
1216         Ok(path)
1217     }
1218 }
1219
1220 /// Extracts a string literal from the macro expanded version of `expr`,
1221 /// returning a diagnostic error of `err_msg` if `expr` is not a string literal.
1222 /// The returned bool indicates whether an applicable suggestion has already been
1223 /// added to the diagnostic to avoid emitting multiple suggestions. `Err(None)`
1224 /// indicates that an ast error was encountered.
1225 pub fn expr_to_spanned_string<'a>(
1226     cx: &'a mut ExtCtxt<'_>,
1227     expr: P<ast::Expr>,
1228     err_msg: &str,
1229 ) -> Result<(Symbol, ast::StrStyle, Span), Option<(DiagnosticBuilder<'a, ErrorGuaranteed>, bool)>> {
1230     // Perform eager expansion on the expression.
1231     // We want to be able to handle e.g., `concat!("foo", "bar")`.
1232     let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1233
1234     Err(match expr.kind {
1235         ast::ExprKind::Lit(token_lit) => match ast::LitKind::from_token_lit(token_lit) {
1236             Ok(ast::LitKind::Str(s, style)) => return Ok((s, style, expr.span)),
1237             Ok(ast::LitKind::ByteStr(_)) => {
1238                 let mut err = cx.struct_span_err(expr.span, err_msg);
1239                 let span = expr.span.shrink_to_lo();
1240                 err.span_suggestion(
1241                     span.with_hi(span.lo() + BytePos(1)),
1242                     "consider removing the leading `b`",
1243                     "",
1244                     Applicability::MaybeIncorrect,
1245                 );
1246                 Some((err, true))
1247             }
1248             Ok(ast::LitKind::Err) => None,
1249             Err(err) => {
1250                 report_lit_error(&cx.sess.parse_sess, err, token_lit, expr.span);
1251                 None
1252             }
1253             _ => Some((cx.struct_span_err(expr.span, err_msg), false)),
1254         },
1255         ast::ExprKind::Err => None,
1256         _ => Some((cx.struct_span_err(expr.span, err_msg), false)),
1257     })
1258 }
1259
1260 /// Extracts a string literal from the macro expanded version of `expr`,
1261 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1262 /// compilation on error, merely emits a non-fatal error and returns `None`.
1263 pub fn expr_to_string(
1264     cx: &mut ExtCtxt<'_>,
1265     expr: P<ast::Expr>,
1266     err_msg: &str,
1267 ) -> Option<(Symbol, ast::StrStyle)> {
1268     expr_to_spanned_string(cx, expr, err_msg)
1269         .map_err(|err| {
1270             err.map(|(mut err, _)| {
1271                 err.emit();
1272             })
1273         })
1274         .ok()
1275         .map(|(symbol, style, _)| (symbol, style))
1276 }
1277
1278 /// Non-fatally assert that `tts` is empty. Note that this function
1279 /// returns even when `tts` is non-empty, macros that *need* to stop
1280 /// compilation should call
1281 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1282 /// done as rarely as possible).
1283 pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) {
1284     if !tts.is_empty() {
1285         cx.span_err(sp, &format!("{} takes no arguments", name));
1286     }
1287 }
1288
1289 /// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`.
1290 pub fn parse_expr(p: &mut parser::Parser<'_>) -> Option<P<ast::Expr>> {
1291     match p.parse_expr() {
1292         Ok(e) => return Some(e),
1293         Err(mut err) => {
1294             err.emit();
1295         }
1296     }
1297     while p.token != token::Eof {
1298         p.bump();
1299     }
1300     None
1301 }
1302
1303 /// Interpreting `tts` as a comma-separated sequence of expressions,
1304 /// expect exactly one string literal, or emit an error and return `None`.
1305 pub fn get_single_str_from_tts(
1306     cx: &mut ExtCtxt<'_>,
1307     sp: Span,
1308     tts: TokenStream,
1309     name: &str,
1310 ) -> Option<Symbol> {
1311     let mut p = cx.new_parser_from_tts(tts);
1312     if p.token == token::Eof {
1313         cx.span_err(sp, &format!("{} takes 1 argument", name));
1314         return None;
1315     }
1316     let ret = parse_expr(&mut p)?;
1317     let _ = p.eat(&token::Comma);
1318
1319     if p.token != token::Eof {
1320         cx.span_err(sp, &format!("{} takes 1 argument", name));
1321     }
1322     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s)
1323 }
1324
1325 /// Extracts comma-separated expressions from `tts`.
1326 /// On error, emit it, and return `None`.
1327 pub fn get_exprs_from_tts(
1328     cx: &mut ExtCtxt<'_>,
1329     sp: Span,
1330     tts: TokenStream,
1331 ) -> Option<Vec<P<ast::Expr>>> {
1332     let mut p = cx.new_parser_from_tts(tts);
1333     let mut es = Vec::new();
1334     while p.token != token::Eof {
1335         let expr = parse_expr(&mut p)?;
1336
1337         // Perform eager expansion on the expression.
1338         // We want to be able to handle e.g., `concat!("foo", "bar")`.
1339         let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1340
1341         es.push(expr);
1342         if p.eat(&token::Comma) {
1343             continue;
1344         }
1345         if p.token != token::Eof {
1346             cx.span_err(sp, "expected token: `,`");
1347             return None;
1348         }
1349     }
1350     Some(es)
1351 }
1352
1353 pub fn parse_macro_name_and_helper_attrs(
1354     diag: &rustc_errors::Handler,
1355     attr: &Attribute,
1356     descr: &str,
1357 ) -> Option<(Symbol, Vec<Symbol>)> {
1358     // Once we've located the `#[proc_macro_derive]` attribute, verify
1359     // that it's of the form `#[proc_macro_derive(Foo)]` or
1360     // `#[proc_macro_derive(Foo, attributes(A, ..))]`
1361     let list = attr.meta_item_list()?;
1362     if list.len() != 1 && list.len() != 2 {
1363         diag.span_err(attr.span, "attribute must have either one or two arguments");
1364         return None;
1365     }
1366     let Some(trait_attr) = list[0].meta_item() else {
1367         diag.span_err(list[0].span(), "not a meta item");
1368         return None;
1369     };
1370     let trait_ident = match trait_attr.ident() {
1371         Some(trait_ident) if trait_attr.is_word() => trait_ident,
1372         _ => {
1373             diag.span_err(trait_attr.span, "must only be one word");
1374             return None;
1375         }
1376     };
1377
1378     if !trait_ident.name.can_be_raw() {
1379         diag.span_err(
1380             trait_attr.span,
1381             &format!("`{}` cannot be a name of {} macro", trait_ident, descr),
1382         );
1383     }
1384
1385     let attributes_attr = list.get(1);
1386     let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
1387         if !attr.has_name(sym::attributes) {
1388             diag.span_err(attr.span(), "second argument must be `attributes`");
1389         }
1390         attr.meta_item_list()
1391             .unwrap_or_else(|| {
1392                 diag.span_err(attr.span(), "attribute must be of form: `attributes(foo, bar)`");
1393                 &[]
1394             })
1395             .iter()
1396             .filter_map(|attr| {
1397                 let Some(attr) = attr.meta_item() else {
1398                     diag.span_err(attr.span(), "not a meta item");
1399                     return None;
1400                 };
1401
1402                 let ident = match attr.ident() {
1403                     Some(ident) if attr.is_word() => ident,
1404                     _ => {
1405                         diag.span_err(attr.span, "must only be one word");
1406                         return None;
1407                     }
1408                 };
1409                 if !ident.name.can_be_raw() {
1410                     diag.span_err(
1411                         attr.span,
1412                         &format!("`{}` cannot be a name of derive helper attribute", ident),
1413                     );
1414                 }
1415
1416                 Some(ident.name)
1417             })
1418             .collect()
1419     } else {
1420         Vec::new()
1421     };
1422
1423     Some((trait_ident.name, proc_attrs))
1424 }
1425
1426 /// This nonterminal looks like some specific enums from
1427 /// `proc-macro-hack` and `procedural-masquerade` crates.
1428 /// We need to maintain some special pretty-printing behavior for them due to incorrect
1429 /// asserts in old versions of those crates and their wide use in the ecosystem.
1430 /// See issue #73345 for more details.
1431 /// FIXME(#73933): Remove this eventually.
1432 fn pretty_printing_compatibility_hack(item: &Item, sess: &ParseSess) -> bool {
1433     let name = item.ident.name;
1434     if name == sym::ProceduralMasqueradeDummyType {
1435         if let ast::ItemKind::Enum(enum_def, _) = &item.kind {
1436             if let [variant] = &*enum_def.variants {
1437                 if variant.ident.name == sym::Input {
1438                     let filename = sess.source_map().span_to_filename(item.ident.span);
1439                     if let FileName::Real(RealFileName::LocalPath(path)) = filename {
1440                         if let Some(c) = path
1441                             .components()
1442                             .flat_map(|c| c.as_os_str().to_str())
1443                             .find(|c| c.starts_with("rental") || c.starts_with("allsorts-rental"))
1444                         {
1445                             let crate_matches = if c.starts_with("allsorts-rental") {
1446                                 true
1447                             } else {
1448                                 let mut version = c.trim_start_matches("rental-").split('.');
1449                                 version.next() == Some("0")
1450                                     && version.next() == Some("5")
1451                                     && version
1452                                         .next()
1453                                         .and_then(|c| c.parse::<u32>().ok())
1454                                         .map_or(false, |v| v < 6)
1455                             };
1456
1457                             if crate_matches {
1458                                 sess.buffer_lint_with_diagnostic(
1459                                         &PROC_MACRO_BACK_COMPAT,
1460                                         item.ident.span,
1461                                         ast::CRATE_NODE_ID,
1462                                         "using an old version of `rental`",
1463                                         BuiltinLintDiagnostics::ProcMacroBackCompat(
1464                                         "older versions of the `rental` crate will stop compiling in future versions of Rust; \
1465                                         please update to `rental` v0.5.6, or switch to one of the `rental` alternatives".to_string()
1466                                         )
1467                                     );
1468                                 return true;
1469                             }
1470                         }
1471                     }
1472                 }
1473             }
1474         }
1475     }
1476     false
1477 }
1478
1479 pub(crate) fn ann_pretty_printing_compatibility_hack(ann: &Annotatable, sess: &ParseSess) -> bool {
1480     let item = match ann {
1481         Annotatable::Item(item) => item,
1482         Annotatable::Stmt(stmt) => match &stmt.kind {
1483             ast::StmtKind::Item(item) => item,
1484             _ => return false,
1485         },
1486         _ => return false,
1487     };
1488     pretty_printing_compatibility_hack(item, sess)
1489 }
1490
1491 pub(crate) fn nt_pretty_printing_compatibility_hack(nt: &Nonterminal, sess: &ParseSess) -> bool {
1492     let item = match nt {
1493         Nonterminal::NtItem(item) => item,
1494         Nonterminal::NtStmt(stmt) => match &stmt.kind {
1495             ast::StmtKind::Item(item) => item,
1496             _ => return false,
1497         },
1498         _ => return false,
1499     };
1500     pretty_printing_compatibility_hack(item, sess)
1501 }