]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/macros.rs
7733ce475e339529662808efc1f26bd04d521f96
[rust.git] / src / librustc_resolve / macros.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use {AmbiguityError, CrateLint, Resolver, ResolutionError, is_known_tool, resolve_error};
12 use {Module, ModuleKind, NameBinding, NameBindingKind, PathResult, ToNameBinding};
13 use ModuleOrUniformRoot;
14 use Namespace::{self, TypeNS, MacroNS};
15 use build_reduced_graph::{BuildReducedGraphVisitor, IsMacroExport};
16 use resolve_imports::ImportResolver;
17 use rustc::hir::def_id::{DefId, BUILTIN_MACROS_CRATE, CRATE_DEF_INDEX, DefIndex,
18                          DefIndexAddressSpace};
19 use rustc::hir::def::{Def, NonMacroAttrKind};
20 use rustc::hir::map::{self, DefCollector};
21 use rustc::{ty, lint};
22 use rustc::middle::cstore::CrateStore;
23 use syntax::ast::{self, Name, Ident};
24 use syntax::attr;
25 use syntax::errors::DiagnosticBuilder;
26 use syntax::ext::base::{self, Determinacy, MultiModifier, MultiDecorator};
27 use syntax::ext::base::{MacroKind, SyntaxExtension, Resolver as SyntaxResolver};
28 use syntax::ext::expand::{AstFragment, Invocation, InvocationKind};
29 use syntax::ext::hygiene::{self, Mark};
30 use syntax::ext::tt::macro_rules;
31 use syntax::feature_gate::{self, feature_err, emit_feature_err, is_builtin_attr_name, GateIssue};
32 use syntax::feature_gate::EXPLAIN_DERIVE_UNDERSCORE;
33 use syntax::fold::{self, Folder};
34 use syntax::parse::parser::PathStyle;
35 use syntax::parse::token::{self, Token};
36 use syntax::ptr::P;
37 use syntax::symbol::{Symbol, keywords};
38 use syntax::tokenstream::{TokenStream, TokenTree, Delimited, DelimSpan};
39 use syntax::util::lev_distance::find_best_match_for_name;
40 use syntax_pos::{Span, DUMMY_SP};
41 use errors::Applicability;
42
43 use std::cell::Cell;
44 use std::mem;
45 use rustc_data_structures::sync::Lrc;
46 use rustc_data_structures::small_vec::ExpectOne;
47
48 #[derive(Clone, Copy)]
49 crate struct FromPrelude(bool);
50
51 #[derive(Clone)]
52 pub struct InvocationData<'a> {
53     def_index: DefIndex,
54     /// Module in which the macro was invoked.
55     crate module: Cell<Module<'a>>,
56     /// Legacy scope in which the macro was invoked.
57     /// The invocation path is resolved in this scope.
58     crate parent_legacy_scope: Cell<LegacyScope<'a>>,
59     /// Legacy scope *produced* by expanding this macro invocation,
60     /// includes all the macro_rules items, other invocations, etc generated by it.
61     /// Set to the parent scope if the macro is not expanded yet (as if the macro produced nothing).
62     crate output_legacy_scope: Cell<LegacyScope<'a>>,
63 }
64
65 impl<'a> InvocationData<'a> {
66     pub fn root(graph_root: Module<'a>) -> Self {
67         InvocationData {
68             module: Cell::new(graph_root),
69             def_index: CRATE_DEF_INDEX,
70             parent_legacy_scope: Cell::new(LegacyScope::Empty),
71             output_legacy_scope: Cell::new(LegacyScope::Empty),
72         }
73     }
74 }
75
76 /// Binding produced by a `macro_rules` item.
77 /// Not modularized, can shadow previous legacy bindings, etc.
78 pub struct LegacyBinding<'a> {
79     binding: &'a NameBinding<'a>,
80     /// Legacy scope into which the `macro_rules` item was planted.
81     parent_legacy_scope: LegacyScope<'a>,
82     ident: Ident,
83 }
84
85 /// Scope introduced by a `macro_rules!` macro.
86 /// Starts at the macro's definition and ends at the end of the macro's parent module
87 /// (named or unnamed), or even further if it escapes with `#[macro_use]`.
88 /// Some macro invocations need to introduce legacy scopes too because they
89 /// potentially can expand into macro definitions.
90 #[derive(Copy, Clone)]
91 pub enum LegacyScope<'a> {
92     /// Created when invocation data is allocated in the arena,
93     /// must be replaced with a proper scope later.
94     Uninitialized,
95     /// Empty "root" scope at the crate start containing no names.
96     Empty,
97     /// Scope introduced by a `macro_rules!` macro definition.
98     Binding(&'a LegacyBinding<'a>),
99     /// Scope introduced by a macro invocation that can potentially
100     /// create a `macro_rules!` macro definition.
101     Invocation(&'a InvocationData<'a>),
102 }
103
104 pub struct ProcMacError {
105     crate_name: Symbol,
106     name: Symbol,
107     module: ast::NodeId,
108     use_span: Span,
109     warn_msg: &'static str,
110 }
111
112 // For compatibility bang macros are skipped when resolving potentially built-in attributes.
113 fn macro_kind_mismatch(name: Name, requirement: Option<MacroKind>, candidate: Option<MacroKind>)
114                        -> bool {
115     requirement == Some(MacroKind::Attr) && candidate == Some(MacroKind::Bang) &&
116     (name == "test" || name == "bench" || is_builtin_attr_name(name))
117 }
118
119 impl<'a, 'crateloader: 'a> base::Resolver for Resolver<'a, 'crateloader> {
120     fn next_node_id(&mut self) -> ast::NodeId {
121         self.session.next_node_id()
122     }
123
124     fn get_module_scope(&mut self, id: ast::NodeId) -> Mark {
125         let mark = Mark::fresh(Mark::root());
126         let module = self.module_map[&self.definitions.local_def_id(id)];
127         self.invocations.insert(mark, self.arenas.alloc_invocation_data(InvocationData {
128             module: Cell::new(module),
129             def_index: module.def_id().unwrap().index,
130             parent_legacy_scope: Cell::new(LegacyScope::Empty),
131             output_legacy_scope: Cell::new(LegacyScope::Empty),
132         }));
133         mark
134     }
135
136     fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> {
137         struct EliminateCrateVar<'b, 'a: 'b, 'crateloader: 'a>(
138             &'b mut Resolver<'a, 'crateloader>, Span
139         );
140
141         impl<'a, 'b, 'crateloader> Folder for EliminateCrateVar<'a, 'b, 'crateloader> {
142             fn fold_path(&mut self, path: ast::Path) -> ast::Path {
143                 match self.fold_qpath(None, path) {
144                     (None, path) => path,
145                     _ => unreachable!(),
146                 }
147             }
148
149             fn fold_qpath(&mut self, mut qself: Option<ast::QSelf>, mut path: ast::Path)
150                           -> (Option<ast::QSelf>, ast::Path) {
151                 qself = qself.map(|ast::QSelf { ty, path_span, position }| {
152                     ast::QSelf {
153                         ty: self.fold_ty(ty),
154                         path_span: self.new_span(path_span),
155                         position,
156                     }
157                 });
158
159                 if path.segments[0].ident.name == keywords::DollarCrate.name() {
160                     let module = self.0.resolve_crate_root(path.segments[0].ident);
161                     path.segments[0].ident.name = keywords::CrateRoot.name();
162                     if !module.is_local() {
163                         let span = path.segments[0].ident.span;
164                         path.segments.insert(1, match module.kind {
165                             ModuleKind::Def(_, name) => ast::PathSegment::from_ident(
166                                 ast::Ident::with_empty_ctxt(name).with_span_pos(span)
167                             ),
168                             _ => unreachable!(),
169                         });
170                         if let Some(qself) = &mut qself {
171                             qself.position += 1;
172                         }
173                     }
174                 }
175                 (qself, path)
176             }
177
178             fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
179                 fold::noop_fold_mac(mac, self)
180             }
181         }
182
183         EliminateCrateVar(self, item.span).fold_item(item).expect_one("")
184     }
185
186     fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool {
187         self.whitelisted_legacy_custom_derives.contains(&name)
188     }
189
190     fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
191                                             derives: &[Mark]) {
192         let invocation = self.invocations[&mark];
193         self.collect_def_ids(mark, invocation, fragment);
194
195         self.current_module = invocation.module.get();
196         self.current_module.unresolved_invocations.borrow_mut().remove(&mark);
197         self.current_module.unresolved_invocations.borrow_mut().extend(derives);
198         for &derive in derives {
199             self.invocations.insert(derive, invocation);
200         }
201         let mut visitor = BuildReducedGraphVisitor {
202             resolver: self,
203             current_legacy_scope: invocation.parent_legacy_scope.get(),
204             expansion: mark,
205         };
206         fragment.visit_with(&mut visitor);
207         invocation.output_legacy_scope.set(visitor.current_legacy_scope);
208     }
209
210     fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>) {
211         let def_id = DefId {
212             krate: BUILTIN_MACROS_CRATE,
213             index: DefIndex::from_array_index(self.macro_map.len(),
214                                               DefIndexAddressSpace::Low),
215         };
216         let kind = ext.kind();
217         self.macro_map.insert(def_id, ext);
218         let binding = self.arenas.alloc_name_binding(NameBinding {
219             kind: NameBindingKind::Def(Def::Macro(def_id, kind), false),
220             span: DUMMY_SP,
221             vis: ty::Visibility::Invisible,
222             expansion: Mark::root(),
223         });
224         if self.builtin_macros.insert(ident.name, binding).is_some() {
225             self.session.span_err(ident.span,
226                                   &format!("built-in macro `{}` was already defined", ident));
227         }
228     }
229
230     fn resolve_imports(&mut self) {
231         ImportResolver { resolver: self }.resolve_imports()
232     }
233
234     // Resolves attribute and derive legacy macros from `#![plugin(..)]`.
235     fn find_legacy_attr_invoc(&mut self, attrs: &mut Vec<ast::Attribute>, allow_derive: bool)
236                               -> Option<ast::Attribute> {
237         for i in 0..attrs.len() {
238             let name = attrs[i].name();
239
240             if self.session.plugin_attributes.borrow().iter()
241                     .any(|&(ref attr_nm, _)| name == &**attr_nm) {
242                 attr::mark_known(&attrs[i]);
243             }
244
245             match self.builtin_macros.get(&name).cloned() {
246                 Some(binding) => match *binding.get_macro(self) {
247                     MultiModifier(..) | MultiDecorator(..) | SyntaxExtension::AttrProcMacro(..) => {
248                         return Some(attrs.remove(i))
249                     }
250                     _ => {}
251                 },
252                 None => {}
253             }
254         }
255
256         if !allow_derive { return None }
257
258         // Check for legacy derives
259         for i in 0..attrs.len() {
260             let name = attrs[i].name();
261
262             if name == "derive" {
263                 let result = attrs[i].parse_list(&self.session.parse_sess, |parser| {
264                     parser.parse_path_allowing_meta(PathStyle::Mod)
265                 });
266
267                 let mut traits = match result {
268                     Ok(traits) => traits,
269                     Err(mut e) => {
270                         e.cancel();
271                         continue
272                     }
273                 };
274
275                 for j in 0..traits.len() {
276                     if traits[j].segments.len() > 1 {
277                         continue
278                     }
279                     let trait_name = traits[j].segments[0].ident.name;
280                     let legacy_name = Symbol::intern(&format!("derive_{}", trait_name));
281                     if !self.builtin_macros.contains_key(&legacy_name) {
282                         continue
283                     }
284                     let span = traits.remove(j).span;
285                     self.gate_legacy_custom_derive(legacy_name, span);
286                     if traits.is_empty() {
287                         attrs.remove(i);
288                     } else {
289                         let mut tokens = Vec::new();
290                         for (j, path) in traits.iter().enumerate() {
291                             if j > 0 {
292                                 tokens.push(TokenTree::Token(attrs[i].span, Token::Comma).into());
293                             }
294                             for (k, segment) in path.segments.iter().enumerate() {
295                                 if k > 0 {
296                                     tokens.push(TokenTree::Token(path.span, Token::ModSep).into());
297                                 }
298                                 let tok = Token::from_ast_ident(segment.ident);
299                                 tokens.push(TokenTree::Token(path.span, tok).into());
300                             }
301                         }
302                         let delim_span = DelimSpan::from_single(attrs[i].span);
303                         attrs[i].tokens = TokenTree::Delimited(delim_span, Delimited {
304                             delim: token::Paren,
305                             tts: TokenStream::concat(tokens).into(),
306                         }).into();
307                     }
308                     return Some(ast::Attribute {
309                         path: ast::Path::from_ident(Ident::new(legacy_name, span)),
310                         tokens: TokenStream::empty(),
311                         id: attr::mk_attr_id(),
312                         style: ast::AttrStyle::Outer,
313                         is_sugared_doc: false,
314                         span,
315                     });
316                 }
317             }
318         }
319
320         None
321     }
322
323     fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
324                                 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
325         let (path, kind, derives_in_scope) = match invoc.kind {
326             InvocationKind::Attr { attr: None, .. } =>
327                 return Ok(None),
328             InvocationKind::Attr { attr: Some(ref attr), ref traits, .. } =>
329                 (&attr.path, MacroKind::Attr, &traits[..]),
330             InvocationKind::Bang { ref mac, .. } =>
331                 (&mac.node.path, MacroKind::Bang, &[][..]),
332             InvocationKind::Derive { ref path, .. } =>
333                 (path, MacroKind::Derive, &[][..]),
334         };
335
336         let (def, ext) = self.resolve_macro_to_def(path, kind, invoc_id, derives_in_scope, force)?;
337
338         if let Def::Macro(def_id, _) = def {
339             self.macro_defs.insert(invoc.expansion_data.mark, def_id);
340             let normal_module_def_id =
341                 self.macro_def_scope(invoc.expansion_data.mark).normal_ancestor_id;
342             self.definitions.add_parent_module_of_macro_def(invoc.expansion_data.mark,
343                                                             normal_module_def_id);
344             invoc.expansion_data.mark.set_default_transparency(ext.default_transparency());
345             invoc.expansion_data.mark.set_is_builtin(def_id.krate == BUILTIN_MACROS_CRATE);
346         }
347
348         Ok(Some(ext))
349     }
350
351     fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
352                           derives_in_scope: &[ast::Path], force: bool)
353                           -> Result<Lrc<SyntaxExtension>, Determinacy> {
354         Ok(self.resolve_macro_to_def(path, kind, invoc_id, derives_in_scope, force)?.1)
355     }
356
357     fn check_unused_macros(&self) {
358         for did in self.unused_macros.iter() {
359             let id_span = match *self.macro_map[did] {
360                 SyntaxExtension::NormalTT { def_info, .. } |
361                 SyntaxExtension::DeclMacro { def_info, .. } => def_info,
362                 _ => None,
363             };
364             if let Some((id, span)) = id_span {
365                 let lint = lint::builtin::UNUSED_MACROS;
366                 let msg = "unused macro definition";
367                 self.session.buffer_lint(lint, id, span, msg);
368             } else {
369                 bug!("attempted to create unused macro error, but span not available");
370             }
371         }
372     }
373 }
374
375 impl<'a, 'cl> Resolver<'a, 'cl> {
376     fn resolve_macro_to_def(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
377                             derives_in_scope: &[ast::Path], force: bool)
378                             -> Result<(Def, Lrc<SyntaxExtension>), Determinacy> {
379         let def = self.resolve_macro_to_def_inner(path, kind, invoc_id, derives_in_scope, force);
380
381         // Report errors and enforce feature gates for the resolved macro.
382         if def != Err(Determinacy::Undetermined) {
383             // Do not report duplicated errors on every undetermined resolution.
384             for segment in &path.segments {
385                 if let Some(args) = &segment.args {
386                     self.session.span_err(args.span(), "generic arguments in macro path");
387                 }
388             }
389         }
390
391         let def = def?;
392
393         match def {
394             Def::Macro(def_id, macro_kind) => {
395                 self.unused_macros.remove(&def_id);
396                 if macro_kind == MacroKind::ProcMacroStub {
397                     let msg = "can't use a procedural macro from the same crate that defines it";
398                     self.session.span_err(path.span, msg);
399                     return Err(Determinacy::Determined);
400                 }
401             }
402             Def::NonMacroAttr(attr_kind) => {
403                 if kind == MacroKind::Attr {
404                     let features = self.session.features_untracked();
405                     if attr_kind == NonMacroAttrKind::Custom {
406                         assert!(path.segments.len() == 1);
407                         let name = path.segments[0].ident.name.as_str();
408                         if name.starts_with("rustc_") {
409                             if !features.rustc_attrs {
410                                 let msg = "unless otherwise specified, attributes with the prefix \
411                                            `rustc_` are reserved for internal compiler diagnostics";
412                                 feature_err(&self.session.parse_sess, "rustc_attrs", path.span,
413                                             GateIssue::Language, &msg).emit();
414                             }
415                         } else if name.starts_with("derive_") {
416                             if !features.custom_derive {
417                                 feature_err(&self.session.parse_sess, "custom_derive", path.span,
418                                             GateIssue::Language, EXPLAIN_DERIVE_UNDERSCORE).emit();
419                             }
420                         } else if !features.custom_attribute {
421                             let msg = format!("The attribute `{}` is currently unknown to the \
422                                                compiler and may have meaning added to it in the \
423                                                future", path);
424                             feature_err(&self.session.parse_sess, "custom_attribute", path.span,
425                                         GateIssue::Language, &msg).emit();
426                         }
427                     }
428                 } else {
429                     // Not only attributes, but anything in macro namespace can result in
430                     // `Def::NonMacroAttr` definition (e.g. `inline!()`), so we must report
431                     // an error for those cases.
432                     let msg = format!("expected a macro, found {}", def.kind_name());
433                     self.session.span_err(path.span, &msg);
434                     return Err(Determinacy::Determined);
435                 }
436             }
437             _ => panic!("expected `Def::Macro` or `Def::NonMacroAttr`"),
438         }
439
440         Ok((def, self.get_macro(def)))
441     }
442
443     pub fn resolve_macro_to_def_inner(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
444                                       derives_in_scope: &[ast::Path], force: bool)
445                                       -> Result<Def, Determinacy> {
446         let ast::Path { ref segments, span } = *path;
447         let mut path: Vec<_> = segments.iter().map(|seg| seg.ident).collect();
448         let invocation = self.invocations[&invoc_id];
449         let parent_expansion = invoc_id.parent();
450         let parent_legacy_scope = invocation.parent_legacy_scope.get();
451         self.current_module = invocation.module.get().nearest_item_scope();
452
453         // Possibly apply the macro helper hack
454         if kind == MacroKind::Bang && path.len() == 1 &&
455            path[0].span.ctxt().outer().expn_info().map_or(false, |info| info.local_inner_macros) {
456             let root = Ident::new(keywords::DollarCrate.name(), path[0].span);
457             path.insert(0, root);
458         }
459
460         if path.len() > 1 {
461             let def = match self.resolve_path_with_parent_expansion(None, &path, Some(MacroNS),
462                                                                     parent_expansion, false, span,
463                                                                     CrateLint::No) {
464                 PathResult::NonModule(path_res) => match path_res.base_def() {
465                     Def::Err => Err(Determinacy::Determined),
466                     def @ _ => {
467                         if path_res.unresolved_segments() > 0 {
468                             self.found_unresolved_macro = true;
469                             self.session.span_err(span, "fail to resolve non-ident macro path");
470                             Err(Determinacy::Determined)
471                         } else {
472                             Ok(def)
473                         }
474                     }
475                 },
476                 PathResult::Module(..) => unreachable!(),
477                 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
478                 _ => {
479                     self.found_unresolved_macro = true;
480                     Err(Determinacy::Determined)
481                 },
482             };
483             self.current_module.macro_resolutions.borrow_mut()
484                 .push((path.into_boxed_slice(), span));
485             return def;
486         }
487
488         let legacy_resolution = self.resolve_legacy_scope(
489             path[0], Some(kind), parent_expansion, parent_legacy_scope, false
490         );
491         let result = if let Some(legacy_binding) = legacy_resolution {
492             Ok(legacy_binding.def())
493         } else {
494             match self.resolve_lexical_macro_path_segment(path[0], MacroNS, Some(kind),
495                                                           parent_expansion, false, force, span) {
496                 Ok((binding, _)) => Ok(binding.def_ignoring_ambiguity()),
497                 Err(Determinacy::Undetermined) => return Err(Determinacy::Undetermined),
498                 Err(Determinacy::Determined) => {
499                     self.found_unresolved_macro = true;
500                     Err(Determinacy::Determined)
501                 }
502             }
503         };
504
505         self.current_module.legacy_macro_resolutions.borrow_mut()
506             .push((path[0], kind, parent_expansion, parent_legacy_scope, result.ok()));
507
508         if let Ok(Def::NonMacroAttr(NonMacroAttrKind::Custom)) = result {} else {
509             return result;
510         }
511
512         // At this point we've found that the `attr` is determinately unresolved and thus can be
513         // interpreted as a custom attribute. Normally custom attributes are feature gated, but
514         // it may be a custom attribute whitelisted by a derive macro and they do not require
515         // a feature gate.
516         //
517         // So here we look through all of the derive annotations in scope and try to resolve them.
518         // If they themselves successfully resolve *and* one of the resolved derive macros
519         // whitelists this attribute's name, then this is a registered attribute and we can convert
520         // it from a "generic custom attrite" into a "known derive helper attribute".
521         assert!(kind == MacroKind::Attr);
522         enum ConvertToDeriveHelper { Yes, No, DontKnow }
523         let mut convert_to_derive_helper = ConvertToDeriveHelper::No;
524         for derive in derives_in_scope {
525             match self.resolve_macro_path(derive, MacroKind::Derive, invoc_id, &[], force) {
526                 Ok(ext) => if let SyntaxExtension::ProcMacroDerive(_, ref inert_attrs, _) = *ext {
527                     if inert_attrs.contains(&path[0].name) {
528                         convert_to_derive_helper = ConvertToDeriveHelper::Yes;
529                         break
530                     }
531                 },
532                 Err(Determinacy::Undetermined) =>
533                     convert_to_derive_helper = ConvertToDeriveHelper::DontKnow,
534                 Err(Determinacy::Determined) => {}
535             }
536         }
537
538         match convert_to_derive_helper {
539             ConvertToDeriveHelper::Yes => Ok(Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper)),
540             ConvertToDeriveHelper::No => result,
541             ConvertToDeriveHelper::DontKnow => Err(Determinacy::determined(force)),
542         }
543     }
544
545     // Resolve the initial segment of a non-global macro path
546     // (e.g. `foo` in `foo::bar!(); or `foo!();`).
547     // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
548     // expansion and import resolution (perhaps they can be merged in the future).
549     crate fn resolve_lexical_macro_path_segment(
550         &mut self,
551         mut ident: Ident,
552         ns: Namespace,
553         kind: Option<MacroKind>,
554         parent_expansion: Mark,
555         record_used: bool,
556         force: bool,
557         path_span: Span,
558     ) -> Result<(&'a NameBinding<'a>, FromPrelude), Determinacy> {
559         // General principles:
560         // 1. Not controlled (user-defined) names should have higher priority than controlled names
561         //    built into the language or standard library. This way we can add new names into the
562         //    language or standard library without breaking user code.
563         // 2. "Closed set" below means new names can appear after the current resolution attempt.
564         // Places to search (in order of decreasing priority):
565         // (Type NS)
566         // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
567         //    (open set, not controlled).
568         // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
569         //    (open, not controlled).
570         // 3. Extern prelude (closed, not controlled).
571         // 4. Tool modules (closed, controlled right now, but not in the future).
572         // 5. Standard library prelude (de-facto closed, controlled).
573         // 6. Language prelude (closed, controlled).
574         // (Macro NS)
575         // 1. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
576         //    (open, not controlled).
577         // 2. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
578         // 2a. User-defined prelude from macro-use
579         //    (open, the open part is from macro expansions, not controlled).
580         // 2b. Standard library prelude is currently implemented as `macro-use` (closed, controlled)
581         // 3. Language prelude: builtin macros (closed, controlled, except for legacy plugins).
582         // 4. Language prelude: builtin attributes (closed, controlled).
583
584         assert!(ns == TypeNS  || ns == MacroNS);
585         assert!(force || !record_used); // `record_used` implies `force`
586         ident = ident.modern();
587
588         // This is *the* result, resolution from the scope closest to the resolved identifier.
589         // However, sometimes this result is "weak" because it comes from a glob import or
590         // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
591         // mod m { ... } // solution in outer scope
592         // {
593         //     use prefix::*; // imports another `m` - innermost solution
594         //                    // weak, cannot shadow the outer `m`, need to report ambiguity error
595         //     m::mac!();
596         // }
597         // So we have to save the innermost solution and continue searching in outer scopes
598         // to detect potential ambiguities.
599         let mut innermost_result: Option<(&NameBinding, FromPrelude)> = None;
600
601         enum WhereToResolve<'a> {
602             Module(Module<'a>),
603             MacroUsePrelude,
604             BuiltinMacros,
605             BuiltinAttrs,
606             ExternPrelude,
607             ToolPrelude,
608             StdLibPrelude,
609             BuiltinTypes,
610         }
611
612         // Go through all the scopes and try to resolve the name.
613         let mut where_to_resolve = WhereToResolve::Module(self.current_module);
614         let mut use_prelude = !self.current_module.no_implicit_prelude;
615         loop {
616             let result = match where_to_resolve {
617                 WhereToResolve::Module(module) => {
618                     let orig_current_module = mem::replace(&mut self.current_module, module);
619                     let binding = self.resolve_ident_in_module_unadjusted(
620                         ModuleOrUniformRoot::Module(module),
621                         ident,
622                         ns,
623                         true,
624                         record_used,
625                         path_span,
626                     );
627                     self.current_module = orig_current_module;
628                     binding.map(|binding| (binding, FromPrelude(false)))
629                 }
630                 WhereToResolve::MacroUsePrelude => {
631                     match self.macro_use_prelude.get(&ident.name).cloned() {
632                         Some(binding) => Ok((binding, FromPrelude(true))),
633                         None => Err(Determinacy::Determined),
634                     }
635                 }
636                 WhereToResolve::BuiltinMacros => {
637                     match self.builtin_macros.get(&ident.name).cloned() {
638                         Some(binding) => Ok((binding, FromPrelude(true))),
639                         None => Err(Determinacy::Determined),
640                     }
641                 }
642                 WhereToResolve::BuiltinAttrs => {
643                     // FIXME: Only built-in attributes are not considered as candidates for
644                     // non-attributes to fight off regressions on stable channel (#53205).
645                     // We need to come up with some more principled approach instead.
646                     if kind == Some(MacroKind::Attr) && is_builtin_attr_name(ident.name) {
647                         let binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
648                                        ty::Visibility::Public, ident.span, Mark::root())
649                                        .to_name_binding(self.arenas);
650                         Ok((binding, FromPrelude(true)))
651                     } else {
652                         Err(Determinacy::Determined)
653                     }
654                 }
655                 WhereToResolve::ExternPrelude => {
656                     if use_prelude && self.extern_prelude.contains(&ident.name) {
657                         if !self.session.features_untracked().extern_prelude &&
658                            !self.ignore_extern_prelude_feature {
659                             feature_err(&self.session.parse_sess, "extern_prelude",
660                                         ident.span, GateIssue::Language,
661                                         "access to extern crates through prelude is experimental")
662                                         .emit();
663                         }
664
665                         let crate_id =
666                             self.crate_loader.process_path_extern(ident.name, ident.span);
667                         let crate_root =
668                             self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
669                         self.populate_module_if_necessary(crate_root);
670
671                         let binding = (crate_root, ty::Visibility::Public,
672                                        ident.span, Mark::root()).to_name_binding(self.arenas);
673                         Ok((binding, FromPrelude(true)))
674                     } else {
675                         Err(Determinacy::Determined)
676                     }
677                 }
678                 WhereToResolve::ToolPrelude => {
679                     if use_prelude && is_known_tool(ident.name) {
680                         let binding = (Def::ToolMod, ty::Visibility::Public,
681                                        ident.span, Mark::root()).to_name_binding(self.arenas);
682                         Ok((binding, FromPrelude(true)))
683                     } else {
684                         Err(Determinacy::Determined)
685                     }
686                 }
687                 WhereToResolve::StdLibPrelude => {
688                     let mut result = Err(Determinacy::Determined);
689                     if use_prelude {
690                         if let Some(prelude) = self.prelude {
691                             if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
692                                 ModuleOrUniformRoot::Module(prelude),
693                                 ident,
694                                 ns,
695                                 false,
696                                 false,
697                                 path_span,
698                             ) {
699                                 result = Ok((binding, FromPrelude(true)));
700                             }
701                         }
702                     }
703                     result
704                 }
705                 WhereToResolve::BuiltinTypes => {
706                     if let Some(prim_ty) =
707                             self.primitive_type_table.primitive_types.get(&ident.name).cloned() {
708                         let binding = (Def::PrimTy(prim_ty), ty::Visibility::Public,
709                                        ident.span, Mark::root()).to_name_binding(self.arenas);
710                         Ok((binding, FromPrelude(true)))
711                     } else {
712                         Err(Determinacy::Determined)
713                     }
714                 }
715             };
716
717             macro_rules! continue_search { () => {
718                 where_to_resolve = match where_to_resolve {
719                     WhereToResolve::Module(module) => {
720                         match self.hygienic_lexical_parent(module, &mut ident.span) {
721                             Some(parent_module) => WhereToResolve::Module(parent_module),
722                             None => {
723                                 use_prelude = !module.no_implicit_prelude;
724                                 if ns == MacroNS {
725                                     WhereToResolve::MacroUsePrelude
726                                 } else {
727                                     WhereToResolve::ExternPrelude
728                                 }
729                             }
730                         }
731                     }
732                     WhereToResolve::MacroUsePrelude => WhereToResolve::BuiltinMacros,
733                     WhereToResolve::BuiltinMacros => WhereToResolve::BuiltinAttrs,
734                     WhereToResolve::BuiltinAttrs => break, // nowhere else to search
735                     WhereToResolve::ExternPrelude => WhereToResolve::ToolPrelude,
736                     WhereToResolve::ToolPrelude => WhereToResolve::StdLibPrelude,
737                     WhereToResolve::StdLibPrelude => WhereToResolve::BuiltinTypes,
738                     WhereToResolve::BuiltinTypes => break, // nowhere else to search
739                 };
740
741                 continue;
742             }}
743
744             match result {
745                 Ok(result) => {
746                     if macro_kind_mismatch(ident.name, kind, result.0.macro_kind()) {
747                         continue_search!();
748                     }
749
750                     if !record_used {
751                         return Ok(result);
752                     }
753
754                     if let Some(innermost_result) = innermost_result {
755                         // Found another solution, if the first one was "weak", report an error.
756                         if result.0.def() != innermost_result.0.def() &&
757                            (innermost_result.0.is_glob_import() ||
758                             innermost_result.0.may_appear_after(parent_expansion, result.0)) {
759                             self.ambiguity_errors.push(AmbiguityError {
760                                 ident,
761                                 b1: innermost_result.0,
762                                 b2: result.0,
763                             });
764                             return Ok(innermost_result);
765                         }
766                     } else {
767                         // Found the first solution.
768                         innermost_result = Some(result);
769                     }
770
771                     continue_search!();
772                 },
773                 Err(Determinacy::Determined) => {
774                     continue_search!();
775                 }
776                 Err(Determinacy::Undetermined) => return Err(Determinacy::determined(force)),
777             }
778         }
779
780         // The first found solution was the only one, return it.
781         if let Some(innermost_result) = innermost_result {
782             return Ok(innermost_result);
783         }
784
785         let determinacy = Determinacy::determined(force);
786         if determinacy == Determinacy::Determined && kind == Some(MacroKind::Attr) {
787             // For single-segment attributes interpret determinate "no resolution" as a custom
788             // attribute. (Lexical resolution implies the first segment and attr kind should imply
789             // the last segment, so we are certainly working with a single-segment attribute here.)
790             assert!(ns == MacroNS);
791             let binding = (Def::NonMacroAttr(NonMacroAttrKind::Custom),
792                            ty::Visibility::Public, ident.span, Mark::root())
793                            .to_name_binding(self.arenas);
794             Ok((binding, FromPrelude(true)))
795         } else {
796             Err(determinacy)
797         }
798     }
799
800     fn resolve_legacy_scope(&mut self,
801                             ident: Ident,
802                             kind: Option<MacroKind>,
803                             parent_expansion: Mark,
804                             parent_legacy_scope: LegacyScope<'a>,
805                             record_used: bool)
806                             -> Option<&'a NameBinding<'a>> {
807         if macro_kind_mismatch(ident.name, kind, Some(MacroKind::Bang)) {
808             return None;
809         }
810
811         let ident = ident.modern();
812
813         // This is *the* result, resolution from the scope closest to the resolved identifier.
814         // However, sometimes this result is "weak" because it comes from a macro expansion,
815         // and in this case it cannot shadow names from outer scopes, e.g.
816         // macro_rules! m { ... } // solution in outer scope
817         // {
818         //     define_m!(); // generates another `macro_rules! m` - innermost solution
819         //                  // weak, cannot shadow the outer `m`, need to report ambiguity error
820         //     m!();
821         // }
822         // So we have to save the innermost solution and continue searching in outer scopes
823         // to detect potential ambiguities.
824         let mut innermost_result: Option<&NameBinding> = None;
825
826         // Go through all the scopes and try to resolve the name.
827         let mut where_to_resolve = parent_legacy_scope;
828         loop {
829             let result = match where_to_resolve {
830                 LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident =>
831                     Some(legacy_binding.binding),
832                 _ => None,
833             };
834
835             macro_rules! continue_search { () => {
836                 where_to_resolve = match where_to_resolve {
837                     LegacyScope::Empty => break, // nowhere else to search
838                     LegacyScope::Binding(binding) => binding.parent_legacy_scope,
839                     LegacyScope::Invocation(invocation) => invocation.output_legacy_scope.get(),
840                     LegacyScope::Uninitialized => unreachable!(),
841                 };
842
843                 continue;
844             }}
845
846             match result {
847                 Some(result) => {
848                     if !record_used {
849                         return Some(result);
850                     }
851
852                     if let Some(innermost_result) = innermost_result {
853                         // Found another solution, if the first one was "weak", report an error.
854                         if result.def() != innermost_result.def() &&
855                            innermost_result.may_appear_after(parent_expansion, result) {
856                             self.ambiguity_errors.push(AmbiguityError {
857                                 ident,
858                                 b1: innermost_result,
859                                 b2: result,
860                             });
861                             return Some(innermost_result);
862                         }
863                     } else {
864                         // Found the first solution.
865                         innermost_result = Some(result);
866                     }
867
868                     continue_search!();
869                 }
870                 None => {
871                     continue_search!();
872                 }
873             }
874         }
875
876         // The first found solution was the only one (or there was no solution at all), return it.
877         innermost_result
878     }
879
880     pub fn finalize_current_module_macro_resolutions(&mut self) {
881         let module = self.current_module;
882         for &(ref path, span) in module.macro_resolutions.borrow().iter() {
883             match self.resolve_path(None, &path, Some(MacroNS), true, span, CrateLint::No) {
884                 PathResult::NonModule(_) => {},
885                 PathResult::Failed(span, msg, _) => {
886                     resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
887                 }
888                 _ => unreachable!(),
889             }
890         }
891
892         for &(ident, kind, parent_expansion, parent_legacy_scope, def)
893                 in module.legacy_macro_resolutions.borrow().iter() {
894             let span = ident.span;
895             let legacy_resolution = self.resolve_legacy_scope(
896                 ident, Some(kind), parent_expansion, parent_legacy_scope, true
897             );
898             let resolution = self.resolve_lexical_macro_path_segment(
899                 ident, MacroNS, Some(kind), parent_expansion, true, true, span
900             );
901
902             let check_consistency = |this: &Self, new_def: Def| {
903                 if let Some(def) = def {
904                     if this.ambiguity_errors.is_empty() && new_def != def && new_def != Def::Err {
905                         // Make sure compilation does not succeed if preferred macro resolution
906                         // has changed after the macro had been expanded. In theory all such
907                         // situations should be reported as ambiguity errors, so this is span-bug.
908                         span_bug!(span, "inconsistent resolution for a macro");
909                     }
910                 } else {
911                     // It's possible that the macro was unresolved (indeterminate) and silently
912                     // expanded into a dummy fragment for recovery during expansion.
913                     // Now, post-expansion, the resolution may succeed, but we can't change the
914                     // past and need to report an error.
915                     let msg =
916                         format!("cannot determine resolution for the {} `{}`", kind.descr(), ident);
917                     let msg_note = "import resolution is stuck, try simplifying macro imports";
918                     this.session.struct_span_err(span, &msg).note(msg_note).emit();
919                 }
920             };
921
922             match (legacy_resolution, resolution) {
923                 (None, Err(_)) => {
924                     assert!(def.is_none());
925                     let bang = if kind == MacroKind::Bang { "!" } else { "" };
926                     let msg =
927                         format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
928                     let mut err = self.session.struct_span_err(span, &msg);
929                     self.suggest_macro_name(&ident.as_str(), kind, &mut err, span);
930                     err.emit();
931                 },
932                 (Some(legacy_binding), Ok((binding, FromPrelude(from_prelude))))
933                         if legacy_binding.def() != binding.def_ignoring_ambiguity() &&
934                            (!from_prelude ||
935                             legacy_binding.may_appear_after(parent_expansion, binding)) => {
936                     self.report_ambiguity_error(ident, legacy_binding, binding);
937                 },
938                 // OK, non-macro-expanded legacy wins over prelude even if defs are different
939                 // Also, legacy and modern can co-exist if their defs are same
940                 (Some(legacy_binding), Ok(_)) |
941                 // OK, unambiguous resolution
942                 (Some(legacy_binding), Err(_)) => {
943                     check_consistency(self, legacy_binding.def());
944                 }
945                 // OK, unambiguous resolution
946                 (None, Ok((binding, FromPrelude(from_prelude)))) => {
947                     check_consistency(self, binding.def_ignoring_ambiguity());
948                     if from_prelude {
949                         self.record_use(ident, MacroNS, binding);
950                         self.err_if_macro_use_proc_macro(ident.name, span, binding);
951                     }
952                 }
953             };
954         }
955
956         for &(ident, parent_expansion, parent_legacy_scope)
957                 in module.builtin_attrs.borrow().iter() {
958             let resolve_legacy = |this: &mut Self| this.resolve_legacy_scope(
959                 ident, Some(MacroKind::Attr), parent_expansion, parent_legacy_scope, true
960             );
961             let resolve_modern = |this: &mut Self| this.resolve_lexical_macro_path_segment(
962                 ident, MacroNS, Some(MacroKind::Attr), parent_expansion, true, true, ident.span
963             ).map(|(binding, _)| binding).ok();
964
965             if let Some(binding) = resolve_legacy(self).or_else(|| resolve_modern(self)) {
966                 if binding.def_ignoring_ambiguity() !=
967                         Def::NonMacroAttr(NonMacroAttrKind::Builtin) {
968                     let builtin_binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
969                                            ty::Visibility::Public, ident.span, Mark::root())
970                                            .to_name_binding(self.arenas);
971                     self.report_ambiguity_error(ident, binding, builtin_binding);
972                 }
973             }
974         }
975     }
976
977     fn suggest_macro_name(&mut self, name: &str, kind: MacroKind,
978                           err: &mut DiagnosticBuilder<'a>, span: Span) {
979         // First check if this is a locally-defined bang macro.
980         let suggestion = if let MacroKind::Bang = kind {
981             find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, None)
982         } else {
983             None
984         // Then check global macros.
985         }.or_else(|| {
986             let names = self.builtin_macros.iter().chain(self.macro_use_prelude.iter())
987                                                   .filter_map(|(name, binding)| {
988                 if binding.macro_kind() == Some(kind) { Some(name) } else { None }
989             });
990             find_best_match_for_name(names, name, None)
991         // Then check modules.
992         }).or_else(|| {
993             let is_macro = |def| {
994                 if let Def::Macro(_, def_kind) = def {
995                     def_kind == kind
996                 } else {
997                     false
998                 }
999             };
1000             let ident = Ident::new(Symbol::intern(name), span);
1001             self.lookup_typo_candidate(&[ident], MacroNS, is_macro, span)
1002         });
1003
1004         if let Some(suggestion) = suggestion {
1005             if suggestion != name {
1006                 if let MacroKind::Bang = kind {
1007                     err.span_suggestion_with_applicability(
1008                         span,
1009                         "you could try the macro",
1010                         suggestion.to_string(),
1011                         Applicability::MaybeIncorrect
1012                     );
1013                 } else {
1014                     err.span_suggestion_with_applicability(
1015                         span,
1016                         "try",
1017                         suggestion.to_string(),
1018                         Applicability::MaybeIncorrect
1019                     );
1020                 }
1021             } else {
1022                 err.help("have you added the `#[macro_use]` on the module/import?");
1023             }
1024         }
1025     }
1026
1027     fn collect_def_ids(&mut self,
1028                        mark: Mark,
1029                        invocation: &'a InvocationData<'a>,
1030                        fragment: &AstFragment) {
1031         let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
1032         let InvocationData { def_index, .. } = *invocation;
1033
1034         let visit_macro_invoc = &mut |invoc: map::MacroInvocationData| {
1035             invocations.entry(invoc.mark).or_insert_with(|| {
1036                 arenas.alloc_invocation_data(InvocationData {
1037                     def_index: invoc.def_index,
1038                     module: Cell::new(graph_root),
1039                     parent_legacy_scope: Cell::new(LegacyScope::Uninitialized),
1040                     output_legacy_scope: Cell::new(LegacyScope::Uninitialized),
1041                 })
1042             });
1043         };
1044
1045         let mut def_collector = DefCollector::new(&mut self.definitions, mark);
1046         def_collector.visit_macro_invoc = Some(visit_macro_invoc);
1047         def_collector.with_parent(def_index, |def_collector| {
1048             fragment.visit_with(def_collector)
1049         });
1050     }
1051
1052     pub fn define_macro(&mut self,
1053                         item: &ast::Item,
1054                         expansion: Mark,
1055                         current_legacy_scope: &mut LegacyScope<'a>) {
1056         self.local_macro_def_scopes.insert(item.id, self.current_module);
1057         let ident = item.ident;
1058         if ident.name == "macro_rules" {
1059             self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
1060         }
1061
1062         let def_id = self.definitions.local_def_id(item.id);
1063         let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
1064                                                &self.session.features_untracked(),
1065                                                item, hygiene::default_edition()));
1066         self.macro_map.insert(def_id, ext);
1067
1068         let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
1069         if def.legacy {
1070             let ident = ident.modern();
1071             self.macro_names.insert(ident);
1072             let def = Def::Macro(def_id, MacroKind::Bang);
1073             let vis = ty::Visibility::Invisible; // Doesn't matter for legacy bindings
1074             let binding = (def, vis, item.span, expansion).to_name_binding(self.arenas);
1075             let legacy_binding = self.arenas.alloc_legacy_binding(LegacyBinding {
1076                 parent_legacy_scope: *current_legacy_scope, binding, ident
1077             });
1078             *current_legacy_scope = LegacyScope::Binding(legacy_binding);
1079             self.all_macros.insert(ident.name, def);
1080             if attr::contains_name(&item.attrs, "macro_export") {
1081                 let module = self.graph_root;
1082                 let vis = ty::Visibility::Public;
1083                 self.define(module, ident, MacroNS,
1084                             (def, vis, item.span, expansion, IsMacroExport));
1085             } else {
1086                 if !attr::contains_name(&item.attrs, "rustc_doc_only_macro") {
1087                     self.check_reserved_macro_name(ident, MacroNS);
1088                 }
1089                 self.unused_macros.insert(def_id);
1090             }
1091         } else {
1092             let module = self.current_module;
1093             let def = Def::Macro(def_id, MacroKind::Bang);
1094             let vis = self.resolve_visibility(&item.vis);
1095             if vis != ty::Visibility::Public {
1096                 self.unused_macros.insert(def_id);
1097             }
1098             self.define(module, ident, MacroNS, (def, vis, item.span, expansion));
1099         }
1100     }
1101
1102     /// Error if `ext` is a Macros 1.1 procedural macro being imported by `#[macro_use]`
1103     fn err_if_macro_use_proc_macro(&mut self, name: Name, use_span: Span,
1104                                    binding: &NameBinding<'a>) {
1105         let krate = match binding.def() {
1106             Def::NonMacroAttr(..) | Def::Err => return,
1107             Def::Macro(def_id, _) => def_id.krate,
1108             _ => unreachable!(),
1109         };
1110
1111         // Plugin-based syntax extensions are exempt from this check
1112         if krate == BUILTIN_MACROS_CRATE { return; }
1113
1114         let ext = binding.get_macro(self);
1115
1116         match *ext {
1117             // If `ext` is a procedural macro, check if we've already warned about it
1118             SyntaxExtension::AttrProcMacro(..) | SyntaxExtension::ProcMacro { .. } =>
1119                 if !self.warned_proc_macros.insert(name) { return; },
1120             _ => return,
1121         }
1122
1123         let warn_msg = match *ext {
1124             SyntaxExtension::AttrProcMacro(..) =>
1125                 "attribute procedural macros cannot be imported with `#[macro_use]`",
1126             SyntaxExtension::ProcMacro { .. } =>
1127                 "procedural macros cannot be imported with `#[macro_use]`",
1128             _ => return,
1129         };
1130
1131         let def_id = self.current_module.normal_ancestor_id;
1132         let node_id = self.definitions.as_local_node_id(def_id).unwrap();
1133
1134         self.proc_mac_errors.push(ProcMacError {
1135             crate_name: self.cstore.crate_name_untracked(krate),
1136             name,
1137             module: node_id,
1138             use_span,
1139             warn_msg,
1140         });
1141     }
1142
1143     pub fn report_proc_macro_import(&mut self, krate: &ast::Crate) {
1144         for err in self.proc_mac_errors.drain(..) {
1145             let (span, found_use) = ::UsePlacementFinder::check(krate, err.module);
1146
1147             if let Some(span) = span {
1148                 let found_use = if found_use { "" } else { "\n" };
1149                 self.session.struct_span_err(err.use_span, err.warn_msg)
1150                     .span_suggestion_with_applicability(
1151                         span,
1152                         "instead, import the procedural macro like any other item",
1153                         format!("use {}::{};{}", err.crate_name, err.name, found_use),
1154                         Applicability::MachineApplicable
1155                     ).emit();
1156             } else {
1157                 self.session.struct_span_err(err.use_span, err.warn_msg)
1158                     .help(&format!("instead, import the procedural macro like any other item: \
1159                                     `use {}::{};`", err.crate_name, err.name))
1160                     .emit();
1161             }
1162         }
1163     }
1164
1165     fn gate_legacy_custom_derive(&mut self, name: Symbol, span: Span) {
1166         if !self.session.features_untracked().custom_derive {
1167             let sess = &self.session.parse_sess;
1168             let explain = feature_gate::EXPLAIN_CUSTOM_DERIVE;
1169             emit_feature_err(sess, "custom_derive", span, GateIssue::Language, explain);
1170         } else if !self.is_whitelisted_legacy_custom_derive(name) {
1171             self.session.span_warn(span, feature_gate::EXPLAIN_DEPR_CUSTOM_DERIVE);
1172         }
1173     }
1174 }