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