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