]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/build_reduced_graph.rs
Rollup merge of #58273 - taiki-e:rename-dependency, r=matthewjasper
[rust.git] / src / librustc_resolve / build_reduced_graph.rs
1 //! Reduced graph building.
2 //!
3 //! Here we build the "reduced graph": the graph of the module tree without
4 //! any imports resolved.
5
6 use crate::macros::{InvocationData, ParentScope, LegacyScope};
7 use crate::resolve_imports::ImportDirective;
8 use crate::resolve_imports::ImportDirectiveSubclass::{self, GlobImport, SingleImport};
9 use crate::{Module, ModuleData, ModuleKind, NameBinding, NameBindingKind, Segment, ToNameBinding};
10 use crate::{ModuleOrUniformRoot, PerNS, Resolver, ResolverArenas, ExternPreludeEntry};
11 use crate::Namespace::{self, TypeNS, ValueNS, MacroNS};
12 use crate::{resolve_error, resolve_struct_error, ResolutionError};
13
14 use rustc::bug;
15 use rustc::hir::def::*;
16 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
17 use rustc::ty;
18 use rustc::middle::cstore::CrateStore;
19 use rustc_metadata::cstore::LoadedMacro;
20
21 use std::cell::Cell;
22 use std::ptr;
23 use rustc_data_structures::sync::Lrc;
24
25 use errors::Applicability;
26
27 use syntax::ast::{Name, Ident};
28 use syntax::attr;
29
30 use syntax::ast::{self, Block, ForeignItem, ForeignItemKind, Item, ItemKind, NodeId};
31 use syntax::ast::{MetaItemKind, Mutability, StmtKind, TraitItem, TraitItemKind, Variant};
32 use syntax::ext::base::{MacroKind, SyntaxExtension};
33 use syntax::ext::base::Determinacy::Undetermined;
34 use syntax::ext::hygiene::Mark;
35 use syntax::ext::tt::macro_rules;
36 use syntax::feature_gate::is_builtin_attr;
37 use syntax::parse::token::{self, Token};
38 use syntax::span_err;
39 use syntax::std_inject::injected_crate_name;
40 use syntax::symbol::keywords;
41 use syntax::visit::{self, Visitor};
42
43 use syntax_pos::{Span, DUMMY_SP};
44
45 use log::debug;
46
47 impl<'a> ToNameBinding<'a> for (Module<'a>, ty::Visibility, Span, Mark) {
48     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
49         arenas.alloc_name_binding(NameBinding {
50             kind: NameBindingKind::Module(self.0),
51             ambiguity: None,
52             vis: self.1,
53             span: self.2,
54             expansion: self.3,
55         })
56     }
57 }
58
59 impl<'a> ToNameBinding<'a> for (Def, ty::Visibility, Span, Mark) {
60     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
61         arenas.alloc_name_binding(NameBinding {
62             kind: NameBindingKind::Def(self.0, false),
63             ambiguity: None,
64             vis: self.1,
65             span: self.2,
66             expansion: self.3,
67         })
68     }
69 }
70
71 pub(crate) struct IsMacroExport;
72
73 impl<'a> ToNameBinding<'a> for (Def, ty::Visibility, Span, Mark, IsMacroExport) {
74     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
75         arenas.alloc_name_binding(NameBinding {
76             kind: NameBindingKind::Def(self.0, true),
77             ambiguity: None,
78             vis: self.1,
79             span: self.2,
80             expansion: self.3,
81         })
82     }
83 }
84
85 impl<'a> Resolver<'a> {
86     /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
87     /// otherwise, reports an error.
88     pub fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
89         where T: ToNameBinding<'a>,
90     {
91         let binding = def.to_name_binding(self.arenas);
92         if let Err(old_binding) = self.try_define(parent, ident, ns, binding) {
93             self.report_conflict(parent, ident, ns, old_binding, &binding);
94         }
95     }
96
97     fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
98         // If any statements are items, we need to create an anonymous module
99         block.stmts.iter().any(|statement| match statement.node {
100             StmtKind::Item(_) | StmtKind::Mac(_) => true,
101             _ => false,
102         })
103     }
104
105     fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Name>) {
106         if !field_names.is_empty() {
107             self.field_names.insert(def_id, field_names);
108         }
109     }
110
111     fn build_reduced_graph_for_use_tree(
112         &mut self,
113         // This particular use tree
114         use_tree: &ast::UseTree,
115         id: NodeId,
116         parent_prefix: &[Segment],
117         nested: bool,
118         // The whole `use` item
119         parent_scope: ParentScope<'a>,
120         item: &Item,
121         vis: ty::Visibility,
122         root_span: Span,
123     ) {
124         debug!("build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})",
125                parent_prefix, use_tree, nested);
126
127         let mut prefix_iter = parent_prefix.iter().cloned()
128             .chain(use_tree.prefix.segments.iter().map(|seg| seg.into())).peekable();
129
130         // On 2015 edition imports are resolved as crate-relative by default,
131         // so prefixes are prepended with crate root segment if necessary.
132         // The root is prepended lazily, when the first non-empty prefix or terminating glob
133         // appears, so imports in braced groups can have roots prepended independently.
134         // 2015 identifiers used on global 2018 edition enter special "virtual 2015 mode", don't
135         // get crate root prepended, but get special treatment during in-scope resolution instead.
136         let is_glob = if let ast::UseTreeKind::Glob = use_tree.kind { true } else { false };
137         let crate_root = match prefix_iter.peek() {
138             Some(seg) if !seg.ident.is_path_segment_keyword() &&
139                          seg.ident.span.rust_2015() && self.session.rust_2015() => {
140                 Some(seg.ident.span.ctxt())
141             }
142             None if is_glob && use_tree.span.rust_2015() => {
143                 Some(use_tree.span.ctxt())
144             }
145             _ => None,
146         }.map(|ctxt| Segment::from_ident(Ident::new(
147             keywords::PathRoot.name(), use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt)
148         )));
149
150         let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
151         debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix);
152
153         let empty_for_self = |prefix: &[Segment]| {
154             prefix.is_empty() ||
155             prefix.len() == 1 && prefix[0].ident.name == keywords::PathRoot.name()
156         };
157         match use_tree.kind {
158             ast::UseTreeKind::Simple(rename, ..) => {
159                 let mut ident = use_tree.ident().gensym_if_underscore();
160                 let mut module_path = prefix;
161                 let mut source = module_path.pop().unwrap();
162                 let mut type_ns_only = false;
163
164                 if nested {
165                     // Correctly handle `self`
166                     if source.ident.name == keywords::SelfLower.name() {
167                         type_ns_only = true;
168
169                         if empty_for_self(&module_path) {
170                             resolve_error(
171                                 self,
172                                 use_tree.span,
173                                 ResolutionError::
174                                 SelfImportOnlyInImportListWithNonEmptyPrefix
175                             );
176                             return;
177                         }
178
179                         // Replace `use foo::self;` with `use foo;`
180                         source = module_path.pop().unwrap();
181                         if rename.is_none() {
182                             ident = source.ident;
183                         }
184                     }
185                 } else {
186                     // Disallow `self`
187                     if source.ident.name == keywords::SelfLower.name() {
188                         resolve_error(self,
189                                       use_tree.span,
190                                       ResolutionError::SelfImportsOnlyAllowedWithin);
191                     }
192
193                     // Disallow `use $crate;`
194                     if source.ident.name == keywords::DollarCrate.name() && module_path.is_empty() {
195                         let crate_root = self.resolve_crate_root(source.ident);
196                         let crate_name = match crate_root.kind {
197                             ModuleKind::Def(_, name) => name,
198                             ModuleKind::Block(..) => unreachable!(),
199                         };
200                         // HACK(eddyb) unclear how good this is, but keeping `$crate`
201                         // in `source` breaks `src/test/compile-fail/import-crate-var.rs`,
202                         // while the current crate doesn't have a valid `crate_name`.
203                         if crate_name != keywords::Invalid.name() {
204                             // `crate_name` should not be interpreted as relative.
205                             module_path.push(Segment {
206                                 ident: Ident {
207                                     name: keywords::PathRoot.name(),
208                                     span: source.ident.span,
209                                 },
210                                 id: Some(self.session.next_node_id()),
211                             });
212                             source.ident.name = crate_name;
213                         }
214                         if rename.is_none() {
215                             ident.name = crate_name;
216                         }
217
218                         self.session.struct_span_warn(item.span, "`$crate` may not be imported")
219                             .note("`use $crate;` was erroneously allowed and \
220                                    will become a hard error in a future release")
221                             .emit();
222                     }
223                 }
224
225                 if ident.name == keywords::Crate.name() {
226                     self.session.span_err(ident.span,
227                         "crate root imports need to be explicitly named: \
228                          `use crate as name;`");
229                 }
230
231                 let subclass = SingleImport {
232                     source: source.ident,
233                     target: ident,
234                     source_bindings: PerNS {
235                         type_ns: Cell::new(Err(Undetermined)),
236                         value_ns: Cell::new(Err(Undetermined)),
237                         macro_ns: Cell::new(Err(Undetermined)),
238                     },
239                     target_bindings: PerNS {
240                         type_ns: Cell::new(None),
241                         value_ns: Cell::new(None),
242                         macro_ns: Cell::new(None),
243                     },
244                     type_ns_only,
245                     nested,
246                 };
247                 self.add_import_directive(
248                     module_path,
249                     subclass,
250                     use_tree.span,
251                     id,
252                     item,
253                     root_span,
254                     item.id,
255                     vis,
256                     parent_scope,
257                 );
258             }
259             ast::UseTreeKind::Glob => {
260                 let subclass = GlobImport {
261                     is_prelude: attr::contains_name(&item.attrs, "prelude_import"),
262                     max_vis: Cell::new(ty::Visibility::Invisible),
263                 };
264                 self.add_import_directive(
265                     prefix,
266                     subclass,
267                     use_tree.span,
268                     id,
269                     item,
270                     root_span,
271                     item.id,
272                     vis,
273                     parent_scope,
274                 );
275             }
276             ast::UseTreeKind::Nested(ref items) => {
277                 // Ensure there is at most one `self` in the list
278                 let self_spans = items.iter().filter_map(|&(ref use_tree, _)| {
279                     if let ast::UseTreeKind::Simple(..) = use_tree.kind {
280                         if use_tree.ident().name == keywords::SelfLower.name() {
281                             return Some(use_tree.span);
282                         }
283                     }
284
285                     None
286                 }).collect::<Vec<_>>();
287                 if self_spans.len() > 1 {
288                     let mut e = resolve_struct_error(self,
289                         self_spans[0],
290                         ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
291
292                     for other_span in self_spans.iter().skip(1) {
293                         e.span_label(*other_span, "another `self` import appears here");
294                     }
295
296                     e.emit();
297                 }
298
299                 for &(ref tree, id) in items {
300                     self.build_reduced_graph_for_use_tree(
301                         // This particular use tree
302                         tree, id, &prefix, true,
303                         // The whole `use` item
304                         parent_scope.clone(), item, vis, root_span,
305                     );
306                 }
307
308                 // Empty groups `a::b::{}` are turned into synthetic `self` imports
309                 // `a::b::c::{self as _}`, so that their prefixes are correctly
310                 // resolved and checked for privacy/stability/etc.
311                 if items.is_empty() && !empty_for_self(&prefix) {
312                     let new_span = prefix[prefix.len() - 1].ident.span;
313                     let tree = ast::UseTree {
314                         prefix: ast::Path::from_ident(
315                             Ident::new(keywords::SelfLower.name(), new_span)
316                         ),
317                         kind: ast::UseTreeKind::Simple(
318                             Some(Ident::new(keywords::Underscore.name().gensymed(), new_span)),
319                             ast::DUMMY_NODE_ID,
320                             ast::DUMMY_NODE_ID,
321                         ),
322                         span: use_tree.span,
323                     };
324                     self.build_reduced_graph_for_use_tree(
325                         // This particular use tree
326                         &tree, id, &prefix, true,
327                         // The whole `use` item
328                         parent_scope, item, ty::Visibility::Invisible, root_span,
329                     );
330                 }
331             }
332         }
333     }
334
335     /// Constructs the reduced graph for one item.
336     fn build_reduced_graph_for_item(&mut self, item: &Item, parent_scope: ParentScope<'a>) {
337         let parent = parent_scope.module;
338         let expansion = parent_scope.expansion;
339         let ident = item.ident.gensym_if_underscore();
340         let sp = item.span;
341         let vis = self.resolve_visibility(&item.vis);
342
343         match item.node {
344             ItemKind::Use(ref use_tree) => {
345                 self.build_reduced_graph_for_use_tree(
346                     // This particular use tree
347                     use_tree, item.id, &[], false,
348                     // The whole `use` item
349                     parent_scope, item, vis, use_tree.span,
350                 );
351             }
352
353             ItemKind::ExternCrate(orig_name) => {
354                 let module = if orig_name.is_none() && ident.name == keywords::SelfLower.name() {
355                     self.session
356                         .struct_span_err(item.span, "`extern crate self;` requires renaming")
357                         .span_suggestion(
358                             item.span,
359                             "try",
360                             "extern crate self as name;".into(),
361                             Applicability::HasPlaceholders,
362                         )
363                         .emit();
364                     return;
365                 } else if orig_name == Some(keywords::SelfLower.name()) {
366                     self.graph_root
367                 } else {
368                     let crate_id = self.crate_loader.process_extern_crate(item, &self.definitions);
369                     self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX })
370                 };
371
372                 self.populate_module_if_necessary(module);
373                 if injected_crate_name().map_or(false, |name| ident.name == name) {
374                     self.injected_crate = Some(module);
375                 }
376
377                 let used = self.process_legacy_macro_imports(item, module, &parent_scope);
378                 let binding =
379                     (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.arenas);
380                 let directive = self.arenas.alloc_import_directive(ImportDirective {
381                     root_id: item.id,
382                     id: item.id,
383                     parent_scope,
384                     imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
385                     subclass: ImportDirectiveSubclass::ExternCrate {
386                         source: orig_name,
387                         target: ident,
388                     },
389                     has_attributes: !item.attrs.is_empty(),
390                     use_span_with_attributes: item.span_with_attributes(),
391                     use_span: item.span,
392                     root_span: item.span,
393                     span: item.span,
394                     module_path: Vec::new(),
395                     vis: Cell::new(vis),
396                     used: Cell::new(used),
397                 });
398                 self.potentially_unused_imports.push(directive);
399                 let imported_binding = self.import(binding, directive);
400                 if ptr::eq(self.current_module, self.graph_root) {
401                     if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
402                         if expansion != Mark::root() && orig_name.is_some() &&
403                            entry.extern_crate_item.is_none() {
404                             self.session.span_err(item.span, "macro-expanded `extern crate` items \
405                                                               cannot shadow names passed with \
406                                                               `--extern`");
407                         }
408                     }
409                     let entry = self.extern_prelude.entry(ident.modern())
410                                                    .or_insert(ExternPreludeEntry {
411                         extern_crate_item: None,
412                         introduced_by_item: true,
413                     });
414                     entry.extern_crate_item = Some(imported_binding);
415                     if orig_name.is_some() {
416                         entry.introduced_by_item = true;
417                     }
418                 }
419                 self.define(parent, ident, TypeNS, imported_binding);
420             }
421
422             ItemKind::GlobalAsm(..) => {}
423
424             ItemKind::Mod(..) if ident == keywords::Invalid.ident() => {} // Crate root
425
426             ItemKind::Mod(..) => {
427                 let def_id = self.definitions.local_def_id(item.id);
428                 let module_kind = ModuleKind::Def(Def::Mod(def_id), ident.name);
429                 let module = self.arenas.alloc_module(ModuleData {
430                     no_implicit_prelude: parent.no_implicit_prelude || {
431                         attr::contains_name(&item.attrs, "no_implicit_prelude")
432                     },
433                     ..ModuleData::new(Some(parent), module_kind, def_id, expansion, item.span)
434                 });
435                 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
436                 self.module_map.insert(def_id, module);
437
438                 // Descend into the module.
439                 self.current_module = module;
440             }
441
442             // Handled in `rustc_metadata::{native_libs,link_args}`
443             ItemKind::ForeignMod(..) => {}
444
445             // These items live in the value namespace.
446             ItemKind::Static(_, m, _) => {
447                 let mutbl = m == Mutability::Mutable;
448                 let def = Def::Static(self.definitions.local_def_id(item.id), mutbl);
449                 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
450             }
451             ItemKind::Const(..) => {
452                 let def = Def::Const(self.definitions.local_def_id(item.id));
453                 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
454             }
455             ItemKind::Fn(..) => {
456                 let def = Def::Fn(self.definitions.local_def_id(item.id));
457                 self.define(parent, ident, ValueNS, (def, vis, sp, expansion));
458
459                 // Functions introducing procedural macros reserve a slot
460                 // in the macro namespace as well (see #52225).
461                 if attr::contains_name(&item.attrs, "proc_macro") ||
462                    attr::contains_name(&item.attrs, "proc_macro_attribute") {
463                     let def = Def::Macro(def.def_id(), MacroKind::ProcMacroStub);
464                     self.define(parent, ident, MacroNS, (def, vis, sp, expansion));
465                 }
466                 if let Some(attr) = attr::find_by_name(&item.attrs, "proc_macro_derive") {
467                     if let Some(trait_attr) =
468                             attr.meta_item_list().and_then(|list| list.get(0).cloned()) {
469                         if let Some(ident) = trait_attr.name().map(Ident::with_empty_ctxt) {
470                             let sp = trait_attr.span;
471                             let def = Def::Macro(def.def_id(), MacroKind::ProcMacroStub);
472                             self.define(parent, ident, MacroNS, (def, vis, sp, expansion));
473                         }
474                     }
475                 }
476             }
477
478             // These items live in the type namespace.
479             ItemKind::Ty(..) => {
480                 let def = Def::TyAlias(self.definitions.local_def_id(item.id));
481                 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
482             }
483
484             ItemKind::Existential(_, _) => {
485                 let def = Def::Existential(self.definitions.local_def_id(item.id));
486                 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
487             }
488
489             ItemKind::Enum(ref enum_definition, _) => {
490                 let def = Def::Enum(self.definitions.local_def_id(item.id));
491                 let module_kind = ModuleKind::Def(def, ident.name);
492                 let module = self.new_module(parent,
493                                              module_kind,
494                                              parent.normal_ancestor_id,
495                                              expansion,
496                                              item.span);
497                 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
498
499                 for variant in &(*enum_definition).variants {
500                     self.build_reduced_graph_for_variant(variant, module, vis, expansion);
501                 }
502             }
503
504             ItemKind::TraitAlias(..) => {
505                 let def = Def::TraitAlias(self.definitions.local_def_id(item.id));
506                 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
507             }
508
509             // These items live in both the type and value namespaces.
510             ItemKind::Struct(ref struct_def, _) => {
511                 // Define a name in the type namespace.
512                 let def_id = self.definitions.local_def_id(item.id);
513                 let def = Def::Struct(def_id);
514                 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
515
516                 let mut ctor_vis = vis;
517
518                 let has_non_exhaustive = attr::contains_name(&item.attrs, "non_exhaustive");
519
520                 // If the structure is marked as non_exhaustive then lower the visibility
521                 // to within the crate.
522                 if has_non_exhaustive && vis == ty::Visibility::Public {
523                     ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
524                 }
525
526                 // Record field names for error reporting.
527                 let field_names = struct_def.fields().iter().filter_map(|field| {
528                     let field_vis = self.resolve_visibility(&field.vis);
529                     if ctor_vis.is_at_least(field_vis, &*self) {
530                         ctor_vis = field_vis;
531                     }
532                     field.ident.map(|ident| ident.name)
533                 }).collect();
534                 let item_def_id = self.definitions.local_def_id(item.id);
535                 self.insert_field_names(item_def_id, field_names);
536
537                 // If this is a tuple or unit struct, define a name
538                 // in the value namespace as well.
539                 if !struct_def.is_struct() {
540                     let ctor_def = Def::StructCtor(self.definitions.local_def_id(struct_def.id()),
541                                                    CtorKind::from_ast(struct_def));
542                     self.define(parent, ident, ValueNS, (ctor_def, ctor_vis, sp, expansion));
543                     self.struct_constructors.insert(def.def_id(), (ctor_def, ctor_vis));
544                 }
545             }
546
547             ItemKind::Union(ref vdata, _) => {
548                 let def = Def::Union(self.definitions.local_def_id(item.id));
549                 self.define(parent, ident, TypeNS, (def, vis, sp, expansion));
550
551                 // Record field names for error reporting.
552                 let field_names = vdata.fields().iter().filter_map(|field| {
553                     self.resolve_visibility(&field.vis);
554                     field.ident.map(|ident| ident.name)
555                 }).collect();
556                 let item_def_id = self.definitions.local_def_id(item.id);
557                 self.insert_field_names(item_def_id, field_names);
558             }
559
560             ItemKind::Impl(..) => {}
561
562             ItemKind::Trait(..) => {
563                 let def_id = self.definitions.local_def_id(item.id);
564
565                 // Add all the items within to a new module.
566                 let module_kind = ModuleKind::Def(Def::Trait(def_id), ident.name);
567                 let module = self.new_module(parent,
568                                              module_kind,
569                                              parent.normal_ancestor_id,
570                                              expansion,
571                                              item.span);
572                 self.define(parent, ident, TypeNS, (module, vis, sp, expansion));
573                 self.current_module = module;
574             }
575
576             ItemKind::MacroDef(..) | ItemKind::Mac(_) => unreachable!(),
577         }
578     }
579
580     // Constructs the reduced graph for one variant. Variants exist in the
581     // type and value namespaces.
582     fn build_reduced_graph_for_variant(&mut self,
583                                        variant: &Variant,
584                                        parent: Module<'a>,
585                                        vis: ty::Visibility,
586                                        expansion: Mark) {
587         let ident = variant.node.ident;
588         let def_id = self.definitions.local_def_id(variant.node.data.id());
589
590         // Define a name in the type namespace.
591         let def = Def::Variant(def_id);
592         self.define(parent, ident, TypeNS, (def, vis, variant.span, expansion));
593
594         // Define a constructor name in the value namespace.
595         // Braced variants, unlike structs, generate unusable names in
596         // value namespace, they are reserved for possible future use.
597         let ctor_kind = CtorKind::from_ast(&variant.node.data);
598         let ctor_def = Def::VariantCtor(def_id, ctor_kind);
599
600         self.define(parent, ident, ValueNS, (ctor_def, vis, variant.span, expansion));
601     }
602
603     /// Constructs the reduced graph for one foreign item.
604     fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, expansion: Mark) {
605         let (def, ns) = match item.node {
606             ForeignItemKind::Fn(..) => {
607                 (Def::Fn(self.definitions.local_def_id(item.id)), ValueNS)
608             }
609             ForeignItemKind::Static(_, m) => {
610                 (Def::Static(self.definitions.local_def_id(item.id), m), ValueNS)
611             }
612             ForeignItemKind::Ty => {
613                 (Def::ForeignTy(self.definitions.local_def_id(item.id)), TypeNS)
614             }
615             ForeignItemKind::Macro(_) => unreachable!(),
616         };
617         let parent = self.current_module;
618         let vis = self.resolve_visibility(&item.vis);
619         self.define(parent, item.ident, ns, (def, vis, item.span, expansion));
620     }
621
622     fn build_reduced_graph_for_block(&mut self, block: &Block, expansion: Mark) {
623         let parent = self.current_module;
624         if self.block_needs_anonymous_module(block) {
625             let module = self.new_module(parent,
626                                          ModuleKind::Block(block.id),
627                                          parent.normal_ancestor_id,
628                                          expansion,
629                                          block.span);
630             self.block_map.insert(block.id, module);
631             self.current_module = module; // Descend into the block.
632         }
633     }
634
635     /// Builds the reduced graph for a single item in an external crate.
636     fn build_reduced_graph_for_external_crate_def(&mut self, parent: Module<'a>, child: Export) {
637         let Export { ident, def, vis, span } = child;
638         // FIXME: We shouldn't create the gensym here, it should come from metadata,
639         // but metadata cannot encode gensyms currently, so we create it here.
640         // This is only a guess, two equivalent idents may incorrectly get different gensyms here.
641         let ident = ident.gensym_if_underscore();
642         let def_id = def.def_id();
643         let expansion = Mark::root(); // FIXME(jseyfried) intercrate hygiene
644         match def {
645             Def::Mod(..) | Def::Enum(..) => {
646                 let module = self.new_module(parent,
647                                              ModuleKind::Def(def, ident.name),
648                                              def_id,
649                                              expansion,
650                                              span);
651                 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
652             }
653             Def::Variant(..) | Def::TyAlias(..) | Def::ForeignTy(..) => {
654                 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
655             }
656             Def::Fn(..) | Def::Static(..) | Def::Const(..) | Def::VariantCtor(..) => {
657                 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
658             }
659             Def::StructCtor(..) => {
660                 self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, expansion));
661
662                 if let Some(struct_def_id) =
663                         self.cstore.def_key(def_id).parent
664                             .map(|index| DefId { krate: def_id.krate, index: index }) {
665                     self.struct_constructors.insert(struct_def_id, (def, vis));
666                 }
667             }
668             Def::Trait(..) => {
669                 let module_kind = ModuleKind::Def(def, ident.name);
670                 let module = self.new_module(parent,
671                                              module_kind,
672                                              parent.normal_ancestor_id,
673                                              expansion,
674                                              span);
675                 self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
676
677                 for child in self.cstore.item_children_untracked(def_id, self.session) {
678                     let ns = if let Def::AssociatedTy(..) = child.def { TypeNS } else { ValueNS };
679                     self.define(module, child.ident, ns,
680                                 (child.def, ty::Visibility::Public, DUMMY_SP, expansion));
681
682                     if self.cstore.associated_item_cloned_untracked(child.def.def_id())
683                            .method_has_self_argument {
684                         self.has_self.insert(child.def.def_id());
685                     }
686                 }
687                 module.populated.set(true);
688             }
689             Def::Existential(..) |
690             Def::TraitAlias(..) => {
691                 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
692             }
693             Def::Struct(..) | Def::Union(..) => {
694                 self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, expansion));
695
696                 // Record field names for error reporting.
697                 let field_names = self.cstore.struct_field_names_untracked(def_id);
698                 self.insert_field_names(def_id, field_names);
699             }
700             Def::Macro(..) => {
701                 self.define(parent, ident, MacroNS, (def, vis, DUMMY_SP, expansion));
702             }
703             _ => bug!("unexpected definition: {:?}", def)
704         }
705     }
706
707     pub fn get_module(&mut self, def_id: DefId) -> Module<'a> {
708         if def_id.krate == LOCAL_CRATE {
709             return self.module_map[&def_id]
710         }
711
712         let macros_only = self.cstore.dep_kind_untracked(def_id.krate).macros_only();
713         if let Some(&module) = self.extern_module_map.get(&(def_id, macros_only)) {
714             return module;
715         }
716
717         let (name, parent) = if def_id.index == CRATE_DEF_INDEX {
718             (self.cstore.crate_name_untracked(def_id.krate).as_interned_str(), None)
719         } else {
720             let def_key = self.cstore.def_key(def_id);
721             (def_key.disambiguated_data.data.get_opt_name().unwrap(),
722              Some(self.get_module(DefId { index: def_key.parent.unwrap(), ..def_id })))
723         };
724
725         let kind = ModuleKind::Def(Def::Mod(def_id), name.as_symbol());
726         let module =
727             self.arenas.alloc_module(ModuleData::new(parent, kind, def_id, Mark::root(), DUMMY_SP));
728         self.extern_module_map.insert((def_id, macros_only), module);
729         module
730     }
731
732     pub fn macro_def_scope(&mut self, expansion: Mark) -> Module<'a> {
733         let def_id = self.macro_defs[&expansion];
734         if let Some(id) = self.definitions.as_local_node_id(def_id) {
735             self.local_macro_def_scopes[&id]
736         } else if def_id.krate == CrateNum::BuiltinMacros {
737             self.injected_crate.unwrap_or(self.graph_root)
738         } else {
739             let module_def_id = ty::DefIdTree::parent(&*self, def_id).unwrap();
740             self.get_module(module_def_id)
741         }
742     }
743
744     pub fn get_macro(&mut self, def: Def) -> Lrc<SyntaxExtension> {
745         let def_id = match def {
746             Def::Macro(def_id, ..) => def_id,
747             Def::NonMacroAttr(attr_kind) => return Lrc::new(SyntaxExtension::NonMacroAttr {
748                 mark_used: attr_kind == NonMacroAttrKind::Tool,
749             }),
750             _ => panic!("expected `Def::Macro` or `Def::NonMacroAttr`"),
751         };
752         if let Some(ext) = self.macro_map.get(&def_id) {
753             return ext.clone();
754         }
755
756         let macro_def = match self.cstore.load_macro_untracked(def_id, &self.session) {
757             LoadedMacro::MacroDef(macro_def) => macro_def,
758             LoadedMacro::ProcMacro(ext) => return ext,
759         };
760
761         let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
762                                                &self.session.features_untracked(),
763                                                &macro_def,
764                                                self.cstore.crate_edition_untracked(def_id.krate)));
765         self.macro_map.insert(def_id, ext.clone());
766         ext
767     }
768
769     /// Ensures that the reduced graph rooted at the given external module
770     /// is built, building it if it is not.
771     pub fn populate_module_if_necessary(&mut self, module: Module<'a>) {
772         if module.populated.get() { return }
773         let def_id = module.def_id().unwrap();
774         for child in self.cstore.item_children_untracked(def_id, self.session) {
775             self.build_reduced_graph_for_external_crate_def(module, child);
776         }
777         module.populated.set(true)
778     }
779
780     fn legacy_import_macro(&mut self,
781                            name: Name,
782                            binding: &'a NameBinding<'a>,
783                            span: Span,
784                            allow_shadowing: bool) {
785         if self.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing {
786             let msg = format!("`{}` is already in scope", name);
787             let note =
788                 "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)";
789             self.session.struct_span_err(span, &msg).note(note).emit();
790         }
791     }
792
793     /// Returns `true` if we should consider the underlying `extern crate` to be used.
794     fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>,
795                                     parent_scope: &ParentScope<'a>) -> bool {
796         let mut import_all = None;
797         let mut single_imports = Vec::new();
798         for attr in &item.attrs {
799             if attr.check_name("macro_use") {
800                 if self.current_module.parent.is_some() {
801                     span_err!(self.session, item.span, E0468,
802                         "an `extern crate` loading macros must be at the crate root");
803                 }
804                 if let ItemKind::ExternCrate(Some(orig_name)) = item.node {
805                     if orig_name == keywords::SelfLower.name() {
806                         self.session.span_err(attr.span,
807                             "`macro_use` is not supported on `extern crate self`");
808                     }
809                 }
810                 let ill_formed = |span| span_err!(self.session, span, E0466, "bad macro import");
811                 match attr.meta() {
812                     Some(meta) => match meta.node {
813                         MetaItemKind::Word => {
814                             import_all = Some(meta.span);
815                             break;
816                         }
817                         MetaItemKind::List(nested_metas) => for nested_meta in nested_metas {
818                             match nested_meta.word() {
819                                 Some(word) => single_imports.push((word.name(), word.span)),
820                                 None => ill_formed(nested_meta.span),
821                             }
822                         }
823                         MetaItemKind::NameValue(..) => ill_formed(meta.span),
824                     }
825                     None => ill_formed(attr.span()),
826                 }
827             }
828         }
829
830         let arenas = self.arenas;
831         let macro_use_directive = |span| arenas.alloc_import_directive(ImportDirective {
832             root_id: item.id,
833             id: item.id,
834             parent_scope: parent_scope.clone(),
835             imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
836             subclass: ImportDirectiveSubclass::MacroUse,
837             use_span_with_attributes: item.span_with_attributes(),
838             has_attributes: !item.attrs.is_empty(),
839             use_span: item.span,
840             root_span: span,
841             span,
842             module_path: Vec::new(),
843             vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))),
844             used: Cell::new(false),
845         });
846
847         let allow_shadowing = parent_scope.expansion == Mark::root();
848         if let Some(span) = import_all {
849             let directive = macro_use_directive(span);
850             self.potentially_unused_imports.push(directive);
851             module.for_each_child(|ident, ns, binding| if ns == MacroNS {
852                 let imported_binding = self.import(binding, directive);
853                 self.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
854             });
855         } else {
856             for (name, span) in single_imports.iter().cloned() {
857                 let ident = Ident::with_empty_ctxt(name);
858                 let result = self.resolve_ident_in_module(
859                     ModuleOrUniformRoot::Module(module),
860                     ident,
861                     MacroNS,
862                     None,
863                     false,
864                     span,
865                 );
866                 if let Ok(binding) = result {
867                     let directive = macro_use_directive(span);
868                     self.potentially_unused_imports.push(directive);
869                     let imported_binding = self.import(binding, directive);
870                     self.legacy_import_macro(name, imported_binding, span, allow_shadowing);
871                 } else {
872                     span_err!(self.session, span, E0469, "imported macro not found");
873                 }
874             }
875         }
876         import_all.is_some() || !single_imports.is_empty()
877     }
878
879     /// Returns `true` if this attribute list contains `macro_use`.
880     fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
881         for attr in attrs {
882             if attr.check_name("macro_escape") {
883                 let msg = "macro_escape is a deprecated synonym for macro_use";
884                 let mut err = self.session.struct_span_warn(attr.span, msg);
885                 if let ast::AttrStyle::Inner = attr.style {
886                     err.help("consider an outer attribute, #[macro_use] mod ...").emit();
887                 } else {
888                     err.emit();
889                 }
890             } else if !attr.check_name("macro_use") {
891                 continue;
892             }
893
894             if !attr.is_word() {
895                 self.session.span_err(attr.span, "arguments to macro_use are not allowed here");
896             }
897             return true;
898         }
899
900         false
901     }
902 }
903
904 pub struct BuildReducedGraphVisitor<'a, 'b: 'a> {
905     pub resolver: &'a mut Resolver<'b>,
906     pub current_legacy_scope: LegacyScope<'b>,
907     pub expansion: Mark,
908 }
909
910 impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
911     fn visit_invoc(&mut self, id: ast::NodeId) -> &'b InvocationData<'b> {
912         let mark = id.placeholder_to_mark();
913         self.resolver.current_module.unresolved_invocations.borrow_mut().insert(mark);
914         let invocation = self.resolver.invocations[&mark];
915         invocation.module.set(self.resolver.current_module);
916         invocation.parent_legacy_scope.set(self.current_legacy_scope);
917         invocation
918     }
919 }
920
921 macro_rules! method {
922     ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
923         fn $visit(&mut self, node: &'a $ty) {
924             if let $invoc(..) = node.node {
925                 self.visit_invoc(node.id);
926             } else {
927                 visit::$walk(self, node);
928             }
929         }
930     }
931 }
932
933 impl<'a, 'b> Visitor<'a> for BuildReducedGraphVisitor<'a, 'b> {
934     method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item);
935     method!(visit_expr:      ast::Expr,     ast::ExprKind::Mac,       walk_expr);
936     method!(visit_pat:       ast::Pat,      ast::PatKind::Mac,        walk_pat);
937     method!(visit_ty:        ast::Ty,       ast::TyKind::Mac,         walk_ty);
938
939     fn visit_item(&mut self, item: &'a Item) {
940         let macro_use = match item.node {
941             ItemKind::MacroDef(..) => {
942                 self.resolver.define_macro(item, self.expansion, &mut self.current_legacy_scope);
943                 return
944             }
945             ItemKind::Mac(..) => {
946                 self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(item.id));
947                 return
948             }
949             ItemKind::Mod(..) => self.resolver.contains_macro_use(&item.attrs),
950             _ => false,
951         };
952
953         let orig_current_module = self.resolver.current_module;
954         let orig_current_legacy_scope = self.current_legacy_scope;
955         let parent_scope = ParentScope {
956             module: self.resolver.current_module,
957             expansion: self.expansion,
958             legacy: self.current_legacy_scope,
959             derives: Vec::new(),
960         };
961         self.resolver.build_reduced_graph_for_item(item, parent_scope);
962         visit::walk_item(self, item);
963         self.resolver.current_module = orig_current_module;
964         if !macro_use {
965             self.current_legacy_scope = orig_current_legacy_scope;
966         }
967     }
968
969     fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
970         if let ast::StmtKind::Mac(..) = stmt.node {
971             self.current_legacy_scope = LegacyScope::Invocation(self.visit_invoc(stmt.id));
972         } else {
973             visit::walk_stmt(self, stmt);
974         }
975     }
976
977     fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
978         if let ForeignItemKind::Macro(_) = foreign_item.node {
979             self.visit_invoc(foreign_item.id);
980             return;
981         }
982
983         self.resolver.build_reduced_graph_for_foreign_item(foreign_item, self.expansion);
984         visit::walk_foreign_item(self, foreign_item);
985     }
986
987     fn visit_block(&mut self, block: &'a Block) {
988         let orig_current_module = self.resolver.current_module;
989         let orig_current_legacy_scope = self.current_legacy_scope;
990         self.resolver.build_reduced_graph_for_block(block, self.expansion);
991         visit::walk_block(self, block);
992         self.resolver.current_module = orig_current_module;
993         self.current_legacy_scope = orig_current_legacy_scope;
994     }
995
996     fn visit_trait_item(&mut self, item: &'a TraitItem) {
997         let parent = self.resolver.current_module;
998
999         if let TraitItemKind::Macro(_) = item.node {
1000             self.visit_invoc(item.id);
1001             return
1002         }
1003
1004         // Add the item to the trait info.
1005         let item_def_id = self.resolver.definitions.local_def_id(item.id);
1006         let (def, ns) = match item.node {
1007             TraitItemKind::Const(..) => (Def::AssociatedConst(item_def_id), ValueNS),
1008             TraitItemKind::Method(ref sig, _) => {
1009                 if sig.decl.has_self() {
1010                     self.resolver.has_self.insert(item_def_id);
1011                 }
1012                 (Def::Method(item_def_id), ValueNS)
1013             }
1014             TraitItemKind::Type(..) => (Def::AssociatedTy(item_def_id), TypeNS),
1015             TraitItemKind::Macro(_) => bug!(),  // handled above
1016         };
1017
1018         let vis = ty::Visibility::Public;
1019         self.resolver.define(parent, item.ident, ns, (def, vis, item.span, self.expansion));
1020
1021         self.resolver.current_module = parent.parent.unwrap(); // nearest normal ancestor
1022         visit::walk_trait_item(self, item);
1023         self.resolver.current_module = parent;
1024     }
1025
1026     fn visit_token(&mut self, t: Token) {
1027         if let Token::Interpolated(nt) = t {
1028             if let token::NtExpr(ref expr) = nt.0 {
1029                 if let ast::ExprKind::Mac(..) = expr.node {
1030                     self.visit_invoc(expr.id);
1031                 }
1032             }
1033         }
1034     }
1035
1036     fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1037         if !attr.is_sugared_doc && is_builtin_attr(attr) {
1038             let parent_scope = ParentScope {
1039                 module: self.resolver.current_module.nearest_item_scope(),
1040                 expansion: self.expansion,
1041                 legacy: self.current_legacy_scope,
1042                 // Let's hope discerning built-in attributes from derive helpers is not necessary
1043                 derives: Vec::new(),
1044             };
1045             parent_scope.module.builtin_attrs.borrow_mut().push((
1046                 attr.path.segments[0].ident, parent_scope
1047             ));
1048         }
1049         visit::walk_attribute(self, attr);
1050     }
1051 }