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.
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.
11 use {AmbiguityError, Resolver, ResolutionError, resolve_error};
12 use {Module, ModuleKind, NameBinding, NameBindingKind, PathResult};
13 use Namespace::{self, MacroNS};
14 use build_reduced_graph::BuildReducedGraphVisitor;
15 use resolve_imports::ImportResolver;
16 use rustc::hir::def_id::{DefId, BUILTIN_MACROS_CRATE, CRATE_DEF_INDEX, DefIndex};
17 use rustc::hir::def::{Def, Export};
18 use rustc::hir::map::{self, DefCollector};
19 use rustc::{ty, lint};
20 use syntax::ast::{self, Name, Ident};
21 use syntax::attr::{self, HasAttrs};
22 use syntax::codemap::respan;
23 use syntax::errors::DiagnosticBuilder;
24 use syntax::ext::base::{self, Annotatable, Determinacy, MultiModifier, MultiDecorator};
25 use syntax::ext::base::{MacroKind, SyntaxExtension, Resolver as SyntaxResolver};
26 use syntax::ext::expand::{Expansion, ExpansionKind, Invocation, InvocationKind, find_attr_invoc};
27 use syntax::ext::hygiene::Mark;
28 use syntax::ext::placeholders::placeholder;
29 use syntax::ext::tt::macro_rules;
30 use syntax::feature_gate::{self, emit_feature_err, GateIssue};
31 use syntax::fold::{self, Folder};
32 use syntax::parse::parser::PathStyle;
33 use syntax::parse::token::{self, Token};
35 use syntax::symbol::{Symbol, keywords};
36 use syntax::tokenstream::{TokenStream, TokenTree, Delimited};
37 use syntax::util::lev_distance::find_best_match_for_name;
38 use syntax_pos::{Span, DUMMY_SP};
45 pub struct InvocationData<'a> {
46 pub module: Cell<Module<'a>>,
47 pub def_index: DefIndex,
48 // True if this expansion is in a `const_expr` position, for example `[u32; m!()]`.
49 // c.f. `DefCollector::visit_const_expr`.
51 // The scope in which the invocation path is resolved.
52 pub legacy_scope: Cell<LegacyScope<'a>>,
53 // The smallest scope that includes this invocation's expansion,
54 // or `Empty` if this invocation has not been expanded yet.
55 pub expansion: Cell<LegacyScope<'a>>,
58 impl<'a> InvocationData<'a> {
59 pub fn root(graph_root: Module<'a>) -> Self {
61 module: Cell::new(graph_root),
62 def_index: CRATE_DEF_INDEX,
64 legacy_scope: Cell::new(LegacyScope::Empty),
65 expansion: Cell::new(LegacyScope::Empty),
70 #[derive(Copy, Clone)]
71 pub enum LegacyScope<'a> {
73 Invocation(&'a InvocationData<'a>), // The scope of the invocation, not including its expansion
74 Expansion(&'a InvocationData<'a>), // The scope of the invocation, including its expansion
75 Binding(&'a LegacyBinding<'a>),
78 pub struct LegacyBinding<'a> {
79 pub parent: Cell<LegacyScope<'a>>,
85 #[derive(Copy, Clone)]
86 pub enum MacroBinding<'a> {
87 Legacy(&'a LegacyBinding<'a>),
88 Global(&'a NameBinding<'a>),
89 Modern(&'a NameBinding<'a>),
92 impl<'a> MacroBinding<'a> {
93 pub fn span(self) -> Span {
95 MacroBinding::Legacy(binding) => binding.span,
96 MacroBinding::Global(binding) | MacroBinding::Modern(binding) => binding.span,
100 pub fn binding(self) -> &'a NameBinding<'a> {
102 MacroBinding::Global(binding) | MacroBinding::Modern(binding) => binding,
103 MacroBinding::Legacy(_) => panic!("unexpected MacroBinding::Legacy"),
108 impl<'a> base::Resolver for Resolver<'a> {
109 fn next_node_id(&mut self) -> ast::NodeId {
110 self.session.next_node_id()
113 fn get_module_scope(&mut self, id: ast::NodeId) -> Mark {
114 let mark = Mark::fresh(Mark::root());
115 let module = self.module_map[&self.definitions.local_def_id(id)];
116 self.invocations.insert(mark, self.arenas.alloc_invocation_data(InvocationData {
117 module: Cell::new(module),
118 def_index: module.def_id().unwrap().index,
120 legacy_scope: Cell::new(LegacyScope::Empty),
121 expansion: Cell::new(LegacyScope::Empty),
126 fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> {
127 struct EliminateCrateVar<'b, 'a: 'b>(&'b mut Resolver<'a>, Span);
129 impl<'a, 'b> Folder for EliminateCrateVar<'a, 'b> {
130 fn fold_path(&mut self, mut path: ast::Path) -> ast::Path {
131 let ident = path.segments[0].identifier;
132 if ident.name == keywords::DollarCrate.name() {
133 path.segments[0].identifier.name = keywords::CrateRoot.name();
134 let module = self.0.resolve_crate_root(ident.ctxt);
135 if !module.is_local() {
136 let span = path.segments[0].span;
137 path.segments.insert(1, match module.kind {
138 ModuleKind::Def(_, name) => ast::PathSegment::from_ident(
139 ast::Ident::with_empty_ctxt(name), span
148 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
149 fold::noop_fold_mac(mac, self)
153 EliminateCrateVar(self, item.span).fold_item(item).expect_one("")
156 fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool {
157 self.whitelisted_legacy_custom_derives.contains(&name)
160 fn visit_expansion(&mut self, mark: Mark, expansion: &Expansion, derives: &[Mark]) {
161 let invocation = self.invocations[&mark];
162 self.collect_def_ids(mark, invocation, expansion);
164 self.current_module = invocation.module.get();
165 self.current_module.unresolved_invocations.borrow_mut().remove(&mark);
166 self.current_module.unresolved_invocations.borrow_mut().extend(derives);
167 for &derive in derives {
168 self.invocations.insert(derive, invocation);
170 let mut visitor = BuildReducedGraphVisitor {
172 legacy_scope: LegacyScope::Invocation(invocation),
175 expansion.visit_with(&mut visitor);
176 invocation.expansion.set(visitor.legacy_scope);
179 fn add_builtin(&mut self, ident: ast::Ident, ext: Rc<SyntaxExtension>) {
181 krate: BUILTIN_MACROS_CRATE,
182 index: DefIndex::new(self.macro_map.len()),
184 let kind = ext.kind();
185 self.macro_map.insert(def_id, ext);
186 let binding = self.arenas.alloc_name_binding(NameBinding {
187 kind: NameBindingKind::Def(Def::Macro(def_id, kind)),
189 vis: ty::Visibility::Invisible,
190 expansion: Mark::root(),
192 self.global_macros.insert(ident.name, binding);
195 fn resolve_imports(&mut self) {
196 ImportResolver { resolver: self }.resolve_imports()
199 // Resolves attribute and derive legacy macros from `#![plugin(..)]`.
200 fn find_legacy_attr_invoc(&mut self, attrs: &mut Vec<ast::Attribute>)
201 -> Option<ast::Attribute> {
202 for i in 0..attrs.len() {
203 let name = unwrap_or!(attrs[i].name(), continue);
205 if self.session.plugin_attributes.borrow().iter()
206 .any(|&(ref attr_nm, _)| name == &**attr_nm) {
207 attr::mark_known(&attrs[i]);
210 match self.global_macros.get(&name).cloned() {
211 Some(binding) => match *binding.get_macro(self) {
212 MultiModifier(..) | MultiDecorator(..) | SyntaxExtension::AttrProcMacro(..) => {
213 return Some(attrs.remove(i))
221 // Check for legacy derives
222 for i in 0..attrs.len() {
223 let name = unwrap_or!(attrs[i].name(), continue);
225 if name == "derive" {
226 let result = attrs[i].parse_list(&self.session.parse_sess, |parser| {
227 parser.parse_path_allowing_meta(PathStyle::Mod)
230 let mut traits = match result {
231 Ok(traits) => traits,
238 for j in 0..traits.len() {
239 if traits[j].segments.len() > 1 {
242 let trait_name = traits[j].segments[0].identifier.name;
243 let legacy_name = Symbol::intern(&format!("derive_{}", trait_name));
244 if !self.global_macros.contains_key(&legacy_name) {
247 let span = traits.remove(j).span;
248 self.gate_legacy_custom_derive(legacy_name, span);
249 if traits.is_empty() {
252 let mut tokens = Vec::new();
253 for (j, path) in traits.iter().enumerate() {
255 tokens.push(TokenTree::Token(attrs[i].span, Token::Comma).into());
257 for (k, segment) in path.segments.iter().enumerate() {
259 tokens.push(TokenTree::Token(path.span, Token::ModSep).into());
261 let tok = Token::Ident(segment.identifier);
262 tokens.push(TokenTree::Token(path.span, tok).into());
265 attrs[i].tokens = TokenTree::Delimited(attrs[i].span, Delimited {
267 tts: TokenStream::concat(tokens).into(),
270 return Some(ast::Attribute {
271 path: ast::Path::from_ident(span, Ident::with_empty_ctxt(legacy_name)),
272 tokens: TokenStream::empty(),
273 id: attr::mk_attr_id(),
274 style: ast::AttrStyle::Outer,
275 is_sugared_doc: false,
285 fn resolve_invoc(&mut self, invoc: &mut Invocation, scope: Mark, force: bool)
286 -> Result<Option<Rc<SyntaxExtension>>, Determinacy> {
287 let def = match invoc.kind {
288 InvocationKind::Attr { attr: None, .. } => return Ok(None),
289 _ => self.resolve_invoc_to_def(invoc, scope, force)?,
292 self.macro_defs.insert(invoc.expansion_data.mark, def.def_id());
293 let normal_module_def_id =
294 self.macro_def_scope(invoc.expansion_data.mark).normal_ancestor_id;
295 self.definitions.add_macro_def_scope(invoc.expansion_data.mark, normal_module_def_id);
297 self.unused_macros.remove(&def.def_id());
298 let ext = self.get_macro(def);
300 invoc.expansion_data.mark.set_modern();
305 fn resolve_macro(&mut self, scope: Mark, path: &ast::Path, kind: MacroKind, force: bool)
306 -> Result<Rc<SyntaxExtension>, Determinacy> {
307 self.resolve_macro_to_def(scope, path, kind, force).map(|def| {
308 self.unused_macros.remove(&def.def_id());
313 fn check_unused_macros(&self) {
314 for did in self.unused_macros.iter() {
315 let id_span = match *self.macro_map[did] {
316 SyntaxExtension::NormalTT { def_info, .. } => def_info,
317 SyntaxExtension::DeclMacro(.., osp) => osp,
320 if let Some((id, span)) = id_span {
321 let lint = lint::builtin::UNUSED_MACROS;
322 let msg = "unused macro definition";
323 self.session.buffer_lint(lint, id, span, msg);
325 bug!("attempted to create unused macro error, but span not available");
331 impl<'a> Resolver<'a> {
332 fn resolve_invoc_to_def(&mut self, invoc: &mut Invocation, scope: Mark, force: bool)
333 -> Result<Def, Determinacy> {
334 let (attr, traits, item) = match invoc.kind {
335 InvocationKind::Attr { ref mut attr, ref traits, ref mut item } => (attr, traits, item),
336 InvocationKind::Bang { ref mac, .. } => {
337 return self.resolve_macro_to_def(scope, &mac.node.path, MacroKind::Bang, force);
339 InvocationKind::Derive { ref path, .. } => {
340 return self.resolve_macro_to_def(scope, path, MacroKind::Derive, force);
345 let path = attr.as_ref().unwrap().path.clone();
346 let mut determinacy = Determinacy::Determined;
347 match self.resolve_macro_to_def(scope, &path, MacroKind::Attr, force) {
348 Ok(def) => return Ok(def),
349 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
350 Err(Determinacy::Determined) if force => return Err(Determinacy::Determined),
351 Err(Determinacy::Determined) => {}
354 let attr_name = match path.segments.len() {
355 1 => path.segments[0].identifier.name,
356 _ => return Err(determinacy),
359 match self.resolve_macro(scope, path, MacroKind::Derive, force) {
360 Ok(ext) => if let SyntaxExtension::ProcMacroDerive(_, ref inert_attrs) = *ext {
361 if inert_attrs.contains(&attr_name) {
362 // FIXME(jseyfried) Avoid `mem::replace` here.
363 let dummy_item = placeholder(ExpansionKind::Items, ast::DUMMY_NODE_ID)
364 .make_items().pop().unwrap();
365 let dummy_item = Annotatable::Item(dummy_item);
366 *item = mem::replace(item, dummy_item).map_attrs(|mut attrs| {
367 let inert_attr = attr.take().unwrap();
368 attr::mark_known(&inert_attr);
369 if self.proc_macro_enabled {
370 *attr = find_attr_invoc(&mut attrs);
372 attrs.push(inert_attr);
376 return Err(Determinacy::Undetermined);
378 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
379 Err(Determinacy::Determined) => {}
386 fn resolve_macro_to_def(&mut self, scope: Mark, path: &ast::Path, kind: MacroKind, force: bool)
387 -> Result<Def, Determinacy> {
388 let def = self.resolve_macro_to_def_inner(scope, path, kind, force);
389 if def != Err(Determinacy::Undetermined) {
390 // Do not report duplicated errors on every undetermined resolution.
391 path.segments.iter().find(|segment| segment.parameters.is_some()).map(|segment| {
392 self.session.span_err(segment.parameters.as_ref().unwrap().span(),
393 "generic arguments in macro path");
399 fn resolve_macro_to_def_inner(&mut self, scope: Mark, path: &ast::Path,
400 kind: MacroKind, force: bool)
401 -> Result<Def, Determinacy> {
402 let ast::Path { ref segments, span } = *path;
403 let path: Vec<_> = segments.iter().map(|seg| respan(seg.span, seg.identifier)).collect();
404 let invocation = self.invocations[&scope];
405 let module = invocation.module.get();
406 self.current_module = if module.is_trait() { module.parent.unwrap() } else { module };
409 if !self.use_extern_macros && self.gated_errors.insert(span) {
410 let msg = "non-ident macro paths are experimental";
411 let feature = "use_extern_macros";
412 emit_feature_err(&self.session.parse_sess, feature, span, GateIssue::Language, msg);
413 self.found_unresolved_macro = true;
414 return Err(Determinacy::Determined);
417 let def = match self.resolve_path(&path, Some(MacroNS), false, span) {
418 PathResult::NonModule(path_res) => match path_res.base_def() {
419 Def::Err => Err(Determinacy::Determined),
422 PathResult::Module(..) => unreachable!(),
423 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
425 self.found_unresolved_macro = true;
426 Err(Determinacy::Determined)
429 let path = path.iter().map(|p| p.node).collect::<Vec<_>>();
430 self.current_module.nearest_item_scope().macro_resolutions.borrow_mut()
431 .push((path.into_boxed_slice(), span));
435 let legacy_resolution = self.resolve_legacy_scope(&invocation.legacy_scope,
438 let result = if let Some(MacroBinding::Legacy(binding)) = legacy_resolution {
439 Ok(Def::Macro(binding.def_id, MacroKind::Bang))
441 match self.resolve_lexical_macro_path_segment(path[0].node, MacroNS, false, span) {
442 Ok(binding) => Ok(binding.binding().def_ignoring_ambiguity()),
443 Err(Determinacy::Undetermined) if !force => return Err(Determinacy::Undetermined),
445 self.found_unresolved_macro = true;
446 Err(Determinacy::Determined)
451 self.current_module.nearest_item_scope().legacy_macro_resolutions.borrow_mut()
452 .push((scope, path[0].node, span, kind));
457 // Resolve the initial segment of a non-global macro path (e.g. `foo` in `foo::bar!();`)
458 pub fn resolve_lexical_macro_path_segment(&mut self,
463 -> Result<MacroBinding<'a>, Determinacy> {
464 ident = ident.modern();
465 let mut module = Some(self.current_module);
466 let mut potential_illegal_shadower = Err(Determinacy::Determined);
468 if record_used { Determinacy::Determined } else { Determinacy::Undetermined };
470 let orig_current_module = self.current_module;
471 let result = if let Some(module) = module {
472 self.current_module = module; // Lexical resolutions can never be a privacy error.
473 // Since expanded macros may not shadow the lexical scope and
474 // globs may not shadow global macros (both enforced below),
475 // we resolve with restricted shadowing (indicated by the penultimate argument).
476 self.resolve_ident_in_module_unadjusted(
477 module, ident, ns, true, record_used, path_span,
478 ).map(MacroBinding::Modern)
480 self.global_macros.get(&ident.name).cloned().ok_or(determinacy)
481 .map(MacroBinding::Global)
483 self.current_module = orig_current_module;
485 match result.map(MacroBinding::binding) {
490 if let Ok(MacroBinding::Modern(shadower)) = potential_illegal_shadower {
491 if shadower.def() != binding.def() {
492 let name = ident.name;
493 self.ambiguity_errors.push(AmbiguityError {
501 return potential_illegal_shadower;
504 if binding.expansion != Mark::root() ||
505 (binding.is_glob_import() && module.unwrap().def().is_some()) {
506 potential_illegal_shadower = result;
511 Err(Determinacy::Undetermined) => return Err(Determinacy::Undetermined),
512 Err(Determinacy::Determined) => {}
515 module = match module {
516 Some(module) => self.hygienic_lexical_parent(module, &mut ident.ctxt),
517 None => return potential_illegal_shadower,
522 pub fn resolve_legacy_scope(&mut self,
523 mut scope: &'a Cell<LegacyScope<'a>>,
526 -> Option<MacroBinding<'a>> {
527 let ident = ident.modern();
528 let mut possible_time_travel = None;
529 let mut relative_depth: u32 = 0;
530 let mut binding = None;
533 LegacyScope::Empty => break,
534 LegacyScope::Expansion(invocation) => {
535 match invocation.expansion.get() {
536 LegacyScope::Invocation(_) => scope.set(invocation.legacy_scope.get()),
537 LegacyScope::Empty => {
538 if possible_time_travel.is_none() {
539 possible_time_travel = Some(scope);
541 scope = &invocation.legacy_scope;
545 scope = &invocation.expansion;
549 LegacyScope::Invocation(invocation) => {
550 relative_depth = relative_depth.saturating_sub(1);
551 scope = &invocation.legacy_scope;
553 LegacyScope::Binding(potential_binding) => {
554 if potential_binding.ident == ident {
555 if (!self.use_extern_macros || record_used) && relative_depth > 0 {
556 self.disallowed_shadowing.push(potential_binding);
558 binding = Some(potential_binding);
561 scope = &potential_binding.parent;
566 let binding = if let Some(binding) = binding {
567 MacroBinding::Legacy(binding)
568 } else if let Some(binding) = self.global_macros.get(&ident.name).cloned() {
569 if !self.use_extern_macros {
570 self.record_use(ident, MacroNS, binding, DUMMY_SP);
572 MacroBinding::Global(binding)
577 if !self.use_extern_macros {
578 if let Some(scope) = possible_time_travel {
579 // Check for disallowed shadowing later
580 self.lexical_macro_resolutions.push((ident, scope));
587 pub fn finalize_current_module_macro_resolutions(&mut self) {
588 let module = self.current_module;
589 for &(ref path, span) in module.macro_resolutions.borrow().iter() {
590 let path = path.iter().map(|p| respan(span, *p)).collect::<Vec<_>>();
591 match self.resolve_path(&path, Some(MacroNS), true, span) {
592 PathResult::NonModule(_) => {},
593 PathResult::Failed(span, msg, _) => {
594 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
600 for &(mark, ident, span, kind) in module.legacy_macro_resolutions.borrow().iter() {
601 let legacy_scope = &self.invocations[&mark].legacy_scope;
602 let legacy_resolution = self.resolve_legacy_scope(legacy_scope, ident, true);
603 let resolution = self.resolve_lexical_macro_path_segment(ident, MacroNS, true, span);
604 match (legacy_resolution, resolution) {
605 (Some(MacroBinding::Legacy(legacy_binding)), Ok(MacroBinding::Modern(binding))) => {
606 let msg1 = format!("`{}` could refer to the macro defined here", ident);
607 let msg2 = format!("`{}` could also refer to the macro imported here", ident);
608 self.session.struct_span_err(span, &format!("`{}` is ambiguous", ident))
609 .span_note(legacy_binding.span, &msg1)
610 .span_note(binding.span, &msg2)
613 (Some(MacroBinding::Global(binding)), Ok(MacroBinding::Global(_))) => {
614 self.record_use(ident, MacroNS, binding, span);
615 self.err_if_macro_use_proc_macro(ident.name, span, binding);
618 let msg = match kind {
620 format!("cannot find macro `{}!` in this scope", ident),
622 format!("cannot find attribute macro `{}` in this scope", ident),
624 format!("cannot find derive macro `{}` in this scope", ident),
626 let mut err = self.session.struct_span_err(span, &msg);
627 self.suggest_macro_name(&ident.name.as_str(), kind, &mut err, span);
635 fn suggest_macro_name(&mut self, name: &str, kind: MacroKind,
636 err: &mut DiagnosticBuilder<'a>, span: Span) {
637 // First check if this is a locally-defined bang macro.
638 let suggestion = if let MacroKind::Bang = kind {
639 find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, None)
642 // Then check global macros.
644 // FIXME: get_macro needs an &mut Resolver, can we do it without cloning?
645 let global_macros = self.global_macros.clone();
646 let names = global_macros.iter().filter_map(|(name, binding)| {
647 if binding.get_macro(self).kind() == kind {
653 find_best_match_for_name(names, name, None)
654 // Then check modules.
656 if !self.use_extern_macros {
659 let is_macro = |def| {
660 if let Def::Macro(_, def_kind) = def {
666 let ident = Ident::from_str(name);
667 self.lookup_typo_candidate(&vec![respan(span, ident)], MacroNS, is_macro, span)
670 if let Some(suggestion) = suggestion {
671 if suggestion != name {
672 if let MacroKind::Bang = kind {
673 err.span_suggestion(span, "you could try the macro",
674 format!("{}!", suggestion));
676 err.span_suggestion(span, "try", suggestion.to_string());
679 err.help("have you added the `#[macro_use]` on the module/import?");
684 fn collect_def_ids(&mut self,
686 invocation: &'a InvocationData<'a>,
687 expansion: &Expansion) {
688 let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
689 let InvocationData { def_index, const_expr, .. } = *invocation;
691 let visit_macro_invoc = &mut |invoc: map::MacroInvocationData| {
692 invocations.entry(invoc.mark).or_insert_with(|| {
693 arenas.alloc_invocation_data(InvocationData {
694 def_index: invoc.def_index,
695 const_expr: invoc.const_expr,
696 module: Cell::new(graph_root),
697 expansion: Cell::new(LegacyScope::Empty),
698 legacy_scope: Cell::new(LegacyScope::Empty),
703 let mut def_collector = DefCollector::new(&mut self.definitions, mark);
704 def_collector.visit_macro_invoc = Some(visit_macro_invoc);
705 def_collector.with_parent(def_index, |def_collector| {
707 if let Expansion::Expr(ref expr) = *expansion {
708 def_collector.visit_const_expr(expr);
711 expansion.visit_with(def_collector)
715 pub fn define_macro(&mut self,
718 legacy_scope: &mut LegacyScope<'a>) {
719 self.local_macro_def_scopes.insert(item.id, self.current_module);
720 let ident = item.ident;
721 if ident.name == "macro_rules" {
722 self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
725 let def_id = self.definitions.local_def_id(item.id);
726 let ext = Rc::new(macro_rules::compile(&self.session.parse_sess,
727 &self.session.features,
729 self.macro_map.insert(def_id, ext);
731 let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
733 let ident = ident.modern();
734 self.macro_names.insert(ident);
735 *legacy_scope = LegacyScope::Binding(self.arenas.alloc_legacy_binding(LegacyBinding {
736 parent: Cell::new(*legacy_scope), ident: ident, def_id: def_id, span: item.span,
738 if attr::contains_name(&item.attrs, "macro_export") {
739 let def = Def::Macro(def_id, MacroKind::Bang);
741 .push(Export { ident: ident.modern(), def: def, span: item.span });
743 self.unused_macros.insert(def_id);
746 let module = self.current_module;
747 let def = Def::Macro(def_id, MacroKind::Bang);
748 let vis = self.resolve_visibility(&item.vis);
749 if vis != ty::Visibility::Public {
750 self.unused_macros.insert(def_id);
752 self.define(module, ident, MacroNS, (def, vis, item.span, expansion));
756 /// Error if `ext` is a Macros 1.1 procedural macro being imported by `#[macro_use]`
757 fn err_if_macro_use_proc_macro(&mut self, name: Name, use_span: Span,
758 binding: &NameBinding<'a>) {
759 use self::SyntaxExtension::*;
761 let krate = binding.def().def_id().krate;
763 // Plugin-based syntax extensions are exempt from this check
764 if krate == BUILTIN_MACROS_CRATE { return; }
766 let ext = binding.get_macro(self);
769 // If `ext` is a procedural macro, check if we've already warned about it
770 AttrProcMacro(_) | ProcMacro(_) => if !self.warned_proc_macros.insert(name) { return; },
774 let warn_msg = match *ext {
775 AttrProcMacro(_) => "attribute procedural macros cannot be \
776 imported with `#[macro_use]`",
777 ProcMacro(_) => "procedural macros cannot be imported with `#[macro_use]`",
781 let crate_name = self.cstore.crate_name_untracked(krate);
783 self.session.struct_span_err(use_span, warn_msg)
784 .help(&format!("instead, import the procedural macro like any other item: \
785 `use {}::{};`", crate_name, name))
789 fn gate_legacy_custom_derive(&mut self, name: Symbol, span: Span) {
790 if !self.session.features.borrow().custom_derive {
791 let sess = &self.session.parse_sess;
792 let explain = feature_gate::EXPLAIN_CUSTOM_DERIVE;
793 emit_feature_err(sess, "custom_derive", span, GateIssue::Language, explain);
794 } else if !self.is_whitelisted_legacy_custom_derive(name) {
795 self.session.span_warn(span, feature_gate::EXPLAIN_DEPR_CUSTOM_DERIVE);