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