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_data_structures::indexed_vec::Idx;
17 use rustc::hir::def_id::{DefId, BUILTIN_MACROS_CRATE, CRATE_DEF_INDEX, DefIndex};
18 use rustc::hir::def::{Def, Export};
19 use rustc::hir::map::{self, DefCollector};
20 use rustc::{ty, lint};
21 use syntax::ast::{self, Name, Ident};
22 use syntax::attr::{self, HasAttrs};
23 use syntax::codemap::respan;
24 use syntax::errors::DiagnosticBuilder;
25 use syntax::ext::base::{self, Annotatable, Determinacy, MultiModifier, MultiDecorator};
26 use syntax::ext::base::{MacroKind, SyntaxExtension, Resolver as SyntaxResolver};
27 use syntax::ext::expand::{Expansion, ExpansionKind, Invocation, InvocationKind, find_attr_invoc};
28 use syntax::ext::hygiene::Mark;
29 use syntax::ext::placeholders::placeholder;
30 use syntax::ext::tt::macro_rules;
31 use syntax::feature_gate::{self, emit_feature_err, GateIssue};
32 use syntax::fold::{self, Folder};
33 use syntax::parse::parser::PathStyle;
34 use syntax::parse::token::{self, Token};
36 use syntax::symbol::{Symbol, keywords};
37 use syntax::tokenstream::{TokenStream, TokenTree, Delimited};
38 use syntax::util::lev_distance::find_best_match_for_name;
39 use syntax_pos::{Span, DUMMY_SP};
46 pub struct InvocationData<'a> {
47 pub module: Cell<Module<'a>>,
48 pub def_index: DefIndex,
49 // True if this expansion is in a `const_expr` position, for example `[u32; m!()]`.
50 // c.f. `DefCollector::visit_const_expr`.
52 // The scope in which the invocation path is resolved.
53 pub legacy_scope: Cell<LegacyScope<'a>>,
54 // The smallest scope that includes this invocation's expansion,
55 // or `Empty` if this invocation has not been expanded yet.
56 pub expansion: Cell<LegacyScope<'a>>,
59 impl<'a> InvocationData<'a> {
60 pub fn root(graph_root: Module<'a>) -> Self {
62 module: Cell::new(graph_root),
63 def_index: CRATE_DEF_INDEX,
65 legacy_scope: Cell::new(LegacyScope::Empty),
66 expansion: Cell::new(LegacyScope::Empty),
71 #[derive(Copy, Clone)]
72 pub enum LegacyScope<'a> {
74 Invocation(&'a InvocationData<'a>), // The scope of the invocation, not including its expansion
75 Expansion(&'a InvocationData<'a>), // The scope of the invocation, including its expansion
76 Binding(&'a LegacyBinding<'a>),
79 pub struct LegacyBinding<'a> {
80 pub parent: Cell<LegacyScope<'a>>,
86 pub struct ProcMacError {
91 warn_msg: &'static str,
94 #[derive(Copy, Clone)]
95 pub enum MacroBinding<'a> {
96 Legacy(&'a LegacyBinding<'a>),
97 Global(&'a NameBinding<'a>),
98 Modern(&'a NameBinding<'a>),
101 impl<'a> MacroBinding<'a> {
102 pub fn span(self) -> Span {
104 MacroBinding::Legacy(binding) => binding.span,
105 MacroBinding::Global(binding) | MacroBinding::Modern(binding) => binding.span,
109 pub fn binding(self) -> &'a NameBinding<'a> {
111 MacroBinding::Global(binding) | MacroBinding::Modern(binding) => binding,
112 MacroBinding::Legacy(_) => panic!("unexpected MacroBinding::Legacy"),
117 impl<'a> base::Resolver for Resolver<'a> {
118 fn next_node_id(&mut self) -> ast::NodeId {
119 self.session.next_node_id()
122 fn get_module_scope(&mut self, id: ast::NodeId) -> Mark {
123 let mark = Mark::fresh(Mark::root());
124 let module = self.module_map[&self.definitions.local_def_id(id)];
125 self.invocations.insert(mark, self.arenas.alloc_invocation_data(InvocationData {
126 module: Cell::new(module),
127 def_index: module.def_id().unwrap().index,
129 legacy_scope: Cell::new(LegacyScope::Empty),
130 expansion: Cell::new(LegacyScope::Empty),
135 fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> {
136 struct EliminateCrateVar<'b, 'a: 'b>(&'b mut Resolver<'a>, Span);
138 impl<'a, 'b> Folder for EliminateCrateVar<'a, 'b> {
139 fn fold_path(&mut self, mut path: ast::Path) -> ast::Path {
140 let ident = path.segments[0].identifier;
141 if ident.name == keywords::DollarCrate.name() {
142 path.segments[0].identifier.name = keywords::CrateRoot.name();
143 let module = self.0.resolve_crate_root(ident.ctxt);
144 if !module.is_local() {
145 let span = path.segments[0].span;
146 path.segments.insert(1, match module.kind {
147 ModuleKind::Def(_, name) => ast::PathSegment::from_ident(
148 ast::Ident::with_empty_ctxt(name), span
157 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
158 fold::noop_fold_mac(mac, self)
162 EliminateCrateVar(self, item.span).fold_item(item).expect_one("")
165 fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool {
166 self.whitelisted_legacy_custom_derives.contains(&name)
169 fn visit_expansion(&mut self, mark: Mark, expansion: &Expansion, derives: &[Mark]) {
170 let invocation = self.invocations[&mark];
171 self.collect_def_ids(mark, invocation, expansion);
173 self.current_module = invocation.module.get();
174 self.current_module.unresolved_invocations.borrow_mut().remove(&mark);
175 self.current_module.unresolved_invocations.borrow_mut().extend(derives);
176 for &derive in derives {
177 self.invocations.insert(derive, invocation);
179 let mut visitor = BuildReducedGraphVisitor {
181 legacy_scope: LegacyScope::Invocation(invocation),
184 expansion.visit_with(&mut visitor);
185 invocation.expansion.set(visitor.legacy_scope);
188 fn add_builtin(&mut self, ident: ast::Ident, ext: Rc<SyntaxExtension>) {
190 krate: BUILTIN_MACROS_CRATE,
191 index: DefIndex::new(self.macro_map.len()),
193 let kind = ext.kind();
194 self.macro_map.insert(def_id, ext);
195 let binding = self.arenas.alloc_name_binding(NameBinding {
196 kind: NameBindingKind::Def(Def::Macro(def_id, kind)),
198 vis: ty::Visibility::Invisible,
199 expansion: Mark::root(),
201 self.global_macros.insert(ident.name, binding);
204 fn resolve_imports(&mut self) {
205 ImportResolver { resolver: self }.resolve_imports()
208 // Resolves attribute and derive legacy macros from `#![plugin(..)]`.
209 fn find_legacy_attr_invoc(&mut self, attrs: &mut Vec<ast::Attribute>)
210 -> Option<ast::Attribute> {
211 for i in 0..attrs.len() {
212 let name = unwrap_or!(attrs[i].name(), continue);
214 if self.session.plugin_attributes.borrow().iter()
215 .any(|&(ref attr_nm, _)| name == &**attr_nm) {
216 attr::mark_known(&attrs[i]);
219 match self.global_macros.get(&name).cloned() {
220 Some(binding) => match *binding.get_macro(self) {
221 MultiModifier(..) | MultiDecorator(..) | SyntaxExtension::AttrProcMacro(..) => {
222 return Some(attrs.remove(i))
230 // Check for legacy derives
231 for i in 0..attrs.len() {
232 let name = unwrap_or!(attrs[i].name(), continue);
234 if name == "derive" {
235 let result = attrs[i].parse_list(&self.session.parse_sess, |parser| {
236 parser.parse_path_allowing_meta(PathStyle::Mod)
239 let mut traits = match result {
240 Ok(traits) => traits,
247 for j in 0..traits.len() {
248 if traits[j].segments.len() > 1 {
251 let trait_name = traits[j].segments[0].identifier.name;
252 let legacy_name = Symbol::intern(&format!("derive_{}", trait_name));
253 if !self.global_macros.contains_key(&legacy_name) {
256 let span = traits.remove(j).span;
257 self.gate_legacy_custom_derive(legacy_name, span);
258 if traits.is_empty() {
261 let mut tokens = Vec::new();
262 for (j, path) in traits.iter().enumerate() {
264 tokens.push(TokenTree::Token(attrs[i].span, Token::Comma).into());
266 for (k, segment) in path.segments.iter().enumerate() {
268 tokens.push(TokenTree::Token(path.span, Token::ModSep).into());
270 let tok = Token::Ident(segment.identifier);
271 tokens.push(TokenTree::Token(path.span, tok).into());
274 attrs[i].tokens = TokenTree::Delimited(attrs[i].span, Delimited {
276 tts: TokenStream::concat(tokens).into(),
279 return Some(ast::Attribute {
280 path: ast::Path::from_ident(span, Ident::with_empty_ctxt(legacy_name)),
281 tokens: TokenStream::empty(),
282 id: attr::mk_attr_id(),
283 style: ast::AttrStyle::Outer,
284 is_sugared_doc: false,
294 fn resolve_invoc(&mut self, invoc: &mut Invocation, scope: Mark, force: bool)
295 -> Result<Option<Rc<SyntaxExtension>>, Determinacy> {
296 let def = match invoc.kind {
297 InvocationKind::Attr { attr: None, .. } => return Ok(None),
298 _ => self.resolve_invoc_to_def(invoc, scope, force)?,
301 self.macro_defs.insert(invoc.expansion_data.mark, def.def_id());
302 let normal_module_def_id =
303 self.macro_def_scope(invoc.expansion_data.mark).normal_ancestor_id;
304 self.definitions.add_macro_def_scope(invoc.expansion_data.mark, normal_module_def_id);
306 self.unused_macros.remove(&def.def_id());
307 let ext = self.get_macro(def);
309 invoc.expansion_data.mark.set_modern();
314 fn resolve_macro(&mut self, scope: Mark, path: &ast::Path, kind: MacroKind, force: bool)
315 -> Result<Rc<SyntaxExtension>, Determinacy> {
316 self.resolve_macro_to_def(scope, path, kind, force).map(|def| {
317 self.unused_macros.remove(&def.def_id());
322 fn check_unused_macros(&self) {
323 for did in self.unused_macros.iter() {
324 let id_span = match *self.macro_map[did] {
325 SyntaxExtension::NormalTT { def_info, .. } => def_info,
326 SyntaxExtension::DeclMacro(.., osp) => osp,
329 if let Some((id, span)) = id_span {
330 let lint = lint::builtin::UNUSED_MACROS;
331 let msg = "unused macro definition";
332 self.session.buffer_lint(lint, id, span, msg);
334 bug!("attempted to create unused macro error, but span not available");
340 impl<'a> Resolver<'a> {
341 fn resolve_invoc_to_def(&mut self, invoc: &mut Invocation, scope: Mark, force: bool)
342 -> Result<Def, Determinacy> {
343 let (attr, traits, item) = match invoc.kind {
344 InvocationKind::Attr { ref mut attr, ref traits, ref mut item } => (attr, traits, item),
345 InvocationKind::Bang { ref mac, .. } => {
346 return self.resolve_macro_to_def(scope, &mac.node.path, MacroKind::Bang, force);
348 InvocationKind::Derive { ref path, .. } => {
349 return self.resolve_macro_to_def(scope, path, MacroKind::Derive, force);
354 let path = attr.as_ref().unwrap().path.clone();
355 let mut determinacy = Determinacy::Determined;
356 match self.resolve_macro_to_def(scope, &path, MacroKind::Attr, force) {
357 Ok(def) => return Ok(def),
358 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
359 Err(Determinacy::Determined) if force => return Err(Determinacy::Determined),
360 Err(Determinacy::Determined) => {}
363 let attr_name = match path.segments.len() {
364 1 => path.segments[0].identifier.name,
365 _ => return Err(determinacy),
368 match self.resolve_macro(scope, path, MacroKind::Derive, force) {
369 Ok(ext) => if let SyntaxExtension::ProcMacroDerive(_, ref inert_attrs) = *ext {
370 if inert_attrs.contains(&attr_name) {
371 // FIXME(jseyfried) Avoid `mem::replace` here.
372 let dummy_item = placeholder(ExpansionKind::Items, ast::DUMMY_NODE_ID)
373 .make_items().pop().unwrap();
374 let dummy_item = Annotatable::Item(dummy_item);
375 *item = mem::replace(item, dummy_item).map_attrs(|mut attrs| {
376 let inert_attr = attr.take().unwrap();
377 attr::mark_known(&inert_attr);
378 if self.proc_macro_enabled {
379 *attr = find_attr_invoc(&mut attrs);
381 attrs.push(inert_attr);
385 return Err(Determinacy::Undetermined);
387 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
388 Err(Determinacy::Determined) => {}
395 fn resolve_macro_to_def(&mut self, scope: Mark, path: &ast::Path, kind: MacroKind, force: bool)
396 -> Result<Def, Determinacy> {
397 let def = self.resolve_macro_to_def_inner(scope, path, kind, force);
398 if def != Err(Determinacy::Undetermined) {
399 // Do not report duplicated errors on every undetermined resolution.
400 path.segments.iter().find(|segment| segment.parameters.is_some()).map(|segment| {
401 self.session.span_err(segment.parameters.as_ref().unwrap().span(),
402 "generic arguments in macro path");
408 fn resolve_macro_to_def_inner(&mut self, scope: Mark, path: &ast::Path,
409 kind: MacroKind, force: bool)
410 -> Result<Def, Determinacy> {
411 let ast::Path { ref segments, span } = *path;
412 let path: Vec<_> = segments.iter().map(|seg| respan(seg.span, seg.identifier)).collect();
413 let invocation = self.invocations[&scope];
414 let module = invocation.module.get();
415 self.current_module = if module.is_trait() { module.parent.unwrap() } else { module };
418 if !self.use_extern_macros && self.gated_errors.insert(span) {
419 let msg = "non-ident macro paths are experimental";
420 let feature = "use_extern_macros";
421 emit_feature_err(&self.session.parse_sess, feature, span, GateIssue::Language, msg);
422 self.found_unresolved_macro = true;
423 return Err(Determinacy::Determined);
426 let def = match self.resolve_path(&path, Some(MacroNS), false, span) {
427 PathResult::NonModule(path_res) => match path_res.base_def() {
428 Def::Err => Err(Determinacy::Determined),
431 PathResult::Module(..) => unreachable!(),
432 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
434 self.found_unresolved_macro = true;
435 Err(Determinacy::Determined)
438 let path = path.iter().map(|p| p.node).collect::<Vec<_>>();
439 self.current_module.nearest_item_scope().macro_resolutions.borrow_mut()
440 .push((path.into_boxed_slice(), span));
444 let legacy_resolution = self.resolve_legacy_scope(&invocation.legacy_scope,
447 let result = if let Some(MacroBinding::Legacy(binding)) = legacy_resolution {
448 Ok(Def::Macro(binding.def_id, MacroKind::Bang))
450 match self.resolve_lexical_macro_path_segment(path[0].node, MacroNS, false, span) {
451 Ok(binding) => Ok(binding.binding().def_ignoring_ambiguity()),
452 Err(Determinacy::Undetermined) if !force => return Err(Determinacy::Undetermined),
454 self.found_unresolved_macro = true;
455 Err(Determinacy::Determined)
460 self.current_module.nearest_item_scope().legacy_macro_resolutions.borrow_mut()
461 .push((scope, path[0].node, span, kind));
466 // Resolve the initial segment of a non-global macro path (e.g. `foo` in `foo::bar!();`)
467 pub fn resolve_lexical_macro_path_segment(&mut self,
472 -> Result<MacroBinding<'a>, Determinacy> {
473 ident = ident.modern();
474 let mut module = Some(self.current_module);
475 let mut potential_illegal_shadower = Err(Determinacy::Determined);
477 if record_used { Determinacy::Determined } else { Determinacy::Undetermined };
479 let orig_current_module = self.current_module;
480 let result = if let Some(module) = module {
481 self.current_module = module; // Lexical resolutions can never be a privacy error.
482 // Since expanded macros may not shadow the lexical scope and
483 // globs may not shadow global macros (both enforced below),
484 // we resolve with restricted shadowing (indicated by the penultimate argument).
485 self.resolve_ident_in_module_unadjusted(
486 module, ident, ns, true, record_used, path_span,
487 ).map(MacroBinding::Modern)
489 self.global_macros.get(&ident.name).cloned().ok_or(determinacy)
490 .map(MacroBinding::Global)
492 self.current_module = orig_current_module;
494 match result.map(MacroBinding::binding) {
499 if let Ok(MacroBinding::Modern(shadower)) = potential_illegal_shadower {
500 if shadower.def() != binding.def() {
501 let name = ident.name;
502 self.ambiguity_errors.push(AmbiguityError {
510 return potential_illegal_shadower;
513 if binding.expansion != Mark::root() ||
514 (binding.is_glob_import() && module.unwrap().def().is_some()) {
515 potential_illegal_shadower = result;
520 Err(Determinacy::Undetermined) => return Err(Determinacy::Undetermined),
521 Err(Determinacy::Determined) => {}
524 module = match module {
525 Some(module) => self.hygienic_lexical_parent(module, &mut ident.ctxt),
526 None => return potential_illegal_shadower,
531 pub fn resolve_legacy_scope(&mut self,
532 mut scope: &'a Cell<LegacyScope<'a>>,
535 -> Option<MacroBinding<'a>> {
536 let ident = ident.modern();
537 let mut possible_time_travel = None;
538 let mut relative_depth: u32 = 0;
539 let mut binding = None;
542 LegacyScope::Empty => break,
543 LegacyScope::Expansion(invocation) => {
544 match invocation.expansion.get() {
545 LegacyScope::Invocation(_) => scope.set(invocation.legacy_scope.get()),
546 LegacyScope::Empty => {
547 if possible_time_travel.is_none() {
548 possible_time_travel = Some(scope);
550 scope = &invocation.legacy_scope;
554 scope = &invocation.expansion;
558 LegacyScope::Invocation(invocation) => {
559 relative_depth = relative_depth.saturating_sub(1);
560 scope = &invocation.legacy_scope;
562 LegacyScope::Binding(potential_binding) => {
563 if potential_binding.ident == ident {
564 if (!self.use_extern_macros || record_used) && relative_depth > 0 {
565 self.disallowed_shadowing.push(potential_binding);
567 binding = Some(potential_binding);
570 scope = &potential_binding.parent;
575 let binding = if let Some(binding) = binding {
576 MacroBinding::Legacy(binding)
577 } else if let Some(binding) = self.global_macros.get(&ident.name).cloned() {
578 if !self.use_extern_macros {
579 self.record_use(ident, MacroNS, binding, DUMMY_SP);
581 MacroBinding::Global(binding)
586 if !self.use_extern_macros {
587 if let Some(scope) = possible_time_travel {
588 // Check for disallowed shadowing later
589 self.lexical_macro_resolutions.push((ident, scope));
596 pub fn finalize_current_module_macro_resolutions(&mut self) {
597 let module = self.current_module;
598 for &(ref path, span) in module.macro_resolutions.borrow().iter() {
599 let path = path.iter().map(|p| respan(span, *p)).collect::<Vec<_>>();
600 match self.resolve_path(&path, Some(MacroNS), true, span) {
601 PathResult::NonModule(_) => {},
602 PathResult::Failed(span, msg, _) => {
603 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
609 for &(mark, ident, span, kind) in module.legacy_macro_resolutions.borrow().iter() {
610 let legacy_scope = &self.invocations[&mark].legacy_scope;
611 let legacy_resolution = self.resolve_legacy_scope(legacy_scope, ident, true);
612 let resolution = self.resolve_lexical_macro_path_segment(ident, MacroNS, true, span);
613 match (legacy_resolution, resolution) {
614 (Some(MacroBinding::Legacy(legacy_binding)), Ok(MacroBinding::Modern(binding))) => {
615 let msg1 = format!("`{}` could refer to the macro defined here", ident);
616 let msg2 = format!("`{}` could also refer to the macro imported here", ident);
617 self.session.struct_span_err(span, &format!("`{}` is ambiguous", ident))
618 .span_note(legacy_binding.span, &msg1)
619 .span_note(binding.span, &msg2)
622 (Some(MacroBinding::Global(binding)), Ok(MacroBinding::Global(_))) => {
623 self.record_use(ident, MacroNS, binding, span);
624 self.err_if_macro_use_proc_macro(ident.name, span, binding);
627 let msg = match kind {
629 format!("cannot find macro `{}!` in this scope", ident),
631 format!("cannot find attribute macro `{}` in this scope", ident),
633 format!("cannot find derive macro `{}` in this scope", ident),
635 let mut err = self.session.struct_span_err(span, &msg);
636 self.suggest_macro_name(&ident.name.as_str(), kind, &mut err, span);
644 fn suggest_macro_name(&mut self, name: &str, kind: MacroKind,
645 err: &mut DiagnosticBuilder<'a>, span: Span) {
646 // First check if this is a locally-defined bang macro.
647 let suggestion = if let MacroKind::Bang = kind {
648 find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, None)
651 // Then check global macros.
653 // FIXME: get_macro needs an &mut Resolver, can we do it without cloning?
654 let global_macros = self.global_macros.clone();
655 let names = global_macros.iter().filter_map(|(name, binding)| {
656 if binding.get_macro(self).kind() == kind {
662 find_best_match_for_name(names, name, None)
663 // Then check modules.
665 if !self.use_extern_macros {
668 let is_macro = |def| {
669 if let Def::Macro(_, def_kind) = def {
675 let ident = Ident::from_str(name);
676 self.lookup_typo_candidate(&vec![respan(span, ident)], MacroNS, is_macro, span)
679 if let Some(suggestion) = suggestion {
680 if suggestion != name {
681 if let MacroKind::Bang = kind {
682 err.span_suggestion(span, "you could try the macro",
683 format!("{}!", suggestion));
685 err.span_suggestion(span, "try", suggestion.to_string());
688 err.help("have you added the `#[macro_use]` on the module/import?");
693 fn collect_def_ids(&mut self,
695 invocation: &'a InvocationData<'a>,
696 expansion: &Expansion) {
697 let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
698 let InvocationData { def_index, const_expr, .. } = *invocation;
700 let visit_macro_invoc = &mut |invoc: map::MacroInvocationData| {
701 invocations.entry(invoc.mark).or_insert_with(|| {
702 arenas.alloc_invocation_data(InvocationData {
703 def_index: invoc.def_index,
704 const_expr: invoc.const_expr,
705 module: Cell::new(graph_root),
706 expansion: Cell::new(LegacyScope::Empty),
707 legacy_scope: Cell::new(LegacyScope::Empty),
712 let mut def_collector = DefCollector::new(&mut self.definitions, mark);
713 def_collector.visit_macro_invoc = Some(visit_macro_invoc);
714 def_collector.with_parent(def_index, |def_collector| {
716 if let Expansion::Expr(ref expr) = *expansion {
717 def_collector.visit_const_expr(expr);
720 expansion.visit_with(def_collector)
724 pub fn define_macro(&mut self,
727 legacy_scope: &mut LegacyScope<'a>) {
728 self.local_macro_def_scopes.insert(item.id, self.current_module);
729 let ident = item.ident;
730 if ident.name == "macro_rules" {
731 self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
734 let def_id = self.definitions.local_def_id(item.id);
735 let ext = Rc::new(macro_rules::compile(&self.session.parse_sess,
736 &self.session.features,
738 self.macro_map.insert(def_id, ext);
740 let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
742 let ident = ident.modern();
743 self.macro_names.insert(ident);
744 *legacy_scope = LegacyScope::Binding(self.arenas.alloc_legacy_binding(LegacyBinding {
745 parent: Cell::new(*legacy_scope), ident: ident, def_id: def_id, span: item.span,
747 if attr::contains_name(&item.attrs, "macro_export") {
748 let def = Def::Macro(def_id, MacroKind::Bang);
750 .push(Export { ident: ident.modern(), def: def, span: item.span });
752 self.unused_macros.insert(def_id);
755 let module = self.current_module;
756 let def = Def::Macro(def_id, MacroKind::Bang);
757 let vis = self.resolve_visibility(&item.vis);
758 if vis != ty::Visibility::Public {
759 self.unused_macros.insert(def_id);
761 self.define(module, ident, MacroNS, (def, vis, item.span, expansion));
765 /// Error if `ext` is a Macros 1.1 procedural macro being imported by `#[macro_use]`
766 fn err_if_macro_use_proc_macro(&mut self, name: Name, use_span: Span,
767 binding: &NameBinding<'a>) {
768 use self::SyntaxExtension::*;
770 let krate = binding.def().def_id().krate;
772 // Plugin-based syntax extensions are exempt from this check
773 if krate == BUILTIN_MACROS_CRATE { return; }
775 let ext = binding.get_macro(self);
778 // If `ext` is a procedural macro, check if we've already warned about it
779 AttrProcMacro(_) | ProcMacro(_) => if !self.warned_proc_macros.insert(name) { return; },
783 let warn_msg = match *ext {
784 AttrProcMacro(_) => "attribute procedural macros cannot be \
785 imported with `#[macro_use]`",
786 ProcMacro(_) => "procedural macros cannot be imported with `#[macro_use]`",
790 let def_id = self.current_module.normal_ancestor_id;
791 let node_id = self.definitions.as_local_node_id(def_id).unwrap();
793 self.proc_mac_errors.push(ProcMacError {
794 crate_name: self.cstore.crate_name_untracked(krate),
802 pub fn report_proc_macro_import(&mut self, krate: &ast::Crate) {
803 for err in self.proc_mac_errors.drain(..) {
804 let (span, found_use) = ::UsePlacementFinder::check(krate, err.module);
806 if let Some(span) = span {
807 let found_use = if found_use { "" } else { "\n" };
808 self.session.struct_span_err(err.use_span, err.warn_msg)
811 "instead, import the procedural macro like any other item",
812 format!("use {}::{};{}", err.crate_name, err.name, found_use),
815 self.session.struct_span_err(err.use_span, err.warn_msg)
816 .help(&format!("instead, import the procedural macro like any other item: \
817 `use {}::{};`", err.crate_name, err.name))
823 fn gate_legacy_custom_derive(&mut self, name: Symbol, span: Span) {
824 if !self.session.features.borrow().custom_derive {
825 let sess = &self.session.parse_sess;
826 let explain = feature_gate::EXPLAIN_CUSTOM_DERIVE;
827 emit_feature_err(sess, "custom_derive", span, GateIssue::Language, explain);
828 } else if !self.is_whitelisted_legacy_custom_derive(name) {
829 self.session.span_warn(span, feature_gate::EXPLAIN_DEPR_CUSTOM_DERIVE);