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