]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/base.rs
Auto merge of #61735 - eddyb:must-use-life, r=oli-obk
[rust.git] / src / libsyntax / ext / base.rs
1 pub use SyntaxExtension::*;
2
3 use crate::ast::{self, Attribute, Name, PatKind, MetaItem};
4 use crate::attr::HasAttrs;
5 use crate::source_map::{SourceMap, Spanned, respan};
6 use crate::edition::Edition;
7 use crate::ext::expand::{self, AstFragment, Invocation};
8 use crate::ext::hygiene::{Mark, SyntaxContext, Transparency};
9 use crate::mut_visit::{self, MutVisitor};
10 use crate::parse::{self, parser, DirectoryOwnership};
11 use crate::parse::token;
12 use crate::ptr::P;
13 use crate::symbol::{kw, sym, Ident, Symbol};
14 use crate::{ThinVec, MACRO_ARGUMENTS};
15 use crate::tokenstream::{self, TokenStream};
16
17 use errors::{DiagnosticBuilder, DiagnosticId};
18 use smallvec::{smallvec, SmallVec};
19 use syntax_pos::{Span, MultiSpan, DUMMY_SP};
20
21 use rustc_data_structures::fx::FxHashMap;
22 use rustc_data_structures::sync::{self, Lrc};
23 use std::iter;
24 use std::path::PathBuf;
25 use std::rc::Rc;
26 use std::default::Default;
27
28
29 #[derive(Debug,Clone)]
30 pub enum Annotatable {
31     Item(P<ast::Item>),
32     TraitItem(P<ast::TraitItem>),
33     ImplItem(P<ast::ImplItem>),
34     ForeignItem(P<ast::ForeignItem>),
35     Stmt(P<ast::Stmt>),
36     Expr(P<ast::Expr>),
37 }
38
39 impl HasAttrs for Annotatable {
40     fn attrs(&self) -> &[Attribute] {
41         match *self {
42             Annotatable::Item(ref item) => &item.attrs,
43             Annotatable::TraitItem(ref trait_item) => &trait_item.attrs,
44             Annotatable::ImplItem(ref impl_item) => &impl_item.attrs,
45             Annotatable::ForeignItem(ref foreign_item) => &foreign_item.attrs,
46             Annotatable::Stmt(ref stmt) => stmt.attrs(),
47             Annotatable::Expr(ref expr) => &expr.attrs,
48         }
49     }
50
51     fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
52         match self {
53             Annotatable::Item(item) => item.visit_attrs(f),
54             Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
55             Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
56             Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
57             Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
58             Annotatable::Expr(expr) => expr.visit_attrs(f),
59         }
60     }
61 }
62
63 impl Annotatable {
64     pub fn span(&self) -> Span {
65         match *self {
66             Annotatable::Item(ref item) => item.span,
67             Annotatable::TraitItem(ref trait_item) => trait_item.span,
68             Annotatable::ImplItem(ref impl_item) => impl_item.span,
69             Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
70             Annotatable::Stmt(ref stmt) => stmt.span,
71             Annotatable::Expr(ref expr) => expr.span,
72         }
73     }
74
75     pub fn expect_item(self) -> P<ast::Item> {
76         match self {
77             Annotatable::Item(i) => i,
78             _ => panic!("expected Item")
79         }
80     }
81
82     pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
83         where F: FnMut(P<ast::Item>) -> P<ast::Item>,
84               G: FnMut(Annotatable) -> Annotatable
85     {
86         match self {
87             Annotatable::Item(i) => Annotatable::Item(f(i)),
88             _ => or(self)
89         }
90     }
91
92     pub fn expect_trait_item(self) -> ast::TraitItem {
93         match self {
94             Annotatable::TraitItem(i) => i.into_inner(),
95             _ => panic!("expected Item")
96         }
97     }
98
99     pub fn expect_impl_item(self) -> ast::ImplItem {
100         match self {
101             Annotatable::ImplItem(i) => i.into_inner(),
102             _ => panic!("expected Item")
103         }
104     }
105
106     pub fn expect_foreign_item(self) -> ast::ForeignItem {
107         match self {
108             Annotatable::ForeignItem(i) => i.into_inner(),
109             _ => panic!("expected foreign item")
110         }
111     }
112
113     pub fn expect_stmt(self) -> ast::Stmt {
114         match self {
115             Annotatable::Stmt(stmt) => stmt.into_inner(),
116             _ => panic!("expected statement"),
117         }
118     }
119
120     pub fn expect_expr(self) -> P<ast::Expr> {
121         match self {
122             Annotatable::Expr(expr) => expr,
123             _ => panic!("expected expression"),
124         }
125     }
126
127     pub fn derive_allowed(&self) -> bool {
128         match *self {
129             Annotatable::Item(ref item) => match item.node {
130                 ast::ItemKind::Struct(..) |
131                 ast::ItemKind::Enum(..) |
132                 ast::ItemKind::Union(..) => true,
133                 _ => false,
134             },
135             _ => false,
136         }
137     }
138 }
139
140 // A more flexible ItemDecorator.
141 pub trait MultiItemDecorator {
142     fn expand(&self,
143               ecx: &mut ExtCtxt<'_>,
144               sp: Span,
145               meta_item: &ast::MetaItem,
146               item: &Annotatable,
147               push: &mut dyn FnMut(Annotatable));
148 }
149
150 impl<F> MultiItemDecorator for F
151     where F : Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, &Annotatable, &mut dyn FnMut(Annotatable))
152 {
153     fn expand(&self,
154               ecx: &mut ExtCtxt<'_>,
155               sp: Span,
156               meta_item: &ast::MetaItem,
157               item: &Annotatable,
158               push: &mut dyn FnMut(Annotatable)) {
159         (*self)(ecx, sp, meta_item, item, push)
160     }
161 }
162
163 // `meta_item` is the annotation, and `item` is the item being modified.
164 // FIXME Decorators should follow the same pattern too.
165 pub trait MultiItemModifier {
166     fn expand(&self,
167               ecx: &mut ExtCtxt<'_>,
168               span: Span,
169               meta_item: &ast::MetaItem,
170               item: Annotatable)
171               -> Vec<Annotatable>;
172 }
173
174 impl<F, T> MultiItemModifier for F
175     where F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> T,
176           T: Into<Vec<Annotatable>>,
177 {
178     fn expand(&self,
179               ecx: &mut ExtCtxt<'_>,
180               span: Span,
181               meta_item: &ast::MetaItem,
182               item: Annotatable)
183               -> Vec<Annotatable> {
184         (*self)(ecx, span, meta_item, item).into()
185     }
186 }
187
188 impl Into<Vec<Annotatable>> for Annotatable {
189     fn into(self) -> Vec<Annotatable> {
190         vec![self]
191     }
192 }
193
194 pub trait ProcMacro {
195     fn expand<'cx>(&self,
196                    ecx: &'cx mut ExtCtxt<'_>,
197                    span: Span,
198                    ts: TokenStream)
199                    -> TokenStream;
200 }
201
202 impl<F> ProcMacro for F
203     where F: Fn(TokenStream) -> TokenStream
204 {
205     fn expand<'cx>(&self,
206                    _ecx: &'cx mut ExtCtxt<'_>,
207                    _span: Span,
208                    ts: TokenStream)
209                    -> TokenStream {
210         // FIXME setup implicit context in TLS before calling self.
211         (*self)(ts)
212     }
213 }
214
215 pub trait AttrProcMacro {
216     fn expand<'cx>(&self,
217                    ecx: &'cx mut ExtCtxt<'_>,
218                    span: Span,
219                    annotation: TokenStream,
220                    annotated: TokenStream)
221                    -> TokenStream;
222 }
223
224 impl<F> AttrProcMacro for F
225     where F: Fn(TokenStream, TokenStream) -> TokenStream
226 {
227     fn expand<'cx>(&self,
228                    _ecx: &'cx mut ExtCtxt<'_>,
229                    _span: Span,
230                    annotation: TokenStream,
231                    annotated: TokenStream)
232                    -> TokenStream {
233         // FIXME setup implicit context in TLS before calling self.
234         (*self)(annotation, annotated)
235     }
236 }
237
238 /// Represents a thing that maps token trees to Macro Results
239 pub trait TTMacroExpander {
240     fn expand<'cx>(
241         &self,
242         ecx: &'cx mut ExtCtxt<'_>,
243         span: Span,
244         input: TokenStream,
245         def_span: Option<Span>,
246     ) -> Box<dyn MacResult+'cx>;
247 }
248
249 pub type MacroExpanderFn =
250     for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, &[tokenstream::TokenTree])
251                 -> Box<dyn MacResult+'cx>;
252
253 impl<F> TTMacroExpander for F
254     where F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, &[tokenstream::TokenTree])
255     -> Box<dyn MacResult+'cx>
256 {
257     fn expand<'cx>(
258         &self,
259         ecx: &'cx mut ExtCtxt<'_>,
260         span: Span,
261         input: TokenStream,
262         _def_span: Option<Span>,
263     ) -> Box<dyn MacResult+'cx> {
264         struct AvoidInterpolatedIdents;
265
266         impl MutVisitor for AvoidInterpolatedIdents {
267             fn visit_tt(&mut self, tt: &mut tokenstream::TokenTree) {
268                 if let tokenstream::TokenTree::Token(token) = tt {
269                     if let token::Interpolated(nt) = &token.kind {
270                         if let token::NtIdent(ident, is_raw) = **nt {
271                             *tt = tokenstream::TokenTree::token(
272                                 token::Ident(ident.name, is_raw), ident.span
273                             );
274                         }
275                     }
276                 }
277                 mut_visit::noop_visit_tt(tt, self)
278             }
279
280             fn visit_mac(&mut self, mac: &mut ast::Mac) {
281                 mut_visit::noop_visit_mac(mac, self)
282             }
283         }
284
285         let input: Vec<_> =
286             input.trees().map(|mut tt| { AvoidInterpolatedIdents.visit_tt(&mut tt); tt }).collect();
287         (*self)(ecx, span, &input)
288     }
289 }
290
291 pub trait IdentMacroExpander {
292     fn expand<'cx>(&self,
293                    cx: &'cx mut ExtCtxt<'_>,
294                    sp: Span,
295                    ident: ast::Ident,
296                    token_tree: Vec<tokenstream::TokenTree>)
297                    -> Box<dyn MacResult+'cx>;
298 }
299
300 pub type IdentMacroExpanderFn =
301     for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, ast::Ident, Vec<tokenstream::TokenTree>)
302                 -> Box<dyn MacResult+'cx>;
303
304 impl<F> IdentMacroExpander for F
305     where F : for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, ast::Ident,
306                           Vec<tokenstream::TokenTree>) -> Box<dyn MacResult+'cx>
307 {
308     fn expand<'cx>(&self,
309                    cx: &'cx mut ExtCtxt<'_>,
310                    sp: Span,
311                    ident: ast::Ident,
312                    token_tree: Vec<tokenstream::TokenTree>)
313                    -> Box<dyn MacResult+'cx>
314     {
315         (*self)(cx, sp, ident, token_tree)
316     }
317 }
318
319 // Use a macro because forwarding to a simple function has type system issues
320 macro_rules! make_stmts_default {
321     ($me:expr) => {
322         $me.make_expr().map(|e| smallvec![ast::Stmt {
323             id: ast::DUMMY_NODE_ID,
324             span: e.span,
325             node: ast::StmtKind::Expr(e),
326         }])
327     }
328 }
329
330 /// The result of a macro expansion. The return values of the various
331 /// methods are spliced into the AST at the callsite of the macro.
332 pub trait MacResult {
333     /// Creates an expression.
334     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
335         None
336     }
337     /// Creates zero or more items.
338     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
339         None
340     }
341
342     /// Creates zero or more impl items.
343     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
344         None
345     }
346
347     /// Creates zero or more trait items.
348     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
349         None
350     }
351
352     /// Creates zero or more items in an `extern {}` block
353     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> { None }
354
355     /// Creates a pattern.
356     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
357         None
358     }
359
360     /// Creates zero or more statements.
361     ///
362     /// By default this attempts to create an expression statement,
363     /// returning None if that fails.
364     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
365         make_stmts_default!(self)
366     }
367
368     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
369         None
370     }
371 }
372
373 macro_rules! make_MacEager {
374     ( $( $fld:ident: $t:ty, )* ) => {
375         /// `MacResult` implementation for the common case where you've already
376         /// built each form of AST that you might return.
377         #[derive(Default)]
378         pub struct MacEager {
379             $(
380                 pub $fld: Option<$t>,
381             )*
382         }
383
384         impl MacEager {
385             $(
386                 pub fn $fld(v: $t) -> Box<dyn MacResult> {
387                     Box::new(MacEager {
388                         $fld: Some(v),
389                         ..Default::default()
390                     })
391                 }
392             )*
393         }
394     }
395 }
396
397 make_MacEager! {
398     expr: P<ast::Expr>,
399     pat: P<ast::Pat>,
400     items: SmallVec<[P<ast::Item>; 1]>,
401     impl_items: SmallVec<[ast::ImplItem; 1]>,
402     trait_items: SmallVec<[ast::TraitItem; 1]>,
403     foreign_items: SmallVec<[ast::ForeignItem; 1]>,
404     stmts: SmallVec<[ast::Stmt; 1]>,
405     ty: P<ast::Ty>,
406 }
407
408 impl MacResult for MacEager {
409     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
410         self.expr
411     }
412
413     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
414         self.items
415     }
416
417     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
418         self.impl_items
419     }
420
421     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
422         self.trait_items
423     }
424
425     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
426         self.foreign_items
427     }
428
429     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
430         match self.stmts.as_ref().map_or(0, |s| s.len()) {
431             0 => make_stmts_default!(self),
432             _ => self.stmts,
433         }
434     }
435
436     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
437         if let Some(p) = self.pat {
438             return Some(p);
439         }
440         if let Some(e) = self.expr {
441             if let ast::ExprKind::Lit(_) = e.node {
442                 return Some(P(ast::Pat {
443                     id: ast::DUMMY_NODE_ID,
444                     span: e.span,
445                     node: PatKind::Lit(e),
446                 }));
447             }
448         }
449         None
450     }
451
452     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
453         self.ty
454     }
455 }
456
457 /// Fill-in macro expansion result, to allow compilation to continue
458 /// after hitting errors.
459 #[derive(Copy, Clone)]
460 pub struct DummyResult {
461     expr_only: bool,
462     is_error: bool,
463     span: Span,
464 }
465
466 impl DummyResult {
467     /// Creates a default MacResult that can be anything.
468     ///
469     /// Use this as a return value after hitting any errors and
470     /// calling `span_err`.
471     pub fn any(span: Span) -> Box<dyn MacResult+'static> {
472         Box::new(DummyResult { expr_only: false, is_error: true, span })
473     }
474
475     /// Same as `any`, but must be a valid fragment, not error.
476     pub fn any_valid(span: Span) -> Box<dyn MacResult+'static> {
477         Box::new(DummyResult { expr_only: false, is_error: false, span })
478     }
479
480     /// Creates a default MacResult that can only be an expression.
481     ///
482     /// Use this for macros that must expand to an expression, so even
483     /// if an error is encountered internally, the user will receive
484     /// an error that they also used it in the wrong place.
485     pub fn expr(span: Span) -> Box<dyn MacResult+'static> {
486         Box::new(DummyResult { expr_only: true, is_error: true, span })
487     }
488
489     /// A plain dummy expression.
490     pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
491         P(ast::Expr {
492             id: ast::DUMMY_NODE_ID,
493             node: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
494             span: sp,
495             attrs: ThinVec::new(),
496         })
497     }
498
499     /// A plain dummy pattern.
500     pub fn raw_pat(sp: Span) -> ast::Pat {
501         ast::Pat {
502             id: ast::DUMMY_NODE_ID,
503             node: PatKind::Wild,
504             span: sp,
505         }
506     }
507
508     /// A plain dummy type.
509     pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
510         P(ast::Ty {
511             id: ast::DUMMY_NODE_ID,
512             node: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
513             span: sp
514         })
515     }
516 }
517
518 impl MacResult for DummyResult {
519     fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
520         Some(DummyResult::raw_expr(self.span, self.is_error))
521     }
522
523     fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
524         Some(P(DummyResult::raw_pat(self.span)))
525     }
526
527     fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
528         // this code needs a comment... why not always just return the Some() ?
529         if self.expr_only {
530             None
531         } else {
532             Some(SmallVec::new())
533         }
534     }
535
536     fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
537         if self.expr_only {
538             None
539         } else {
540             Some(SmallVec::new())
541         }
542     }
543
544     fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
545         if self.expr_only {
546             None
547         } else {
548             Some(SmallVec::new())
549         }
550     }
551
552     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
553         if self.expr_only {
554             None
555         } else {
556             Some(SmallVec::new())
557         }
558     }
559
560     fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
561         Some(smallvec![ast::Stmt {
562             id: ast::DUMMY_NODE_ID,
563             node: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
564             span: self.span,
565         }])
566     }
567
568     fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
569         Some(DummyResult::raw_ty(self.span, self.is_error))
570     }
571 }
572
573 pub type BuiltinDeriveFn =
574     for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, &MetaItem, &Annotatable, &mut dyn FnMut(Annotatable));
575
576 /// Represents different kinds of macro invocations that can be resolved.
577 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
578 pub enum MacroKind {
579     /// A bang macro - foo!()
580     Bang,
581     /// An attribute macro - #[foo]
582     Attr,
583     /// A derive attribute macro - #[derive(Foo)]
584     Derive,
585     /// A view of a procedural macro from the same crate that defines it.
586     ProcMacroStub,
587 }
588
589 impl MacroKind {
590     pub fn descr(self) -> &'static str {
591         match self {
592             MacroKind::Bang => "macro",
593             MacroKind::Attr => "attribute macro",
594             MacroKind::Derive => "derive macro",
595             MacroKind::ProcMacroStub => "crate-local procedural macro",
596         }
597     }
598
599     pub fn article(self) -> &'static str {
600         match self {
601             MacroKind::Attr => "an",
602             _ => "a",
603         }
604     }
605 }
606
607 /// An enum representing the different kinds of syntax extensions.
608 pub enum SyntaxExtension {
609     /// A trivial "extension" that does nothing, only keeps the attribute and marks it as known.
610     NonMacroAttr { mark_used: bool },
611
612     /// A syntax extension that is attached to an item and creates new items
613     /// based upon it.
614     ///
615     /// `#[derive(...)]` is a `MultiItemDecorator`.
616     ///
617     /// Prefer ProcMacro or MultiModifier since they are more flexible.
618     MultiDecorator(Box<dyn MultiItemDecorator + sync::Sync + sync::Send>),
619
620     /// A syntax extension that is attached to an item and modifies it
621     /// in-place. Also allows decoration, i.e., creating new items.
622     MultiModifier(Box<dyn MultiItemModifier + sync::Sync + sync::Send>),
623
624     /// A function-like procedural macro. TokenStream -> TokenStream.
625     ProcMacro {
626         expander: Box<dyn ProcMacro + sync::Sync + sync::Send>,
627         /// Whitelist of unstable features that are treated as stable inside this macro
628         allow_internal_unstable: Option<Lrc<[Symbol]>>,
629         edition: Edition,
630     },
631
632     /// An attribute-like procedural macro. TokenStream, TokenStream -> TokenStream.
633     /// The first TokenSteam is the attribute, the second is the annotated item.
634     /// Allows modification of the input items and adding new items, similar to
635     /// MultiModifier, but uses TokenStreams, rather than AST nodes.
636     AttrProcMacro(Box<dyn AttrProcMacro + sync::Sync + sync::Send>, Edition),
637
638     /// A normal, function-like syntax extension.
639     ///
640     /// `bytes!` is a `NormalTT`.
641     NormalTT {
642         expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
643         def_info: Option<(ast::NodeId, Span)>,
644         /// Whether the contents of the macro can
645         /// directly use `#[unstable]` things.
646         ///
647         /// Only allows things that require a feature gate in the given whitelist
648         allow_internal_unstable: Option<Lrc<[Symbol]>>,
649         /// Whether the contents of the macro can use `unsafe`
650         /// without triggering the `unsafe_code` lint.
651         allow_internal_unsafe: bool,
652         /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
653         /// for a given macro.
654         local_inner_macros: bool,
655         /// The macro's feature name if it is unstable, and the stability feature
656         unstable_feature: Option<(Symbol, u32)>,
657         /// Edition of the crate in which the macro is defined
658         edition: Edition,
659     },
660
661     /// A function-like syntax extension that has an extra ident before
662     /// the block.
663     IdentTT {
664         expander: Box<dyn IdentMacroExpander + sync::Sync + sync::Send>,
665         span: Option<Span>,
666         allow_internal_unstable: Option<Lrc<[Symbol]>>,
667     },
668
669     /// An attribute-like procedural macro. TokenStream -> TokenStream.
670     /// The input is the annotated item.
671     /// Allows generating code to implement a Trait for a given struct
672     /// or enum item.
673     ProcMacroDerive(Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
674                     Vec<Symbol> /* inert attribute names */, Edition),
675
676     /// An attribute-like procedural macro that derives a builtin trait.
677     BuiltinDerive(BuiltinDeriveFn),
678
679     /// A declarative macro, e.g., `macro m() {}`.
680     DeclMacro {
681         expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
682         def_info: Option<(ast::NodeId, Span)>,
683         is_transparent: bool,
684         edition: Edition,
685     }
686 }
687
688 impl SyntaxExtension {
689     /// Returns which kind of macro calls this syntax extension.
690     pub fn kind(&self) -> MacroKind {
691         match *self {
692             SyntaxExtension::DeclMacro { .. } |
693             SyntaxExtension::NormalTT { .. } |
694             SyntaxExtension::IdentTT { .. } |
695             SyntaxExtension::ProcMacro { .. } =>
696                 MacroKind::Bang,
697             SyntaxExtension::NonMacroAttr { .. } |
698             SyntaxExtension::MultiDecorator(..) |
699             SyntaxExtension::MultiModifier(..) |
700             SyntaxExtension::AttrProcMacro(..) =>
701                 MacroKind::Attr,
702             SyntaxExtension::ProcMacroDerive(..) |
703             SyntaxExtension::BuiltinDerive(..) =>
704                 MacroKind::Derive,
705         }
706     }
707
708     pub fn default_transparency(&self) -> Transparency {
709         match *self {
710             SyntaxExtension::ProcMacro { .. } |
711             SyntaxExtension::AttrProcMacro(..) |
712             SyntaxExtension::ProcMacroDerive(..) |
713             SyntaxExtension::DeclMacro { is_transparent: false, .. } => Transparency::Opaque,
714             SyntaxExtension::DeclMacro { is_transparent: true, .. } => Transparency::Transparent,
715             _ => Transparency::SemiTransparent,
716         }
717     }
718
719     pub fn edition(&self, default_edition: Edition) -> Edition {
720         match *self {
721             SyntaxExtension::NormalTT { edition, .. } |
722             SyntaxExtension::DeclMacro { edition, .. } |
723             SyntaxExtension::ProcMacro { edition, .. } |
724             SyntaxExtension::AttrProcMacro(.., edition) |
725             SyntaxExtension::ProcMacroDerive(.., edition) => edition,
726             // Unstable legacy stuff
727             SyntaxExtension::NonMacroAttr { .. } |
728             SyntaxExtension::IdentTT { .. } |
729             SyntaxExtension::MultiDecorator(..) |
730             SyntaxExtension::MultiModifier(..) |
731             SyntaxExtension::BuiltinDerive(..) => default_edition,
732         }
733     }
734 }
735
736 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
737
738 pub trait Resolver {
739     fn next_node_id(&mut self) -> ast::NodeId;
740
741     fn get_module_scope(&mut self, id: ast::NodeId) -> Mark;
742
743     fn resolve_dollar_crates(&mut self, fragment: &AstFragment);
744     fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
745                                             derives: &[Mark]);
746     fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>);
747
748     fn resolve_imports(&mut self);
749
750     fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
751                                 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy>;
752     fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
753                           derives_in_scope: Vec<ast::Path>, force: bool)
754                           -> Result<Lrc<SyntaxExtension>, Determinacy>;
755
756     fn check_unused_macros(&self);
757 }
758
759 #[derive(Copy, Clone, PartialEq, Debug)]
760 pub enum Determinacy {
761     Determined,
762     Undetermined,
763 }
764
765 impl Determinacy {
766     pub fn determined(determined: bool) -> Determinacy {
767         if determined { Determinacy::Determined } else { Determinacy::Undetermined }
768     }
769 }
770
771 pub struct DummyResolver;
772
773 impl Resolver for DummyResolver {
774     fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID }
775
776     fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() }
777
778     fn resolve_dollar_crates(&mut self, _fragment: &AstFragment) {}
779     fn visit_ast_fragment_with_placeholders(&mut self, _invoc: Mark, _fragment: &AstFragment,
780                                             _derives: &[Mark]) {}
781     fn add_builtin(&mut self, _ident: ast::Ident, _ext: Lrc<SyntaxExtension>) {}
782
783     fn resolve_imports(&mut self) {}
784     fn resolve_macro_invocation(&mut self, _invoc: &Invocation, _invoc_id: Mark, _force: bool)
785                                 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
786         Err(Determinacy::Determined)
787     }
788     fn resolve_macro_path(&mut self, _path: &ast::Path, _kind: MacroKind, _invoc_id: Mark,
789                           _derives_in_scope: Vec<ast::Path>, _force: bool)
790                           -> Result<Lrc<SyntaxExtension>, Determinacy> {
791         Err(Determinacy::Determined)
792     }
793     fn check_unused_macros(&self) {}
794 }
795
796 #[derive(Clone)]
797 pub struct ModuleData {
798     pub mod_path: Vec<ast::Ident>,
799     pub directory: PathBuf,
800 }
801
802 #[derive(Clone)]
803 pub struct ExpansionData {
804     pub mark: Mark,
805     pub depth: usize,
806     pub module: Rc<ModuleData>,
807     pub directory_ownership: DirectoryOwnership,
808     pub crate_span: Option<Span>,
809 }
810
811 /// One of these is made during expansion and incrementally updated as we go;
812 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
813 /// -> expn_info` of their expansion context stored into their span.
814 pub struct ExtCtxt<'a> {
815     pub parse_sess: &'a parse::ParseSess,
816     pub ecfg: expand::ExpansionConfig<'a>,
817     pub root_path: PathBuf,
818     pub resolver: &'a mut dyn Resolver,
819     pub current_expansion: ExpansionData,
820     pub expansions: FxHashMap<Span, Vec<String>>,
821 }
822
823 impl<'a> ExtCtxt<'a> {
824     pub fn new(parse_sess: &'a parse::ParseSess,
825                ecfg: expand::ExpansionConfig<'a>,
826                resolver: &'a mut dyn Resolver)
827                -> ExtCtxt<'a> {
828         ExtCtxt {
829             parse_sess,
830             ecfg,
831             root_path: PathBuf::new(),
832             resolver,
833             current_expansion: ExpansionData {
834                 mark: Mark::root(),
835                 depth: 0,
836                 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
837                 directory_ownership: DirectoryOwnership::Owned { relative: None },
838                 crate_span: None,
839             },
840             expansions: FxHashMap::default(),
841         }
842     }
843
844     /// Returns a `Folder` for deeply expanding all macros in an AST node.
845     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
846         expand::MacroExpander::new(self, false)
847     }
848
849     /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
850     /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
851     pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
852         expand::MacroExpander::new(self, true)
853     }
854
855     pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
856         parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect(), MACRO_ARGUMENTS)
857     }
858     pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() }
859     pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
860     pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
861     pub fn call_site(&self) -> Span {
862         match self.current_expansion.mark.expn_info() {
863             Some(expn_info) => expn_info.call_site,
864             None => DUMMY_SP,
865         }
866     }
867     pub fn backtrace(&self) -> SyntaxContext {
868         SyntaxContext::empty().apply_mark(self.current_expansion.mark)
869     }
870
871     /// Returns span for the macro which originally caused the current expansion to happen.
872     ///
873     /// Stops backtracing at include! boundary.
874     pub fn expansion_cause(&self) -> Option<Span> {
875         let mut ctxt = self.backtrace();
876         let mut last_macro = None;
877         loop {
878             if ctxt.outer_expn_info().map_or(None, |info| {
879                 if info.format.name() == sym::include {
880                     // Stop going up the backtrace once include! is encountered
881                     return None;
882                 }
883                 ctxt = info.call_site.ctxt();
884                 last_macro = Some(info.call_site);
885                 Some(())
886             }).is_none() {
887                 break
888             }
889         }
890         last_macro
891     }
892
893     pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
894                                                 sp: S,
895                                                 msg: &str)
896                                                 -> DiagnosticBuilder<'a> {
897         self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
898     }
899     pub fn struct_span_err<S: Into<MultiSpan>>(&self,
900                                                sp: S,
901                                                msg: &str)
902                                                -> DiagnosticBuilder<'a> {
903         self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
904     }
905     pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
906                                                  sp: S,
907                                                  msg: &str)
908                                                  -> DiagnosticBuilder<'a> {
909         self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
910     }
911
912     /// Emit `msg` attached to `sp`, and stop compilation immediately.
913     ///
914     /// `span_err` should be strongly preferred where-ever possible:
915     /// this should *only* be used when:
916     ///
917     /// - continuing has a high risk of flow-on errors (e.g., errors in
918     ///   declaring a macro would cause all uses of that macro to
919     ///   complain about "undefined macro"), or
920     /// - there is literally nothing else that can be done (however,
921     ///   in most cases one can construct a dummy expression/item to
922     ///   substitute; we never hit resolve/type-checking so the dummy
923     ///   value doesn't have to match anything)
924     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
925         self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
926     }
927
928     /// Emit `msg` attached to `sp`, without immediately stopping
929     /// compilation.
930     ///
931     /// Compilation will be stopped in the near future (at the end of
932     /// the macro expansion phase).
933     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
934         self.parse_sess.span_diagnostic.span_err(sp, msg);
935     }
936     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
937         self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
938     }
939     pub fn mut_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str)
940                         -> DiagnosticBuilder<'a> {
941         self.parse_sess.span_diagnostic.mut_span_err(sp, msg)
942     }
943     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
944         self.parse_sess.span_diagnostic.span_warn(sp, msg);
945     }
946     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
947         self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
948     }
949     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
950         self.parse_sess.span_diagnostic.span_bug(sp, msg);
951     }
952     pub fn trace_macros_diag(&mut self) {
953         for (sp, notes) in self.expansions.iter() {
954             let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
955             for note in notes {
956                 db.note(note);
957             }
958             db.emit();
959         }
960         // Fixme: does this result in errors?
961         self.expansions.clear();
962     }
963     pub fn bug(&self, msg: &str) -> ! {
964         self.parse_sess.span_diagnostic.bug(msg);
965     }
966     pub fn trace_macros(&self) -> bool {
967         self.ecfg.trace_mac
968     }
969     pub fn set_trace_macros(&mut self, x: bool) {
970         self.ecfg.trace_mac = x
971     }
972     pub fn ident_of(&self, st: &str) -> ast::Ident {
973         ast::Ident::from_str(st)
974     }
975     pub fn std_path(&self, components: &[Symbol]) -> Vec<ast::Ident> {
976         let def_site = DUMMY_SP.apply_mark(self.current_expansion.mark);
977         iter::once(Ident::new(kw::DollarCrate, def_site))
978             .chain(components.iter().map(|&s| Ident::with_empty_ctxt(s)))
979             .collect()
980     }
981     pub fn name_of(&self, st: &str) -> ast::Name {
982         Symbol::intern(st)
983     }
984
985     pub fn check_unused_macros(&self) {
986         self.resolver.check_unused_macros();
987     }
988 }
989
990 /// Extracts a string literal from the macro expanded version of `expr`,
991 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
992 /// compilation on error, merely emits a non-fatal error and returns `None`.
993 pub fn expr_to_spanned_string<'a>(
994     cx: &'a mut ExtCtxt<'_>,
995     mut expr: P<ast::Expr>,
996     err_msg: &str,
997 ) -> Result<Spanned<(Symbol, ast::StrStyle)>, Option<DiagnosticBuilder<'a>>> {
998     // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
999     expr.span = expr.span.apply_mark(cx.current_expansion.mark);
1000
1001     // we want to be able to handle e.g., `concat!("foo", "bar")`
1002     cx.expander().visit_expr(&mut expr);
1003     Err(match expr.node {
1004         ast::ExprKind::Lit(ref l) => match l.node {
1005             ast::LitKind::Str(s, style) => return Ok(respan(expr.span, (s, style))),
1006             ast::LitKind::Err(_) => None,
1007             _ => Some(cx.struct_span_err(l.span, err_msg))
1008         },
1009         ast::ExprKind::Err => None,
1010         _ => Some(cx.struct_span_err(expr.span, err_msg))
1011     })
1012 }
1013
1014 pub fn expr_to_string(cx: &mut ExtCtxt<'_>, expr: P<ast::Expr>, err_msg: &str)
1015                       -> Option<(Symbol, ast::StrStyle)> {
1016     expr_to_spanned_string(cx, expr, err_msg)
1017         .map_err(|err| err.map(|mut err| err.emit()))
1018         .ok()
1019         .map(|s| s.node)
1020 }
1021
1022 /// Non-fatally assert that `tts` is empty. Note that this function
1023 /// returns even when `tts` is non-empty, macros that *need* to stop
1024 /// compilation should call
1025 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1026 /// done as rarely as possible).
1027 pub fn check_zero_tts(cx: &ExtCtxt<'_>,
1028                       sp: Span,
1029                       tts: &[tokenstream::TokenTree],
1030                       name: &str) {
1031     if !tts.is_empty() {
1032         cx.span_err(sp, &format!("{} takes no arguments", name));
1033     }
1034 }
1035
1036 /// Interpreting `tts` as a comma-separated sequence of expressions,
1037 /// expect exactly one string literal, or emit an error and return `None`.
1038 pub fn get_single_str_from_tts(cx: &mut ExtCtxt<'_>,
1039                                sp: Span,
1040                                tts: &[tokenstream::TokenTree],
1041                                name: &str)
1042                                -> Option<String> {
1043     let mut p = cx.new_parser_from_tts(tts);
1044     if p.token == token::Eof {
1045         cx.span_err(sp, &format!("{} takes 1 argument", name));
1046         return None
1047     }
1048     let ret = panictry!(p.parse_expr());
1049     let _ = p.eat(&token::Comma);
1050
1051     if p.token != token::Eof {
1052         cx.span_err(sp, &format!("{} takes 1 argument", name));
1053     }
1054     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
1055         s.to_string()
1056     })
1057 }
1058
1059 /// Extracts comma-separated expressions from `tts`. If there is a
1060 /// parsing error, emit a non-fatal error and return `None`.
1061 pub fn get_exprs_from_tts(cx: &mut ExtCtxt<'_>,
1062                           sp: Span,
1063                           tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
1064     let mut p = cx.new_parser_from_tts(tts);
1065     let mut es = Vec::new();
1066     while p.token != token::Eof {
1067         let mut expr = panictry!(p.parse_expr());
1068         cx.expander().visit_expr(&mut expr);
1069         es.push(expr);
1070         if p.eat(&token::Comma) {
1071             continue;
1072         }
1073         if p.token != token::Eof {
1074             cx.span_err(sp, "expected token: `,`");
1075             return None;
1076         }
1077     }
1078     Some(es)
1079 }