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 DefIndexAddressSpace};
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, MarkKind};
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};
43 use rustc_data_structures::sync::Lrc;
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, true);
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: Lrc<SyntaxExtension>) {
190 krate: BUILTIN_MACROS_CRATE,
191 index: DefIndex::from_array_index(self.macro_map.len(),
192 DefIndexAddressSpace::Low),
194 let kind = ext.kind();
195 self.macro_map.insert(def_id, ext);
196 let binding = self.arenas.alloc_name_binding(NameBinding {
197 kind: NameBindingKind::Def(Def::Macro(def_id, kind)),
199 vis: ty::Visibility::Invisible,
200 expansion: Mark::root(),
202 self.global_macros.insert(ident.name, binding);
205 fn resolve_imports(&mut self) {
206 ImportResolver { resolver: self }.resolve_imports()
209 // Resolves attribute and derive legacy macros from `#![plugin(..)]`.
210 fn find_legacy_attr_invoc(&mut self, attrs: &mut Vec<ast::Attribute>)
211 -> Option<ast::Attribute> {
212 for i in 0..attrs.len() {
213 let name = unwrap_or!(attrs[i].name(), continue);
215 if self.session.plugin_attributes.borrow().iter()
216 .any(|&(ref attr_nm, _)| name == &**attr_nm) {
217 attr::mark_known(&attrs[i]);
220 match self.global_macros.get(&name).cloned() {
221 Some(binding) => match *binding.get_macro(self) {
222 MultiModifier(..) | MultiDecorator(..) | SyntaxExtension::AttrProcMacro(..) => {
223 return Some(attrs.remove(i))
231 // Check for legacy derives
232 for i in 0..attrs.len() {
233 let name = unwrap_or!(attrs[i].name(), continue);
235 if name == "derive" {
236 let result = attrs[i].parse_list(&self.session.parse_sess, |parser| {
237 parser.parse_path_allowing_meta(PathStyle::Mod)
240 let mut traits = match result {
241 Ok(traits) => traits,
248 for j in 0..traits.len() {
249 if traits[j].segments.len() > 1 {
252 let trait_name = traits[j].segments[0].identifier.name;
253 let legacy_name = Symbol::intern(&format!("derive_{}", trait_name));
254 if !self.global_macros.contains_key(&legacy_name) {
257 let span = traits.remove(j).span;
258 self.gate_legacy_custom_derive(legacy_name, span);
259 if traits.is_empty() {
262 let mut tokens = Vec::new();
263 for (j, path) in traits.iter().enumerate() {
265 tokens.push(TokenTree::Token(attrs[i].span, Token::Comma).into());
267 for (k, segment) in path.segments.iter().enumerate() {
269 tokens.push(TokenTree::Token(path.span, Token::ModSep).into());
271 let tok = Token::Ident(segment.identifier);
272 tokens.push(TokenTree::Token(path.span, tok).into());
275 attrs[i].tokens = TokenTree::Delimited(attrs[i].span, Delimited {
277 tts: TokenStream::concat(tokens).into(),
280 return Some(ast::Attribute {
281 path: ast::Path::from_ident(span, Ident::with_empty_ctxt(legacy_name)),
282 tokens: TokenStream::empty(),
283 id: attr::mk_attr_id(),
284 style: ast::AttrStyle::Outer,
285 is_sugared_doc: false,
295 fn resolve_invoc(&mut self, invoc: &mut Invocation, scope: Mark, force: bool)
296 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
297 let def = match invoc.kind {
298 InvocationKind::Attr { attr: None, .. } => return Ok(None),
299 _ => self.resolve_invoc_to_def(invoc, scope, force)?,
301 let def_id = def.def_id();
303 self.macro_defs.insert(invoc.expansion_data.mark, def_id);
304 let normal_module_def_id =
305 self.macro_def_scope(invoc.expansion_data.mark).normal_ancestor_id;
306 self.definitions.add_macro_def_scope(invoc.expansion_data.mark, normal_module_def_id);
308 self.unused_macros.remove(&def_id);
309 let ext = self.get_macro(def);
311 invoc.expansion_data.mark.set_kind(MarkKind::Modern);
312 } else if def_id.krate == BUILTIN_MACROS_CRATE {
313 invoc.expansion_data.mark.set_kind(MarkKind::Builtin);
318 fn resolve_macro(&mut self, scope: Mark, path: &ast::Path, kind: MacroKind, force: bool)
319 -> Result<Lrc<SyntaxExtension>, Determinacy> {
320 self.resolve_macro_to_def(scope, path, kind, force).map(|def| {
321 self.unused_macros.remove(&def.def_id());
326 fn check_unused_macros(&self) {
327 for did in self.unused_macros.iter() {
328 let id_span = match *self.macro_map[did] {
329 SyntaxExtension::NormalTT { def_info, .. } => def_info,
330 SyntaxExtension::DeclMacro(.., osp) => osp,
333 if let Some((id, span)) = id_span {
334 let lint = lint::builtin::UNUSED_MACROS;
335 let msg = "unused macro definition";
336 self.session.buffer_lint(lint, id, span, msg);
338 bug!("attempted to create unused macro error, but span not available");
344 impl<'a> Resolver<'a> {
345 fn resolve_invoc_to_def(&mut self, invoc: &mut Invocation, scope: Mark, force: bool)
346 -> Result<Def, Determinacy> {
347 let (attr, traits, item) = match invoc.kind {
348 InvocationKind::Attr { ref mut attr, ref traits, ref mut item } => (attr, traits, item),
349 InvocationKind::Bang { ref mac, .. } => {
350 return self.resolve_macro_to_def(scope, &mac.node.path, MacroKind::Bang, force);
352 InvocationKind::Derive { ref path, .. } => {
353 return self.resolve_macro_to_def(scope, path, MacroKind::Derive, force);
358 let path = attr.as_ref().unwrap().path.clone();
359 let mut determinacy = Determinacy::Determined;
360 match self.resolve_macro_to_def(scope, &path, MacroKind::Attr, force) {
361 Ok(def) => return Ok(def),
362 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
363 Err(Determinacy::Determined) if force => return Err(Determinacy::Determined),
364 Err(Determinacy::Determined) => {}
367 let attr_name = match path.segments.len() {
368 1 => path.segments[0].identifier.name,
369 _ => return Err(determinacy),
372 match self.resolve_macro(scope, path, MacroKind::Derive, force) {
373 Ok(ext) => if let SyntaxExtension::ProcMacroDerive(_, ref inert_attrs) = *ext {
374 if inert_attrs.contains(&attr_name) {
375 // FIXME(jseyfried) Avoid `mem::replace` here.
376 let dummy_item = placeholder(ExpansionKind::Items, ast::DUMMY_NODE_ID)
377 .make_items().pop().unwrap();
378 let dummy_item = Annotatable::Item(dummy_item);
379 *item = mem::replace(item, dummy_item).map_attrs(|mut attrs| {
380 let inert_attr = attr.take().unwrap();
381 attr::mark_known(&inert_attr);
382 if self.proc_macro_enabled {
383 *attr = find_attr_invoc(&mut attrs);
385 attrs.push(inert_attr);
389 return Err(Determinacy::Undetermined);
391 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
392 Err(Determinacy::Determined) => {}
399 fn resolve_macro_to_def(&mut self, scope: Mark, path: &ast::Path, kind: MacroKind, force: bool)
400 -> Result<Def, Determinacy> {
401 let def = self.resolve_macro_to_def_inner(scope, path, kind, force);
402 if def != Err(Determinacy::Undetermined) {
403 // Do not report duplicated errors on every undetermined resolution.
404 path.segments.iter().find(|segment| segment.parameters.is_some()).map(|segment| {
405 self.session.span_err(segment.parameters.as_ref().unwrap().span(),
406 "generic arguments in macro path");
412 pub fn resolve_macro_to_def_inner(&mut self, scope: Mark, path: &ast::Path,
413 kind: MacroKind, force: bool)
414 -> Result<Def, Determinacy> {
415 let ast::Path { ref segments, span } = *path;
416 let path: Vec<_> = segments.iter().map(|seg| respan(seg.span, seg.identifier)).collect();
417 let invocation = self.invocations[&scope];
418 let module = invocation.module.get();
419 self.current_module = if module.is_trait() { module.parent.unwrap() } else { module };
422 if !self.use_extern_macros && self.gated_errors.insert(span) {
423 let msg = "non-ident macro paths are experimental";
424 let feature = "use_extern_macros";
425 emit_feature_err(&self.session.parse_sess, feature, span, GateIssue::Language, msg);
426 self.found_unresolved_macro = true;
427 return Err(Determinacy::Determined);
430 let def = match self.resolve_path(&path, Some(MacroNS), false, span) {
431 PathResult::NonModule(path_res) => match path_res.base_def() {
432 Def::Err => Err(Determinacy::Determined),
434 if path_res.unresolved_segments() > 0 {
435 self.found_unresolved_macro = true;
436 self.session.span_err(span, "fail to resolve non-ident macro path");
437 Err(Determinacy::Determined)
443 PathResult::Module(..) => unreachable!(),
444 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
446 self.found_unresolved_macro = true;
447 Err(Determinacy::Determined)
450 let path = path.iter().map(|p| p.node).collect::<Vec<_>>();
451 self.current_module.nearest_item_scope().macro_resolutions.borrow_mut()
452 .push((path.into_boxed_slice(), span));
456 let legacy_resolution = self.resolve_legacy_scope(&invocation.legacy_scope,
459 let result = if let Some(MacroBinding::Legacy(binding)) = legacy_resolution {
460 Ok(Def::Macro(binding.def_id, MacroKind::Bang))
462 match self.resolve_lexical_macro_path_segment(path[0].node, MacroNS, false, span) {
463 Ok(binding) => Ok(binding.binding().def_ignoring_ambiguity()),
464 Err(Determinacy::Undetermined) if !force => return Err(Determinacy::Undetermined),
466 self.found_unresolved_macro = true;
467 Err(Determinacy::Determined)
472 self.current_module.nearest_item_scope().legacy_macro_resolutions.borrow_mut()
473 .push((scope, path[0].node, span, kind));
478 // Resolve the initial segment of a non-global macro path (e.g. `foo` in `foo::bar!();`)
479 pub fn resolve_lexical_macro_path_segment(&mut self,
484 -> Result<MacroBinding<'a>, Determinacy> {
485 ident = ident.modern();
486 let mut module = Some(self.current_module);
487 let mut potential_illegal_shadower = Err(Determinacy::Determined);
489 if record_used { Determinacy::Determined } else { Determinacy::Undetermined };
491 let orig_current_module = self.current_module;
492 let result = if let Some(module) = module {
493 self.current_module = module; // Lexical resolutions can never be a privacy error.
494 // Since expanded macros may not shadow the lexical scope and
495 // globs may not shadow global macros (both enforced below),
496 // we resolve with restricted shadowing (indicated by the penultimate argument).
497 self.resolve_ident_in_module_unadjusted(
498 module, ident, ns, true, record_used, path_span,
499 ).map(MacroBinding::Modern)
501 self.global_macros.get(&ident.name).cloned().ok_or(determinacy)
502 .map(MacroBinding::Global)
504 self.current_module = orig_current_module;
506 match result.map(MacroBinding::binding) {
511 if let Ok(MacroBinding::Modern(shadower)) = potential_illegal_shadower {
512 if shadower.def() != binding.def() {
513 let name = ident.name;
514 self.ambiguity_errors.push(AmbiguityError {
522 return potential_illegal_shadower;
525 if binding.expansion != Mark::root() ||
526 (binding.is_glob_import() && module.unwrap().def().is_some()) {
527 potential_illegal_shadower = result;
532 Err(Determinacy::Undetermined) => return Err(Determinacy::Undetermined),
533 Err(Determinacy::Determined) => {}
536 module = match module {
537 Some(module) => self.hygienic_lexical_parent(module, &mut ident.ctxt),
538 None => return potential_illegal_shadower,
543 pub fn resolve_legacy_scope(&mut self,
544 mut scope: &'a Cell<LegacyScope<'a>>,
547 -> Option<MacroBinding<'a>> {
548 let ident = ident.modern();
549 let mut possible_time_travel = None;
550 let mut relative_depth: u32 = 0;
551 let mut binding = None;
554 LegacyScope::Empty => break,
555 LegacyScope::Expansion(invocation) => {
556 match invocation.expansion.get() {
557 LegacyScope::Invocation(_) => scope.set(invocation.legacy_scope.get()),
558 LegacyScope::Empty => {
559 if possible_time_travel.is_none() {
560 possible_time_travel = Some(scope);
562 scope = &invocation.legacy_scope;
566 scope = &invocation.expansion;
570 LegacyScope::Invocation(invocation) => {
571 relative_depth = relative_depth.saturating_sub(1);
572 scope = &invocation.legacy_scope;
574 LegacyScope::Binding(potential_binding) => {
575 if potential_binding.ident == ident {
576 if (!self.use_extern_macros || record_used) && relative_depth > 0 {
577 self.disallowed_shadowing.push(potential_binding);
579 binding = Some(potential_binding);
582 scope = &potential_binding.parent;
587 let binding = if let Some(binding) = binding {
588 MacroBinding::Legacy(binding)
589 } else if let Some(binding) = self.global_macros.get(&ident.name).cloned() {
590 if !self.use_extern_macros {
591 self.record_use(ident, MacroNS, binding, DUMMY_SP);
593 MacroBinding::Global(binding)
598 if !self.use_extern_macros {
599 if let Some(scope) = possible_time_travel {
600 // Check for disallowed shadowing later
601 self.lexical_macro_resolutions.push((ident, scope));
608 pub fn finalize_current_module_macro_resolutions(&mut self) {
609 let module = self.current_module;
610 for &(ref path, span) in module.macro_resolutions.borrow().iter() {
611 let path = path.iter().map(|p| respan(span, *p)).collect::<Vec<_>>();
612 match self.resolve_path(&path, Some(MacroNS), true, span) {
613 PathResult::NonModule(_) => {},
614 PathResult::Failed(span, msg, _) => {
615 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
621 for &(mark, ident, span, kind) in module.legacy_macro_resolutions.borrow().iter() {
622 let legacy_scope = &self.invocations[&mark].legacy_scope;
623 let legacy_resolution = self.resolve_legacy_scope(legacy_scope, ident, true);
624 let resolution = self.resolve_lexical_macro_path_segment(ident, MacroNS, true, span);
625 match (legacy_resolution, resolution) {
626 (Some(MacroBinding::Legacy(legacy_binding)), Ok(MacroBinding::Modern(binding))) => {
627 let msg1 = format!("`{}` could refer to the macro defined here", ident);
628 let msg2 = format!("`{}` could also refer to the macro imported here", ident);
629 self.session.struct_span_err(span, &format!("`{}` is ambiguous", ident))
630 .span_note(legacy_binding.span, &msg1)
631 .span_note(binding.span, &msg2)
634 (Some(MacroBinding::Global(binding)), Ok(MacroBinding::Global(_))) => {
635 self.record_use(ident, MacroNS, binding, span);
636 self.err_if_macro_use_proc_macro(ident.name, span, binding);
639 let msg = match kind {
641 format!("cannot find macro `{}!` in this scope", ident),
643 format!("cannot find attribute macro `{}` in this scope", ident),
645 format!("cannot find derive macro `{}` in this scope", ident),
647 let mut err = self.session.struct_span_err(span, &msg);
648 self.suggest_macro_name(&ident.name.as_str(), kind, &mut err, span);
656 fn suggest_macro_name(&mut self, name: &str, kind: MacroKind,
657 err: &mut DiagnosticBuilder<'a>, span: Span) {
658 // First check if this is a locally-defined bang macro.
659 let suggestion = if let MacroKind::Bang = kind {
660 find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, None)
663 // Then check global macros.
665 // FIXME: get_macro needs an &mut Resolver, can we do it without cloning?
666 let global_macros = self.global_macros.clone();
667 let names = global_macros.iter().filter_map(|(name, binding)| {
668 if binding.get_macro(self).kind() == kind {
674 find_best_match_for_name(names, name, None)
675 // Then check modules.
677 if !self.use_extern_macros {
680 let is_macro = |def| {
681 if let Def::Macro(_, def_kind) = def {
687 let ident = Ident::from_str(name);
688 self.lookup_typo_candidate(&vec![respan(span, ident)], MacroNS, is_macro, span)
691 if let Some(suggestion) = suggestion {
692 if suggestion != name {
693 if let MacroKind::Bang = kind {
694 err.span_suggestion(span, "you could try the macro", suggestion.to_string());
696 err.span_suggestion(span, "try", suggestion.to_string());
699 err.help("have you added the `#[macro_use]` on the module/import?");
704 fn collect_def_ids(&mut self,
706 invocation: &'a InvocationData<'a>,
707 expansion: &Expansion) {
708 let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
709 let InvocationData { def_index, const_expr, .. } = *invocation;
711 let visit_macro_invoc = &mut |invoc: map::MacroInvocationData| {
712 invocations.entry(invoc.mark).or_insert_with(|| {
713 arenas.alloc_invocation_data(InvocationData {
714 def_index: invoc.def_index,
715 const_expr: invoc.const_expr,
716 module: Cell::new(graph_root),
717 expansion: Cell::new(LegacyScope::Empty),
718 legacy_scope: Cell::new(LegacyScope::Empty),
723 let mut def_collector = DefCollector::new(&mut self.definitions, mark);
724 def_collector.visit_macro_invoc = Some(visit_macro_invoc);
725 def_collector.with_parent(def_index, |def_collector| {
727 if let Expansion::Expr(ref expr) = *expansion {
728 def_collector.visit_const_expr(expr);
731 expansion.visit_with(def_collector)
735 pub fn define_macro(&mut self,
738 legacy_scope: &mut LegacyScope<'a>) {
739 self.local_macro_def_scopes.insert(item.id, self.current_module);
740 let ident = item.ident;
741 if ident.name == "macro_rules" {
742 self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
745 let def_id = self.definitions.local_def_id(item.id);
746 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
747 &self.session.features,
749 self.macro_map.insert(def_id, ext);
751 let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
753 let ident = ident.modern();
754 self.macro_names.insert(ident);
755 *legacy_scope = LegacyScope::Binding(self.arenas.alloc_legacy_binding(LegacyBinding {
756 parent: Cell::new(*legacy_scope), ident: ident, def_id: def_id, span: item.span,
758 let def = Def::Macro(def_id, MacroKind::Bang);
759 self.all_macros.insert(ident.name, def);
760 if attr::contains_name(&item.attrs, "macro_export") {
761 self.macro_exports.push(Export {
762 ident: ident.modern(),
764 vis: ty::Visibility::Public,
769 self.unused_macros.insert(def_id);
772 let module = self.current_module;
773 let def = Def::Macro(def_id, MacroKind::Bang);
774 let vis = self.resolve_visibility(&item.vis);
775 if vis != ty::Visibility::Public {
776 self.unused_macros.insert(def_id);
778 self.define(module, ident, MacroNS, (def, vis, item.span, expansion));
782 /// Error if `ext` is a Macros 1.1 procedural macro being imported by `#[macro_use]`
783 fn err_if_macro_use_proc_macro(&mut self, name: Name, use_span: Span,
784 binding: &NameBinding<'a>) {
785 use self::SyntaxExtension::*;
787 let krate = binding.def().def_id().krate;
789 // Plugin-based syntax extensions are exempt from this check
790 if krate == BUILTIN_MACROS_CRATE { return; }
792 let ext = binding.get_macro(self);
795 // If `ext` is a procedural macro, check if we've already warned about it
796 AttrProcMacro(_) | ProcMacro(_) => if !self.warned_proc_macros.insert(name) { return; },
800 let warn_msg = match *ext {
801 AttrProcMacro(_) => "attribute procedural macros cannot be \
802 imported with `#[macro_use]`",
803 ProcMacro(_) => "procedural macros cannot be imported with `#[macro_use]`",
807 let def_id = self.current_module.normal_ancestor_id;
808 let node_id = self.definitions.as_local_node_id(def_id).unwrap();
810 self.proc_mac_errors.push(ProcMacError {
811 crate_name: self.cstore.crate_name_untracked(krate),
819 pub fn report_proc_macro_import(&mut self, krate: &ast::Crate) {
820 for err in self.proc_mac_errors.drain(..) {
821 let (span, found_use) = ::UsePlacementFinder::check(krate, err.module);
823 if let Some(span) = span {
824 let found_use = if found_use { "" } else { "\n" };
825 self.session.struct_span_err(err.use_span, err.warn_msg)
828 "instead, import the procedural macro like any other item",
829 format!("use {}::{};{}", err.crate_name, err.name, found_use),
832 self.session.struct_span_err(err.use_span, err.warn_msg)
833 .help(&format!("instead, import the procedural macro like any other item: \
834 `use {}::{};`", err.crate_name, err.name))
840 fn gate_legacy_custom_derive(&mut self, name: Symbol, span: Span) {
841 if !self.session.features.borrow().custom_derive {
842 let sess = &self.session.parse_sess;
843 let explain = feature_gate::EXPLAIN_CUSTOM_DERIVE;
844 emit_feature_err(sess, "custom_derive", span, GateIssue::Language, explain);
845 } else if !self.is_whitelisted_legacy_custom_derive(name) {
846 self.session.span_warn(span, feature_gate::EXPLAIN_DEPR_CUSTOM_DERIVE);