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