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