]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/macros.rs
resolve: Consolidate error reporting for resolved macros in `fn resolve_macro_to_def`
[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};
39 use syntax::util::lev_distance::find_best_match_for_name;
40 use syntax_pos::{Span, DUMMY_SP};
41
42 use std::cell::Cell;
43 use std::mem;
44 use rustc_data_structures::sync::Lrc;
45
46 #[derive(Clone)]
47 pub struct InvocationData<'a> {
48     pub module: Cell<Module<'a>>,
49     pub def_index: DefIndex,
50     // The scope in which the invocation path is resolved.
51     pub legacy_scope: Cell<LegacyScope<'a>>,
52     // The smallest scope that includes this invocation's expansion,
53     // or `Empty` if this invocation has not been expanded yet.
54     pub expansion: Cell<LegacyScope<'a>>,
55 }
56
57 impl<'a> InvocationData<'a> {
58     pub fn root(graph_root: Module<'a>) -> Self {
59         InvocationData {
60             module: Cell::new(graph_root),
61             def_index: CRATE_DEF_INDEX,
62             legacy_scope: Cell::new(LegacyScope::Empty),
63             expansion: Cell::new(LegacyScope::Empty),
64         }
65     }
66 }
67
68 #[derive(Copy, Clone)]
69 pub enum LegacyScope<'a> {
70     Empty,
71     Invocation(&'a InvocationData<'a>), // The scope of the invocation, not including its expansion
72     Expansion(&'a InvocationData<'a>), // The scope of the invocation, including its expansion
73     Binding(&'a LegacyBinding<'a>),
74 }
75
76 pub struct LegacyBinding<'a> {
77     pub parent: Cell<LegacyScope<'a>>,
78     pub ident: Ident,
79     def_id: DefId,
80     pub span: Span,
81 }
82
83 pub struct ProcMacError {
84     crate_name: Symbol,
85     name: Symbol,
86     module: ast::NodeId,
87     use_span: Span,
88     warn_msg: &'static str,
89 }
90
91 #[derive(Copy, Clone)]
92 pub enum MacroBinding<'a> {
93     Legacy(&'a LegacyBinding<'a>),
94     Global(&'a NameBinding<'a>),
95     Modern(&'a NameBinding<'a>),
96 }
97
98 impl<'a> MacroBinding<'a> {
99     pub fn span(self) -> Span {
100         match self {
101             MacroBinding::Legacy(binding) => binding.span,
102             MacroBinding::Global(binding) | MacroBinding::Modern(binding) => binding.span,
103         }
104     }
105
106     pub fn binding(self) -> &'a NameBinding<'a> {
107         match self {
108             MacroBinding::Global(binding) | MacroBinding::Modern(binding) => binding,
109             MacroBinding::Legacy(_) => panic!("unexpected MacroBinding::Legacy"),
110         }
111     }
112
113     pub fn def_ignoring_ambiguity(self) -> Def {
114         match self {
115             MacroBinding::Legacy(binding) => Def::Macro(binding.def_id, MacroKind::Bang),
116             MacroBinding::Global(binding) | MacroBinding::Modern(binding) =>
117                 binding.def_ignoring_ambiguity(),
118         }
119     }
120 }
121
122 impl<'a, 'crateloader: 'a> base::Resolver for Resolver<'a, 'crateloader> {
123     fn next_node_id(&mut self) -> ast::NodeId {
124         self.session.next_node_id()
125     }
126
127     fn get_module_scope(&mut self, id: ast::NodeId) -> Mark {
128         let mark = Mark::fresh(Mark::root());
129         let module = self.module_map[&self.definitions.local_def_id(id)];
130         self.invocations.insert(mark, self.arenas.alloc_invocation_data(InvocationData {
131             module: Cell::new(module),
132             def_index: module.def_id().unwrap().index,
133             legacy_scope: Cell::new(LegacyScope::Empty),
134             expansion: Cell::new(LegacyScope::Empty),
135         }));
136         mark
137     }
138
139     fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> {
140         struct EliminateCrateVar<'b, 'a: 'b, 'crateloader: 'a>(
141             &'b mut Resolver<'a, 'crateloader>, Span
142         );
143
144         impl<'a, 'b, 'crateloader> Folder for EliminateCrateVar<'a, 'b, 'crateloader> {
145             fn fold_path(&mut self, path: ast::Path) -> ast::Path {
146                 match self.fold_qpath(None, path) {
147                     (None, path) => path,
148                     _ => unreachable!(),
149                 }
150             }
151
152             fn fold_qpath(&mut self, mut qself: Option<ast::QSelf>, mut path: ast::Path)
153                           -> (Option<ast::QSelf>, ast::Path) {
154                 qself = qself.map(|ast::QSelf { ty, path_span, position }| {
155                     ast::QSelf {
156                         ty: self.fold_ty(ty),
157                         path_span: self.new_span(path_span),
158                         position,
159                     }
160                 });
161
162                 if path.segments[0].ident.name == keywords::DollarCrate.name() {
163                     let module = self.0.resolve_crate_root(path.segments[0].ident);
164                     path.segments[0].ident.name = keywords::CrateRoot.name();
165                     if !module.is_local() {
166                         let span = path.segments[0].ident.span;
167                         path.segments.insert(1, match module.kind {
168                             ModuleKind::Def(_, name) => ast::PathSegment::from_ident(
169                                 ast::Ident::with_empty_ctxt(name).with_span_pos(span)
170                             ),
171                             _ => unreachable!(),
172                         });
173                         if let Some(qself) = &mut qself {
174                             qself.position += 1;
175                         }
176                     }
177                 }
178                 (qself, path)
179             }
180
181             fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
182                 fold::noop_fold_mac(mac, self)
183             }
184         }
185
186         EliminateCrateVar(self, item.span).fold_item(item).expect_one("")
187     }
188
189     fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool {
190         self.whitelisted_legacy_custom_derives.contains(&name)
191     }
192
193     fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
194                                             derives: &[Mark]) {
195         let invocation = self.invocations[&mark];
196         self.collect_def_ids(mark, invocation, fragment);
197
198         self.current_module = invocation.module.get();
199         self.current_module.unresolved_invocations.borrow_mut().remove(&mark);
200         self.current_module.unresolved_invocations.borrow_mut().extend(derives);
201         for &derive in derives {
202             self.invocations.insert(derive, invocation);
203         }
204         let mut visitor = BuildReducedGraphVisitor {
205             resolver: self,
206             legacy_scope: LegacyScope::Invocation(invocation),
207             expansion: mark,
208         };
209         fragment.visit_with(&mut visitor);
210         invocation.expansion.set(visitor.legacy_scope);
211     }
212
213     fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>) {
214         let def_id = DefId {
215             krate: BUILTIN_MACROS_CRATE,
216             index: DefIndex::from_array_index(self.macro_map.len(),
217                                               DefIndexAddressSpace::Low),
218         };
219         let kind = ext.kind();
220         self.macro_map.insert(def_id, ext);
221         let binding = self.arenas.alloc_name_binding(NameBinding {
222             kind: NameBindingKind::Def(Def::Macro(def_id, kind), false),
223             span: DUMMY_SP,
224             vis: ty::Visibility::Invisible,
225             expansion: Mark::root(),
226         });
227         self.macro_prelude.insert(ident.name, binding);
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.macro_prelude.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.macro_prelude.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                         attrs[i].tokens = TokenTree::Delimited(attrs[i].span, Delimited {
303                             delim: token::Paren,
304                             tts: TokenStream::concat(tokens).into(),
305                         }).into();
306                     }
307                     return Some(ast::Attribute {
308                         path: ast::Path::from_ident(Ident::new(legacy_name, span)),
309                         tokens: TokenStream::empty(),
310                         id: attr::mk_attr_id(),
311                         style: ast::AttrStyle::Outer,
312                         is_sugared_doc: false,
313                         span,
314                     });
315                 }
316             }
317         }
318
319         None
320     }
321
322     fn resolve_macro_invocation(&mut self, invoc: &Invocation, scope: Mark, force: bool)
323                                 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
324         let (path, kind, derives_in_scope) = match invoc.kind {
325             InvocationKind::Attr { attr: None, .. } =>
326                 return Ok(None),
327             InvocationKind::Attr { attr: Some(ref attr), ref traits, .. } =>
328                 (&attr.path, MacroKind::Attr, &traits[..]),
329             InvocationKind::Bang { ref mac, .. } =>
330                 (&mac.node.path, MacroKind::Bang, &[][..]),
331             InvocationKind::Derive { ref path, .. } =>
332                 (path, MacroKind::Derive, &[][..]),
333         };
334
335         let (def, ext) = self.resolve_macro_to_def(path, kind, scope, derives_in_scope, force)?;
336
337         if let Def::Macro(def_id, _) = def {
338             self.macro_defs.insert(invoc.expansion_data.mark, def_id);
339             let normal_module_def_id =
340                 self.macro_def_scope(invoc.expansion_data.mark).normal_ancestor_id;
341             self.definitions.add_parent_module_of_macro_def(invoc.expansion_data.mark,
342                                                             normal_module_def_id);
343             invoc.expansion_data.mark.set_default_transparency(ext.default_transparency());
344             invoc.expansion_data.mark.set_is_builtin(def_id.krate == BUILTIN_MACROS_CRATE);
345         }
346
347         Ok(Some(ext))
348     }
349
350     fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, scope: Mark,
351                           derives_in_scope: &[ast::Path], force: bool)
352                           -> Result<Lrc<SyntaxExtension>, Determinacy> {
353         Ok(self.resolve_macro_to_def(path, kind, scope, derives_in_scope, force)?.1)
354     }
355
356     fn check_unused_macros(&self) {
357         for did in self.unused_macros.iter() {
358             let id_span = match *self.macro_map[did] {
359                 SyntaxExtension::NormalTT { def_info, .. } |
360                 SyntaxExtension::DeclMacro { def_info, .. } => def_info,
361                 _ => None,
362             };
363             if let Some((id, span)) = id_span {
364                 let lint = lint::builtin::UNUSED_MACROS;
365                 let msg = "unused macro definition";
366                 self.session.buffer_lint(lint, id, span, msg);
367             } else {
368                 bug!("attempted to create unused macro error, but span not available");
369             }
370         }
371     }
372 }
373
374 impl<'a, 'cl> Resolver<'a, 'cl> {
375     fn resolve_macro_to_def(&mut self, path: &ast::Path, kind: MacroKind, scope: Mark,
376                             derives_in_scope: &[ast::Path], force: bool)
377                             -> Result<(Def, Lrc<SyntaxExtension>), Determinacy> {
378         let def = self.resolve_macro_to_def_inner(path, kind, scope, derives_in_scope, force);
379
380         // Report errors and enforce feature gates for the resolved macro.
381         if def != Err(Determinacy::Undetermined) {
382             // Do not report duplicated errors on every undetermined resolution.
383             for segment in &path.segments {
384                 if let Some(args) = &segment.args {
385                     self.session.span_err(args.span(), "generic arguments in macro path");
386                 }
387             }
388         }
389
390         let def = def?;
391
392         if path.segments.len() > 1 {
393             if kind != MacroKind::Bang {
394                 if def != Def::NonMacroAttr(NonMacroAttrKind::Tool) &&
395                    !self.session.features_untracked().proc_macro_path_invoc {
396                     let msg = format!("non-ident {} paths are unstable", kind.descr());
397                     emit_feature_err(&self.session.parse_sess, "proc_macro_path_invoc",
398                                      path.span, GateIssue::Language, &msg);
399                 }
400             }
401         }
402
403         match def {
404             Def::Macro(def_id, macro_kind) => {
405                 self.unused_macros.remove(&def_id);
406                 if macro_kind == MacroKind::ProcMacroStub {
407                     let msg = "can't use a procedural macro from the same crate that defines it";
408                     self.session.span_err(path.span, msg);
409                     return Err(Determinacy::Determined);
410                 }
411             }
412             Def::NonMacroAttr(attr_kind) => {
413                 if kind == MacroKind::Attr {
414                     let features = self.session.features_untracked();
415                     if attr_kind == NonMacroAttrKind::Tool && !features.tool_attributes {
416                         feature_err(&self.session.parse_sess, "tool_attributes", path.span,
417                                     GateIssue::Language, "tool attributes are unstable").emit();
418                     }
419                     if attr_kind == NonMacroAttrKind::Custom {
420                         assert!(path.segments.len() == 1);
421                         let name = path.segments[0].ident.name.as_str();
422                         if name.starts_with("rustc_") {
423                             if !features.rustc_attrs {
424                                 let msg = "unless otherwise specified, attributes with the prefix \
425                                            `rustc_` are reserved for internal compiler diagnostics";
426                                 feature_err(&self.session.parse_sess, "rustc_attrs", path.span,
427                                             GateIssue::Language, &msg).emit();
428                             }
429                         } else if name.starts_with("derive_") {
430                             if !features.custom_derive {
431                                 feature_err(&self.session.parse_sess, "custom_derive", path.span,
432                                             GateIssue::Language, EXPLAIN_DERIVE_UNDERSCORE).emit();
433                             }
434                         } else if !features.custom_attribute {
435                             let msg = format!("The attribute `{}` is currently unknown to the \
436                                                compiler and may have meaning added to it in the \
437                                                future", path);
438                             feature_err(&self.session.parse_sess, "custom_attribute", path.span,
439                                         GateIssue::Language, &msg).emit();
440                         }
441                     }
442                 } else {
443                     // Not only attributes, but anything in macro namespace can result in
444                     // `Def::NonMacroAttr` definition (e.g. `inline!()`), so we must report
445                     // an error for those cases.
446                     let msg = format!("expected a macro, found {}", def.kind_name());
447                     self.session.span_err(path.span, &msg);
448                     return Err(Determinacy::Determined);
449                 }
450             }
451             _ => panic!("expected `Def::Macro` or `Def::NonMacroAttr`"),
452         }
453
454         Ok((def, self.get_macro(def)))
455     }
456
457     pub fn resolve_macro_to_def_inner(&mut self, path: &ast::Path, kind: MacroKind, scope: Mark,
458                                       derives_in_scope: &[ast::Path], force: bool)
459                                       -> Result<Def, Determinacy> {
460         let ast::Path { ref segments, span } = *path;
461         let mut path: Vec<_> = segments.iter().map(|seg| seg.ident).collect();
462         let invocation = self.invocations[&scope];
463         let module = invocation.module.get();
464         self.current_module = if module.is_trait() { module.parent.unwrap() } else { module };
465
466         // Possibly apply the macro helper hack
467         if kind == MacroKind::Bang && path.len() == 1 &&
468            path[0].span.ctxt().outer().expn_info().map_or(false, |info| info.local_inner_macros) {
469             let root = Ident::new(keywords::DollarCrate.name(), path[0].span);
470             path.insert(0, root);
471         }
472
473         if path.len() > 1 {
474             let res = self.resolve_path(None, &path, Some(MacroNS), false, span, CrateLint::No);
475             let def = match res {
476                 PathResult::NonModule(path_res) => match path_res.base_def() {
477                     Def::Err => Err(Determinacy::Determined),
478                     def @ _ => {
479                         if path_res.unresolved_segments() > 0 {
480                             self.found_unresolved_macro = true;
481                             self.session.span_err(span, "fail to resolve non-ident macro path");
482                             Err(Determinacy::Determined)
483                         } else {
484                             Ok(def)
485                         }
486                     }
487                 },
488                 PathResult::Module(..) => unreachable!(),
489                 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
490                 _ => {
491                     self.found_unresolved_macro = true;
492                     Err(Determinacy::Determined)
493                 },
494             };
495             self.current_module.nearest_item_scope().macro_resolutions.borrow_mut()
496                 .push((path.into_boxed_slice(), span));
497             return def;
498         }
499
500         let legacy_resolution = self.resolve_legacy_scope(&invocation.legacy_scope, path[0], false);
501         let result = if let Some(MacroBinding::Legacy(binding)) = legacy_resolution {
502             Ok(Def::Macro(binding.def_id, MacroKind::Bang))
503         } else {
504             match self.resolve_lexical_macro_path_segment(path[0], MacroNS, false, force,
505                                                           kind == MacroKind::Attr, span) {
506                 Ok(binding) => Ok(binding.binding().def_ignoring_ambiguity()),
507                 Err(Determinacy::Undetermined) => return Err(Determinacy::Undetermined),
508                 Err(Determinacy::Determined) => {
509                     self.found_unresolved_macro = true;
510                     Err(Determinacy::Determined)
511                 }
512             }
513         };
514
515         self.current_module.nearest_item_scope().legacy_macro_resolutions.borrow_mut()
516             .push((scope, path[0], kind, result.ok()));
517
518         if let Ok(Def::NonMacroAttr(NonMacroAttrKind::Custom)) = result {} else {
519             return result;
520         }
521
522         // At this point we've found that the `attr` is determinately unresolved and thus can be
523         // interpreted as a custom attribute. Normally custom attributes are feature gated, but
524         // it may be a custom attribute whitelisted by a derive macro and they do not require
525         // a feature gate.
526         //
527         // So here we look through all of the derive annotations in scope and try to resolve them.
528         // If they themselves successfully resolve *and* one of the resolved derive macros
529         // whitelists this attribute's name, then this is a registered attribute and we can convert
530         // it from a "generic custom attrite" into a "known derive helper attribute".
531         assert!(kind == MacroKind::Attr);
532         enum ConvertToDeriveHelper { Yes, No, DontKnow }
533         let mut convert_to_derive_helper = ConvertToDeriveHelper::No;
534         for derive in derives_in_scope {
535             match self.resolve_macro_path(derive, MacroKind::Derive, scope, &[], force) {
536                 Ok(ext) => if let SyntaxExtension::ProcMacroDerive(_, ref inert_attrs, _) = *ext {
537                     if inert_attrs.contains(&path[0].name) {
538                         convert_to_derive_helper = ConvertToDeriveHelper::Yes;
539                         break
540                     }
541                 },
542                 Err(Determinacy::Undetermined) =>
543                     convert_to_derive_helper = ConvertToDeriveHelper::DontKnow,
544                 Err(Determinacy::Determined) => {}
545             }
546         }
547
548         match convert_to_derive_helper {
549             ConvertToDeriveHelper::Yes => Ok(Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper)),
550             ConvertToDeriveHelper::No => result,
551             ConvertToDeriveHelper::DontKnow => Err(Determinacy::determined(force)),
552         }
553     }
554
555     // Resolve the initial segment of a non-global macro path
556     // (e.g. `foo` in `foo::bar!(); or `foo!();`).
557     // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
558     // expansion and import resolution (perhaps they can be merged in the future).
559     pub fn resolve_lexical_macro_path_segment(&mut self,
560                                               mut ident: Ident,
561                                               ns: Namespace,
562                                               record_used: bool,
563                                               force: bool,
564                                               is_attr: bool,
565                                               path_span: Span)
566                                               -> Result<MacroBinding<'a>, Determinacy> {
567         // General principles:
568         // 1. Not controlled (user-defined) names should have higher priority than controlled names
569         //    built into the language or standard library. This way we can add new names into the
570         //    language or standard library without breaking user code.
571         // 2. "Closed set" below means new names can appear after the current resolution attempt.
572         // Places to search (in order of decreasing priority):
573         // (Type NS)
574         // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
575         //    (open set, not controlled).
576         // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
577         //    (open, not controlled).
578         // 3. Extern prelude (closed, not controlled).
579         // 4. Tool modules (closed, controlled right now, but not in the future).
580         // 5. Standard library prelude (de-facto closed, controlled).
581         // 6. Language prelude (closed, controlled).
582         // (Macro NS)
583         // 1. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
584         //    (open, not controlled).
585         // 2. Macro prelude (language, standard library, user-defined legacy plugins lumped into
586         //    one set) (open, the open part is from macro expansions, not controlled).
587         // 2a. User-defined prelude from macro-use
588         //    (open, the open part is from macro expansions, not controlled).
589         // 2b. Standard library prelude, currently just a macro-use (closed, controlled)
590         // 2c. Language prelude, perhaps including builtin attributes
591         //    (closed, controlled, except for legacy plugins).
592         // 3. Builtin attributes (closed, controlled).
593
594         assert!(ns == TypeNS  || ns == MacroNS);
595         assert!(force || !record_used); // `record_used` implies `force`
596         ident = ident.modern();
597
598         // Names from inner scope that can't shadow names from outer scopes, e.g.
599         // mod m { ... }
600         // {
601         //     use prefix::*; // if this imports another `m`, then it can't shadow the outer `m`
602         //                    // and we have and ambiguity error
603         //     m::mac!();
604         // }
605         // This includes names from globs and from macro expansions.
606         let mut potentially_ambiguous_result: Option<MacroBinding> = None;
607
608         enum WhereToResolve<'a> {
609             Module(Module<'a>),
610             MacroPrelude,
611             BuiltinAttrs,
612             ExternPrelude,
613             ToolPrelude,
614             StdLibPrelude,
615             PrimitiveTypes,
616         }
617
618         // Go through all the scopes and try to resolve the name.
619         let mut where_to_resolve = WhereToResolve::Module(self.current_module);
620         let mut use_prelude = !self.current_module.no_implicit_prelude;
621         loop {
622             let result = match where_to_resolve {
623                 WhereToResolve::Module(module) => {
624                     let orig_current_module = mem::replace(&mut self.current_module, module);
625                     let binding = self.resolve_ident_in_module_unadjusted(
626                         ModuleOrUniformRoot::Module(module),
627                         ident,
628                         ns,
629                         true,
630                         record_used,
631                         path_span,
632                     );
633                     self.current_module = orig_current_module;
634                     binding.map(MacroBinding::Modern)
635                 }
636                 WhereToResolve::MacroPrelude => {
637                     match self.macro_prelude.get(&ident.name).cloned() {
638                         Some(binding) => Ok(MacroBinding::Global(binding)),
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 is_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(MacroBinding::Global(binding))
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(MacroBinding::Global(binding))
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(MacroBinding::Global(binding))
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(MacroBinding::Global(binding));
700                             }
701                         }
702                     }
703                     result
704                 }
705                 WhereToResolve::PrimitiveTypes => {
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(MacroBinding::Global(binding))
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::MacroPrelude
726                                 } else {
727                                     WhereToResolve::ExternPrelude
728                                 }
729                             }
730                         }
731                     }
732                     WhereToResolve::MacroPrelude => WhereToResolve::BuiltinAttrs,
733                     WhereToResolve::BuiltinAttrs => break, // nowhere else to search
734                     WhereToResolve::ExternPrelude => WhereToResolve::ToolPrelude,
735                     WhereToResolve::ToolPrelude => WhereToResolve::StdLibPrelude,
736                     WhereToResolve::StdLibPrelude => WhereToResolve::PrimitiveTypes,
737                     WhereToResolve::PrimitiveTypes => break, // nowhere else to search
738                 };
739
740                 continue;
741             }}
742
743             match result {
744                 Ok(result) => {
745                     if !record_used {
746                         return Ok(result);
747                     }
748
749                     let binding = result.binding();
750
751                     // Found a solution that is ambiguous with a previously found solution.
752                     // Push an ambiguity error for later reporting and
753                     // return something for better recovery.
754                     if let Some(previous_result) = potentially_ambiguous_result {
755                         if binding.def() != previous_result.binding().def() {
756                             self.ambiguity_errors.push(AmbiguityError {
757                                 span: path_span,
758                                 name: ident.name,
759                                 b1: previous_result.binding(),
760                                 b2: binding,
761                                 lexical: true,
762                             });
763                             return Ok(previous_result);
764                         }
765                     }
766
767                     // Found a solution that's not an ambiguity yet, but is "suspicious" and
768                     // can participate in ambiguities later on.
769                     // Remember it and go search for other solutions in outer scopes.
770                     if binding.is_glob_import() || binding.expansion != Mark::root() {
771                         potentially_ambiguous_result = Some(result);
772
773                         continue_search!();
774                     }
775
776                     // Found a solution that can't be ambiguous, great success.
777                     return Ok(result);
778                 },
779                 Err(Determinacy::Determined) => {
780                     continue_search!();
781                 }
782                 Err(Determinacy::Undetermined) => return Err(Determinacy::determined(force)),
783             }
784         }
785
786         // Previously found potentially ambiguous result turned out to not be ambiguous after all.
787         if let Some(previous_result) = potentially_ambiguous_result {
788             return Ok(previous_result);
789         }
790
791         let determinacy = Determinacy::determined(force);
792         if determinacy == Determinacy::Determined && is_attr {
793             // For single-segment attributes interpret determinate "no resolution" as a custom
794             // attribute. (Lexical resolution implies the first segment and is_attr should imply
795             // the last segment, so we are certainly working with a single-segment attribute here.)
796             assert!(ns == MacroNS);
797             let binding = (Def::NonMacroAttr(NonMacroAttrKind::Custom),
798                            ty::Visibility::Public, ident.span, Mark::root())
799                            .to_name_binding(self.arenas);
800             Ok(MacroBinding::Global(binding))
801         } else {
802             Err(determinacy)
803         }
804     }
805
806     pub fn resolve_legacy_scope(&mut self,
807                                 mut scope: &'a Cell<LegacyScope<'a>>,
808                                 ident: Ident,
809                                 record_used: bool)
810                                 -> Option<MacroBinding<'a>> {
811         let ident = ident.modern();
812         let mut relative_depth: u32 = 0;
813         let mut binding = None;
814         loop {
815             match scope.get() {
816                 LegacyScope::Empty => break,
817                 LegacyScope::Expansion(invocation) => {
818                     match invocation.expansion.get() {
819                         LegacyScope::Invocation(_) => scope.set(invocation.legacy_scope.get()),
820                         LegacyScope::Empty => {
821                             scope = &invocation.legacy_scope;
822                         }
823                         _ => {
824                             relative_depth += 1;
825                             scope = &invocation.expansion;
826                         }
827                     }
828                 }
829                 LegacyScope::Invocation(invocation) => {
830                     relative_depth = relative_depth.saturating_sub(1);
831                     scope = &invocation.legacy_scope;
832                 }
833                 LegacyScope::Binding(potential_binding) => {
834                     if potential_binding.ident == ident {
835                         if record_used && relative_depth > 0 {
836                             self.disallowed_shadowing.push(potential_binding);
837                         }
838                         binding = Some(potential_binding);
839                         break
840                     }
841                     scope = &potential_binding.parent;
842                 }
843             };
844         }
845
846         let binding = if let Some(binding) = binding {
847             MacroBinding::Legacy(binding)
848         } else if let Some(binding) = self.macro_prelude.get(&ident.name).cloned() {
849             MacroBinding::Global(binding)
850         } else {
851             return None;
852         };
853
854         Some(binding)
855     }
856
857     pub fn finalize_current_module_macro_resolutions(&mut self) {
858         let module = self.current_module;
859         for &(ref path, span) in module.macro_resolutions.borrow().iter() {
860             match self.resolve_path(None, &path, Some(MacroNS), true, span, CrateLint::No) {
861                 PathResult::NonModule(_) => {},
862                 PathResult::Failed(span, msg, _) => {
863                     resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
864                 }
865                 _ => unreachable!(),
866             }
867         }
868
869         for &(mark, ident, kind, def) in module.legacy_macro_resolutions.borrow().iter() {
870             let span = ident.span;
871             let legacy_scope = &self.invocations[&mark].legacy_scope;
872             let legacy_resolution = self.resolve_legacy_scope(legacy_scope, ident, true);
873             let resolution = self.resolve_lexical_macro_path_segment(ident, MacroNS, true, true,
874                                                                      kind == MacroKind::Attr, span);
875
876             let check_consistency = |this: &Self, binding: MacroBinding| {
877                 if let Some(def) = def {
878                     if this.ambiguity_errors.is_empty() && this.disallowed_shadowing.is_empty() &&
879                        binding.def_ignoring_ambiguity() != def {
880                         // Make sure compilation does not succeed if preferred macro resolution
881                         // has changed after the macro had been expanded. In theory all such
882                         // situations should be reported as ambiguity errors, so this is span-bug.
883                         span_bug!(span, "inconsistent resolution for a macro");
884                     }
885                 } else {
886                     // It's possible that the macro was unresolved (indeterminate) and silently
887                     // expanded into a dummy fragment for recovery during expansion.
888                     // Now, post-expansion, the resolution may succeed, but we can't change the
889                     // past and need to report an error.
890                     let msg =
891                         format!("cannot determine resolution for the {} `{}`", kind.descr(), ident);
892                     let msg_note = "import resolution is stuck, try simplifying macro imports";
893                     this.session.struct_span_err(span, &msg).note(msg_note).emit();
894                 }
895             };
896
897             match (legacy_resolution, resolution) {
898                 (Some(MacroBinding::Legacy(legacy_binding)), Ok(MacroBinding::Modern(binding))) => {
899                     if legacy_binding.def_id != binding.def_ignoring_ambiguity().def_id() {
900                         let msg1 = format!("`{}` could refer to the macro defined here", ident);
901                         let msg2 =
902                             format!("`{}` could also refer to the macro imported here", ident);
903                         self.session.struct_span_err(span, &format!("`{}` is ambiguous", ident))
904                             .span_note(legacy_binding.span, &msg1)
905                             .span_note(binding.span, &msg2)
906                             .emit();
907                     }
908                 },
909                 (None, Err(_)) => {
910                     assert!(def.is_none());
911                     let bang = if kind == MacroKind::Bang { "!" } else { "" };
912                     let msg =
913                         format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
914                     let mut err = self.session.struct_span_err(span, &msg);
915                     self.suggest_macro_name(&ident.as_str(), kind, &mut err, span);
916                     err.emit();
917                 },
918                 (Some(MacroBinding::Modern(_)), _) | (_, Ok(MacroBinding::Legacy(_))) => {
919                     span_bug!(span, "impossible macro resolution result");
920                 }
921                 // OK, unambiguous resolution
922                 (Some(binding), Err(_)) | (None, Ok(binding)) |
923                 // OK, legacy wins over global even if their definitions are different
924                 (Some(binding @ MacroBinding::Legacy(_)), Ok(MacroBinding::Global(_))) |
925                 // OK, modern wins over global even if their definitions are different
926                 (Some(MacroBinding::Global(_)), Ok(binding @ MacroBinding::Modern(_))) => {
927                     check_consistency(self, binding);
928                 }
929                 (Some(MacroBinding::Global(binding1)), Ok(MacroBinding::Global(binding2))) => {
930                     if binding1.def() != binding2.def() {
931                         span_bug!(span, "mismatch between same global macro resolutions");
932                     }
933                     check_consistency(self, MacroBinding::Global(binding1));
934
935                     self.record_use(ident, MacroNS, binding1, span);
936                     self.err_if_macro_use_proc_macro(ident.name, span, binding1);
937                 },
938             };
939         }
940     }
941
942     fn suggest_macro_name(&mut self, name: &str, kind: MacroKind,
943                           err: &mut DiagnosticBuilder<'a>, span: Span) {
944         // First check if this is a locally-defined bang macro.
945         let suggestion = if let MacroKind::Bang = kind {
946             find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, None)
947         } else {
948             None
949         // Then check global macros.
950         }.or_else(|| {
951             // FIXME: get_macro needs an &mut Resolver, can we do it without cloning?
952             let macro_prelude = self.macro_prelude.clone();
953             let names = macro_prelude.iter().filter_map(|(name, binding)| {
954                 if binding.get_macro(self).kind() == kind {
955                     Some(name)
956                 } else {
957                     None
958                 }
959             });
960             find_best_match_for_name(names, name, None)
961         // Then check modules.
962         }).or_else(|| {
963             let is_macro = |def| {
964                 if let Def::Macro(_, def_kind) = def {
965                     def_kind == kind
966                 } else {
967                     false
968                 }
969             };
970             let ident = Ident::new(Symbol::intern(name), span);
971             self.lookup_typo_candidate(&[ident], MacroNS, is_macro, span)
972         });
973
974         if let Some(suggestion) = suggestion {
975             if suggestion != name {
976                 if let MacroKind::Bang = kind {
977                     err.span_suggestion(span, "you could try the macro", suggestion.to_string());
978                 } else {
979                     err.span_suggestion(span, "try", suggestion.to_string());
980                 }
981             } else {
982                 err.help("have you added the `#[macro_use]` on the module/import?");
983             }
984         }
985     }
986
987     fn collect_def_ids(&mut self,
988                        mark: Mark,
989                        invocation: &'a InvocationData<'a>,
990                        fragment: &AstFragment) {
991         let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
992         let InvocationData { def_index, .. } = *invocation;
993
994         let visit_macro_invoc = &mut |invoc: map::MacroInvocationData| {
995             invocations.entry(invoc.mark).or_insert_with(|| {
996                 arenas.alloc_invocation_data(InvocationData {
997                     def_index: invoc.def_index,
998                     module: Cell::new(graph_root),
999                     expansion: Cell::new(LegacyScope::Empty),
1000                     legacy_scope: Cell::new(LegacyScope::Empty),
1001                 })
1002             });
1003         };
1004
1005         let mut def_collector = DefCollector::new(&mut self.definitions, mark);
1006         def_collector.visit_macro_invoc = Some(visit_macro_invoc);
1007         def_collector.with_parent(def_index, |def_collector| {
1008             fragment.visit_with(def_collector)
1009         });
1010     }
1011
1012     pub fn define_macro(&mut self,
1013                         item: &ast::Item,
1014                         expansion: Mark,
1015                         legacy_scope: &mut LegacyScope<'a>) {
1016         self.local_macro_def_scopes.insert(item.id, self.current_module);
1017         let ident = item.ident;
1018         if ident.name == "macro_rules" {
1019             self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
1020         }
1021
1022         let def_id = self.definitions.local_def_id(item.id);
1023         let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
1024                                                &self.session.features_untracked(),
1025                                                item, hygiene::default_edition()));
1026         self.macro_map.insert(def_id, ext);
1027
1028         let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
1029         if def.legacy {
1030             let ident = ident.modern();
1031             self.macro_names.insert(ident);
1032             *legacy_scope = LegacyScope::Binding(self.arenas.alloc_legacy_binding(LegacyBinding {
1033                 parent: Cell::new(*legacy_scope), ident: ident, def_id: def_id, span: item.span,
1034             }));
1035             let def = Def::Macro(def_id, MacroKind::Bang);
1036             self.all_macros.insert(ident.name, def);
1037             if attr::contains_name(&item.attrs, "macro_export") {
1038                 let module = self.graph_root;
1039                 let vis = ty::Visibility::Public;
1040                 self.define(module, ident, MacroNS,
1041                             (def, vis, item.span, expansion, IsMacroExport));
1042             } else {
1043                 self.unused_macros.insert(def_id);
1044             }
1045         } else {
1046             let module = self.current_module;
1047             let def = Def::Macro(def_id, MacroKind::Bang);
1048             let vis = self.resolve_visibility(&item.vis);
1049             if vis != ty::Visibility::Public {
1050                 self.unused_macros.insert(def_id);
1051             }
1052             self.define(module, ident, MacroNS, (def, vis, item.span, expansion));
1053         }
1054     }
1055
1056     /// Error if `ext` is a Macros 1.1 procedural macro being imported by `#[macro_use]`
1057     fn err_if_macro_use_proc_macro(&mut self, name: Name, use_span: Span,
1058                                    binding: &NameBinding<'a>) {
1059         let krate = binding.def().def_id().krate;
1060
1061         // Plugin-based syntax extensions are exempt from this check
1062         if krate == BUILTIN_MACROS_CRATE { return; }
1063
1064         let ext = binding.get_macro(self);
1065
1066         match *ext {
1067             // If `ext` is a procedural macro, check if we've already warned about it
1068             SyntaxExtension::AttrProcMacro(..) | SyntaxExtension::ProcMacro { .. } =>
1069                 if !self.warned_proc_macros.insert(name) { return; },
1070             _ => return,
1071         }
1072
1073         let warn_msg = match *ext {
1074             SyntaxExtension::AttrProcMacro(..) =>
1075                 "attribute procedural macros cannot be imported with `#[macro_use]`",
1076             SyntaxExtension::ProcMacro { .. } =>
1077                 "procedural macros cannot be imported with `#[macro_use]`",
1078             _ => return,
1079         };
1080
1081         let def_id = self.current_module.normal_ancestor_id;
1082         let node_id = self.definitions.as_local_node_id(def_id).unwrap();
1083
1084         self.proc_mac_errors.push(ProcMacError {
1085             crate_name: self.cstore.crate_name_untracked(krate),
1086             name,
1087             module: node_id,
1088             use_span,
1089             warn_msg,
1090         });
1091     }
1092
1093     pub fn report_proc_macro_import(&mut self, krate: &ast::Crate) {
1094         for err in self.proc_mac_errors.drain(..) {
1095             let (span, found_use) = ::UsePlacementFinder::check(krate, err.module);
1096
1097             if let Some(span) = span {
1098                 let found_use = if found_use { "" } else { "\n" };
1099                 self.session.struct_span_err(err.use_span, err.warn_msg)
1100                     .span_suggestion(
1101                         span,
1102                         "instead, import the procedural macro like any other item",
1103                         format!("use {}::{};{}", err.crate_name, err.name, found_use),
1104                     ).emit();
1105             } else {
1106                 self.session.struct_span_err(err.use_span, err.warn_msg)
1107                     .help(&format!("instead, import the procedural macro like any other item: \
1108                                     `use {}::{};`", err.crate_name, err.name))
1109                     .emit();
1110             }
1111         }
1112     }
1113
1114     fn gate_legacy_custom_derive(&mut self, name: Symbol, span: Span) {
1115         if !self.session.features_untracked().custom_derive {
1116             let sess = &self.session.parse_sess;
1117             let explain = feature_gate::EXPLAIN_CUSTOM_DERIVE;
1118             emit_feature_err(sess, "custom_derive", span, GateIssue::Language, explain);
1119         } else if !self.is_whitelisted_legacy_custom_derive(name) {
1120             self.session.span_warn(span, feature_gate::EXPLAIN_DEPR_CUSTOM_DERIVE);
1121         }
1122     }
1123 }