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