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