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