]> git.proxmox.com Git - rustc.git/blob - src/librustc_resolve/lib.rs
5d10b0d9a57b80b31990b6221e44f1cc87370e54
[rustc.git] / src / librustc_resolve / lib.rs
1 // Copyright 2012-2015 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 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
12 #![cfg_attr(stage0, feature(custom_attribute))]
13 #![crate_name = "rustc_resolve"]
14 #![unstable(feature = "rustc_private")]
15 #![staged_api]
16 #![crate_type = "dylib"]
17 #![crate_type = "rlib"]
18 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
19 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
20 html_root_url = "http://doc.rust-lang.org/nightly/")]
21
22 #![feature(associated_consts)]
23 #![feature(rc_weak)]
24 #![feature(rustc_diagnostic_macros)]
25 #![feature(rustc_private)]
26 #![feature(slice_extras)]
27 #![feature(staged_api)]
28
29 #[macro_use] extern crate log;
30 #[macro_use] extern crate syntax;
31 #[macro_use] #[no_link] extern crate rustc_bitflags;
32
33 extern crate rustc;
34
35 use self::PatternBindingMode::*;
36 use self::Namespace::*;
37 use self::NamespaceResult::*;
38 use self::NameDefinition::*;
39 use self::ResolveResult::*;
40 use self::FallbackSuggestion::*;
41 use self::TypeParameters::*;
42 use self::RibKind::*;
43 use self::UseLexicalScopeFlag::*;
44 use self::ModulePrefixResult::*;
45 use self::AssocItemResolveResult::*;
46 use self::NameSearchType::*;
47 use self::BareIdentifierPatternResolution::*;
48 use self::ParentLink::*;
49 use self::ModuleKind::*;
50 use self::FallbackChecks::*;
51
52 use rustc::ast_map;
53 use rustc::session::Session;
54 use rustc::lint;
55 use rustc::metadata::csearch;
56 use rustc::metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
57 use rustc::middle::def::*;
58 use rustc::middle::pat_util::pat_bindings;
59 use rustc::middle::privacy::*;
60 use rustc::middle::subst::{ParamSpace, FnSpace, TypeSpace};
61 use rustc::middle::ty::{Freevar, FreevarMap, TraitMap, GlobMap};
62 use rustc::util::nodemap::{NodeMap, NodeSet, DefIdSet, FnvHashMap};
63 use rustc::util::lev_distance::lev_distance;
64
65 use syntax::ast::{Arm, BindByRef, BindByValue, BindingMode, Block};
66 use syntax::ast::{ConstImplItem, Crate, CrateNum};
67 use syntax::ast::{DefId, Expr, ExprAgain, ExprBreak, ExprField};
68 use syntax::ast::{ExprLoop, ExprWhile, ExprMethodCall};
69 use syntax::ast::{ExprPath, ExprStruct, FnDecl};
70 use syntax::ast::{ForeignItemFn, ForeignItemStatic, Generics};
71 use syntax::ast::{Ident, ImplItem, Item, ItemConst, ItemEnum, ItemExternCrate};
72 use syntax::ast::{ItemFn, ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl};
73 use syntax::ast::{ItemStruct, ItemTrait, ItemTy, ItemUse};
74 use syntax::ast::{Local, MethodImplItem, Name, NodeId};
75 use syntax::ast::{Pat, PatEnum, PatIdent, PatLit, PatQPath};
76 use syntax::ast::{PatRange, PatStruct, Path, PrimTy};
77 use syntax::ast::{TraitRef, Ty, TyBool, TyChar, TyF32};
78 use syntax::ast::{TyF64, TyFloat, TyIs, TyI8, TyI16, TyI32, TyI64, TyInt};
79 use syntax::ast::{TyPath, TyPtr};
80 use syntax::ast::{TyRptr, TyStr, TyUs, TyU8, TyU16, TyU32, TyU64, TyUint};
81 use syntax::ast::TypeImplItem;
82 use syntax::ast;
83 use syntax::ast_util::{local_def, walk_pat};
84 use syntax::attr::AttrMetaMethods;
85 use syntax::ext::mtwt;
86 use syntax::parse::token::{self, special_names, special_idents};
87 use syntax::ptr::P;
88 use syntax::codemap::{self, Span, Pos};
89 use syntax::visit::{self, Visitor};
90
91 use std::collections::{HashMap, HashSet};
92 use std::collections::hash_map::Entry::{Occupied, Vacant};
93 use std::cell::{Cell, RefCell};
94 use std::fmt;
95 use std::mem::replace;
96 use std::rc::{Rc, Weak};
97 use std::usize;
98
99 use resolve_imports::{Target, ImportDirective, ImportResolution};
100 use resolve_imports::Shadowable;
101
102
103 // NB: This module needs to be declared first so diagnostics are
104 // registered before they are used.
105 pub mod diagnostics;
106
107 mod check_unused;
108 mod record_exports;
109 mod build_reduced_graph;
110 mod resolve_imports;
111
112 #[derive(Copy, Clone)]
113 struct BindingInfo {
114 span: Span,
115 binding_mode: BindingMode,
116 }
117
118 // Map from the name in a pattern to its binding mode.
119 type BindingMap = HashMap<Name, BindingInfo>;
120
121 #[derive(Copy, Clone, PartialEq)]
122 enum PatternBindingMode {
123 RefutableMode,
124 LocalIrrefutableMode,
125 ArgumentIrrefutableMode,
126 }
127
128 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
129 enum Namespace {
130 TypeNS,
131 ValueNS
132 }
133
134 /// A NamespaceResult represents the result of resolving an import in
135 /// a particular namespace. The result is either definitely-resolved,
136 /// definitely- unresolved, or unknown.
137 #[derive(Clone)]
138 enum NamespaceResult {
139 /// Means that resolve hasn't gathered enough information yet to determine
140 /// whether the name is bound in this namespace. (That is, it hasn't
141 /// resolved all `use` directives yet.)
142 UnknownResult,
143 /// Means that resolve has determined that the name is definitely
144 /// not bound in the namespace.
145 UnboundResult,
146 /// Means that resolve has determined that the name is bound in the Module
147 /// argument, and specified by the NameBindings argument.
148 BoundResult(Rc<Module>, Rc<NameBindings>)
149 }
150
151 impl NamespaceResult {
152 fn is_unknown(&self) -> bool {
153 match *self {
154 UnknownResult => true,
155 _ => false
156 }
157 }
158 fn is_unbound(&self) -> bool {
159 match *self {
160 UnboundResult => true,
161 _ => false
162 }
163 }
164 }
165
166 enum NameDefinition {
167 // The name was unbound.
168 NoNameDefinition,
169 // The name identifies an immediate child.
170 ChildNameDefinition(Def, LastPrivate),
171 // The name identifies an import.
172 ImportNameDefinition(Def, LastPrivate),
173 }
174
175 impl<'a, 'v, 'tcx> Visitor<'v> for Resolver<'a, 'tcx> {
176 fn visit_item(&mut self, item: &Item) {
177 self.resolve_item(item);
178 }
179 fn visit_arm(&mut self, arm: &Arm) {
180 self.resolve_arm(arm);
181 }
182 fn visit_block(&mut self, block: &Block) {
183 self.resolve_block(block);
184 }
185 fn visit_expr(&mut self, expr: &Expr) {
186 self.resolve_expr(expr);
187 }
188 fn visit_local(&mut self, local: &Local) {
189 self.resolve_local(local);
190 }
191 fn visit_ty(&mut self, ty: &Ty) {
192 self.resolve_type(ty);
193 }
194 fn visit_generics(&mut self, generics: &Generics) {
195 self.resolve_generics(generics);
196 }
197 fn visit_poly_trait_ref(&mut self,
198 tref: &ast::PolyTraitRef,
199 m: &ast::TraitBoundModifier) {
200 match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
201 Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
202 Err(_) => { /* error already reported */ }
203 }
204 visit::walk_poly_trait_ref(self, tref, m);
205 }
206 fn visit_variant(&mut self, variant: &ast::Variant, generics: &Generics) {
207 if let Some(ref dis_expr) = variant.node.disr_expr {
208 // resolve the discriminator expr as a constant
209 self.with_constant_rib(|this| {
210 this.visit_expr(&**dis_expr);
211 });
212 }
213
214 // `visit::walk_variant` without the discriminant expression.
215 match variant.node.kind {
216 ast::TupleVariantKind(ref variant_arguments) => {
217 for variant_argument in variant_arguments {
218 self.visit_ty(&*variant_argument.ty);
219 }
220 }
221 ast::StructVariantKind(ref struct_definition) => {
222 self.visit_struct_def(&**struct_definition,
223 variant.node.name,
224 generics,
225 variant.node.id);
226 }
227 }
228 }
229 fn visit_foreign_item(&mut self, foreign_item: &ast::ForeignItem) {
230 let type_parameters = match foreign_item.node {
231 ForeignItemFn(_, ref generics) => {
232 HasTypeParameters(generics, FnSpace, ItemRibKind)
233 }
234 ForeignItemStatic(..) => NoTypeParameters
235 };
236 self.with_type_parameter_rib(type_parameters, |this| {
237 visit::walk_foreign_item(this, foreign_item);
238 });
239 }
240 fn visit_fn(&mut self,
241 function_kind: visit::FnKind<'v>,
242 declaration: &'v FnDecl,
243 block: &'v Block,
244 _: Span,
245 node_id: NodeId) {
246 let rib_kind = match function_kind {
247 visit::FkItemFn(_, generics, _, _, _, _) => {
248 self.visit_generics(generics);
249 ItemRibKind
250 }
251 visit::FkMethod(_, sig, _) => {
252 self.visit_generics(&sig.generics);
253 self.visit_explicit_self(&sig.explicit_self);
254 MethodRibKind
255 }
256 visit::FkFnBlock(..) => ClosureRibKind(node_id)
257 };
258 self.resolve_function(rib_kind, declaration, block);
259 }
260 }
261
262 type ErrorMessage = Option<(Span, String)>;
263
264 enum ResolveResult<T> {
265 Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
266 Indeterminate, // Couldn't determine due to unresolved globs.
267 Success(T) // Successfully resolved the import.
268 }
269
270 impl<T> ResolveResult<T> {
271 fn indeterminate(&self) -> bool {
272 match *self { Indeterminate => true, _ => false }
273 }
274 }
275
276 enum FallbackSuggestion {
277 NoSuggestion,
278 Field,
279 Method,
280 TraitItem,
281 StaticMethod(String),
282 TraitMethod(String),
283 }
284
285 #[derive(Copy, Clone)]
286 enum TypeParameters<'a> {
287 NoTypeParameters,
288 HasTypeParameters(
289 // Type parameters.
290 &'a Generics,
291
292 // Identifies the things that these parameters
293 // were declared on (type, fn, etc)
294 ParamSpace,
295
296 // The kind of the rib used for type parameters.
297 RibKind)
298 }
299
300 // The rib kind controls the translation of local
301 // definitions (`DefLocal`) to upvars (`DefUpvar`).
302 #[derive(Copy, Clone, Debug)]
303 enum RibKind {
304 // No translation needs to be applied.
305 NormalRibKind,
306
307 // We passed through a closure scope at the given node ID.
308 // Translate upvars as appropriate.
309 ClosureRibKind(NodeId /* func id */),
310
311 // We passed through an impl or trait and are now in one of its
312 // methods. Allow references to ty params that impl or trait
313 // binds. Disallow any other upvars (including other ty params that are
314 // upvars).
315 MethodRibKind,
316
317 // We passed through an item scope. Disallow upvars.
318 ItemRibKind,
319
320 // We're in a constant item. Can't refer to dynamic stuff.
321 ConstantItemRibKind
322 }
323
324 #[derive(Copy, Clone)]
325 enum UseLexicalScopeFlag {
326 DontUseLexicalScope,
327 UseLexicalScope
328 }
329
330 enum ModulePrefixResult {
331 NoPrefixFound,
332 PrefixFound(Rc<Module>, usize)
333 }
334
335 #[derive(Copy, Clone)]
336 enum AssocItemResolveResult {
337 /// Syntax such as `<T>::item`, which can't be resolved until type
338 /// checking.
339 TypecheckRequired,
340 /// We should have been able to resolve the associated item.
341 ResolveAttempt(Option<PathResolution>),
342 }
343
344 #[derive(Copy, Clone, PartialEq)]
345 enum NameSearchType {
346 /// We're doing a name search in order to resolve a `use` directive.
347 ImportSearch,
348
349 /// We're doing a name search in order to resolve a path type, a path
350 /// expression, or a path pattern.
351 PathSearch,
352 }
353
354 #[derive(Copy, Clone)]
355 enum BareIdentifierPatternResolution {
356 FoundStructOrEnumVariant(Def, LastPrivate),
357 FoundConst(Def, LastPrivate),
358 BareIdentifierPatternUnresolved
359 }
360
361 /// One local scope.
362 #[derive(Debug)]
363 struct Rib {
364 bindings: HashMap<Name, DefLike>,
365 kind: RibKind,
366 }
367
368 impl Rib {
369 fn new(kind: RibKind) -> Rib {
370 Rib {
371 bindings: HashMap::new(),
372 kind: kind
373 }
374 }
375 }
376
377 /// The link from a module up to its nearest parent node.
378 #[derive(Clone,Debug)]
379 enum ParentLink {
380 NoParentLink,
381 ModuleParentLink(Weak<Module>, Name),
382 BlockParentLink(Weak<Module>, NodeId)
383 }
384
385 /// The type of module this is.
386 #[derive(Copy, Clone, PartialEq, Debug)]
387 enum ModuleKind {
388 NormalModuleKind,
389 TraitModuleKind,
390 EnumModuleKind,
391 TypeModuleKind,
392 AnonymousModuleKind,
393 }
394
395 /// One node in the tree of modules.
396 pub struct Module {
397 parent_link: ParentLink,
398 def_id: Cell<Option<DefId>>,
399 kind: Cell<ModuleKind>,
400 is_public: bool,
401
402 children: RefCell<HashMap<Name, Rc<NameBindings>>>,
403 imports: RefCell<Vec<ImportDirective>>,
404
405 // The external module children of this node that were declared with
406 // `extern crate`.
407 external_module_children: RefCell<HashMap<Name, Rc<Module>>>,
408
409 // The anonymous children of this node. Anonymous children are pseudo-
410 // modules that are implicitly created around items contained within
411 // blocks.
412 //
413 // For example, if we have this:
414 //
415 // fn f() {
416 // fn g() {
417 // ...
418 // }
419 // }
420 //
421 // There will be an anonymous module created around `g` with the ID of the
422 // entry block for `f`.
423 anonymous_children: RefCell<NodeMap<Rc<Module>>>,
424
425 // The status of resolving each import in this module.
426 import_resolutions: RefCell<HashMap<Name, ImportResolution>>,
427
428 // The number of unresolved globs that this module exports.
429 glob_count: Cell<usize>,
430
431 // The index of the import we're resolving.
432 resolved_import_count: Cell<usize>,
433
434 // Whether this module is populated. If not populated, any attempt to
435 // access the children must be preceded with a
436 // `populate_module_if_necessary` call.
437 populated: Cell<bool>,
438 }
439
440 impl Module {
441 fn new(parent_link: ParentLink,
442 def_id: Option<DefId>,
443 kind: ModuleKind,
444 external: bool,
445 is_public: bool)
446 -> Module {
447 Module {
448 parent_link: parent_link,
449 def_id: Cell::new(def_id),
450 kind: Cell::new(kind),
451 is_public: is_public,
452 children: RefCell::new(HashMap::new()),
453 imports: RefCell::new(Vec::new()),
454 external_module_children: RefCell::new(HashMap::new()),
455 anonymous_children: RefCell::new(NodeMap()),
456 import_resolutions: RefCell::new(HashMap::new()),
457 glob_count: Cell::new(0),
458 resolved_import_count: Cell::new(0),
459 populated: Cell::new(!external),
460 }
461 }
462
463 fn all_imports_resolved(&self) -> bool {
464 self.imports.borrow().len() == self.resolved_import_count.get()
465 }
466 }
467
468 impl fmt::Debug for Module {
469 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
470 write!(f, "{:?}, kind: {:?}, {}",
471 self.def_id,
472 self.kind,
473 if self.is_public { "public" } else { "private" } )
474 }
475 }
476
477 bitflags! {
478 #[derive(Debug)]
479 flags DefModifiers: u8 {
480 const PUBLIC = 1 << 0,
481 const IMPORTABLE = 1 << 1,
482 }
483 }
484
485 // Records a possibly-private type definition.
486 #[derive(Clone,Debug)]
487 struct TypeNsDef {
488 modifiers: DefModifiers, // see note in ImportResolution about how to use this
489 module_def: Option<Rc<Module>>,
490 type_def: Option<Def>,
491 type_span: Option<Span>
492 }
493
494 // Records a possibly-private value definition.
495 #[derive(Clone, Copy, Debug)]
496 struct ValueNsDef {
497 modifiers: DefModifiers, // see note in ImportResolution about how to use this
498 def: Def,
499 value_span: Option<Span>,
500 }
501
502 // Records the definitions (at most one for each namespace) that a name is
503 // bound to.
504 #[derive(Debug)]
505 pub struct NameBindings {
506 type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
507 value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
508 }
509
510 impl NameBindings {
511 fn new() -> NameBindings {
512 NameBindings {
513 type_def: RefCell::new(None),
514 value_def: RefCell::new(None),
515 }
516 }
517
518 /// Creates a new module in this set of name bindings.
519 fn define_module(&self,
520 parent_link: ParentLink,
521 def_id: Option<DefId>,
522 kind: ModuleKind,
523 external: bool,
524 is_public: bool,
525 sp: Span) {
526 // Merges the module with the existing type def or creates a new one.
527 let modifiers = if is_public {
528 DefModifiers::PUBLIC
529 } else {
530 DefModifiers::empty()
531 } | DefModifiers::IMPORTABLE;
532 let module_ = Rc::new(Module::new(parent_link,
533 def_id,
534 kind,
535 external,
536 is_public));
537 let type_def = self.type_def.borrow().clone();
538 match type_def {
539 None => {
540 *self.type_def.borrow_mut() = Some(TypeNsDef {
541 modifiers: modifiers,
542 module_def: Some(module_),
543 type_def: None,
544 type_span: Some(sp)
545 });
546 }
547 Some(type_def) => {
548 *self.type_def.borrow_mut() = Some(TypeNsDef {
549 modifiers: modifiers,
550 module_def: Some(module_),
551 type_span: Some(sp),
552 type_def: type_def.type_def
553 });
554 }
555 }
556 }
557
558 /// Sets the kind of the module, creating a new one if necessary.
559 fn set_module_kind(&self,
560 parent_link: ParentLink,
561 def_id: Option<DefId>,
562 kind: ModuleKind,
563 external: bool,
564 is_public: bool,
565 _sp: Span) {
566 let modifiers = if is_public {
567 DefModifiers::PUBLIC
568 } else {
569 DefModifiers::empty()
570 } | DefModifiers::IMPORTABLE;
571 let type_def = self.type_def.borrow().clone();
572 match type_def {
573 None => {
574 let module = Module::new(parent_link,
575 def_id,
576 kind,
577 external,
578 is_public);
579 *self.type_def.borrow_mut() = Some(TypeNsDef {
580 modifiers: modifiers,
581 module_def: Some(Rc::new(module)),
582 type_def: None,
583 type_span: None,
584 });
585 }
586 Some(type_def) => {
587 match type_def.module_def {
588 None => {
589 let module = Module::new(parent_link,
590 def_id,
591 kind,
592 external,
593 is_public);
594 *self.type_def.borrow_mut() = Some(TypeNsDef {
595 modifiers: modifiers,
596 module_def: Some(Rc::new(module)),
597 type_def: type_def.type_def,
598 type_span: None,
599 });
600 }
601 Some(module_def) => module_def.kind.set(kind),
602 }
603 }
604 }
605 }
606
607 /// Records a type definition.
608 fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
609 debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
610 // Merges the type with the existing type def or creates a new one.
611 let type_def = self.type_def.borrow().clone();
612 match type_def {
613 None => {
614 *self.type_def.borrow_mut() = Some(TypeNsDef {
615 module_def: None,
616 type_def: Some(def),
617 type_span: Some(sp),
618 modifiers: modifiers,
619 });
620 }
621 Some(type_def) => {
622 *self.type_def.borrow_mut() = Some(TypeNsDef {
623 module_def: type_def.module_def,
624 type_def: Some(def),
625 type_span: Some(sp),
626 modifiers: modifiers,
627 });
628 }
629 }
630 }
631
632 /// Records a value definition.
633 fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
634 debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
635 *self.value_def.borrow_mut() = Some(ValueNsDef {
636 def: def,
637 value_span: Some(sp),
638 modifiers: modifiers,
639 });
640 }
641
642 /// Returns the module node if applicable.
643 fn get_module_if_available(&self) -> Option<Rc<Module>> {
644 match *self.type_def.borrow() {
645 Some(ref type_def) => type_def.module_def.clone(),
646 None => None
647 }
648 }
649
650 /// Returns the module node. Panics if this node does not have a module
651 /// definition.
652 fn get_module(&self) -> Rc<Module> {
653 match self.get_module_if_available() {
654 None => {
655 panic!("get_module called on a node with no module \
656 definition!")
657 }
658 Some(module_def) => module_def
659 }
660 }
661
662 fn defined_in_namespace(&self, namespace: Namespace) -> bool {
663 match namespace {
664 TypeNS => return self.type_def.borrow().is_some(),
665 ValueNS => return self.value_def.borrow().is_some()
666 }
667 }
668
669 fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
670 self.defined_in_namespace_with(namespace, DefModifiers::PUBLIC)
671 }
672
673 fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
674 match namespace {
675 TypeNS => match *self.type_def.borrow() {
676 Some(ref def) => def.modifiers.contains(modifiers), None => false
677 },
678 ValueNS => match *self.value_def.borrow() {
679 Some(ref def) => def.modifiers.contains(modifiers), None => false
680 }
681 }
682 }
683
684 fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
685 match namespace {
686 TypeNS => {
687 match *self.type_def.borrow() {
688 None => None,
689 Some(ref type_def) => {
690 match type_def.type_def {
691 Some(type_def) => Some(type_def),
692 None => {
693 match type_def.module_def {
694 Some(ref module) => {
695 match module.def_id.get() {
696 Some(did) => Some(DefMod(did)),
697 None => None,
698 }
699 }
700 None => None,
701 }
702 }
703 }
704 }
705 }
706 }
707 ValueNS => {
708 match *self.value_def.borrow() {
709 None => None,
710 Some(value_def) => Some(value_def.def)
711 }
712 }
713 }
714 }
715
716 fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
717 if self.defined_in_namespace(namespace) {
718 match namespace {
719 TypeNS => {
720 match *self.type_def.borrow() {
721 None => None,
722 Some(ref type_def) => type_def.type_span
723 }
724 }
725 ValueNS => {
726 match *self.value_def.borrow() {
727 None => None,
728 Some(ref value_def) => value_def.value_span
729 }
730 }
731 }
732 } else {
733 None
734 }
735 }
736
737 fn is_public(&self, namespace: Namespace) -> bool {
738 match namespace {
739 TypeNS => {
740 let type_def = self.type_def.borrow();
741 type_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
742 }
743 ValueNS => {
744 let value_def = self.value_def.borrow();
745 value_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
746 }
747 }
748 }
749 }
750
751 /// Interns the names of the primitive types.
752 struct PrimitiveTypeTable {
753 primitive_types: HashMap<Name, PrimTy>,
754 }
755
756 impl PrimitiveTypeTable {
757 fn new() -> PrimitiveTypeTable {
758 let mut table = PrimitiveTypeTable {
759 primitive_types: HashMap::new()
760 };
761
762 table.intern("bool", TyBool);
763 table.intern("char", TyChar);
764 table.intern("f32", TyFloat(TyF32));
765 table.intern("f64", TyFloat(TyF64));
766 table.intern("isize", TyInt(TyIs));
767 table.intern("i8", TyInt(TyI8));
768 table.intern("i16", TyInt(TyI16));
769 table.intern("i32", TyInt(TyI32));
770 table.intern("i64", TyInt(TyI64));
771 table.intern("str", TyStr);
772 table.intern("usize", TyUint(TyUs));
773 table.intern("u8", TyUint(TyU8));
774 table.intern("u16", TyUint(TyU16));
775 table.intern("u32", TyUint(TyU32));
776 table.intern("u64", TyUint(TyU64));
777
778 table
779 }
780
781 fn intern(&mut self, string: &str, primitive_type: PrimTy) {
782 self.primitive_types.insert(token::intern(string), primitive_type);
783 }
784 }
785
786 /// The main resolver class.
787 pub struct Resolver<'a, 'tcx:'a> {
788 session: &'a Session,
789
790 ast_map: &'a ast_map::Map<'tcx>,
791
792 graph_root: NameBindings,
793
794 trait_item_map: FnvHashMap<(Name, DefId), DefId>,
795
796 structs: FnvHashMap<DefId, Vec<Name>>,
797
798 // The number of imports that are currently unresolved.
799 unresolved_imports: usize,
800
801 // The module that represents the current item scope.
802 current_module: Rc<Module>,
803
804 // The current set of local scopes, for values.
805 // FIXME #4948: Reuse ribs to avoid allocation.
806 value_ribs: Vec<Rib>,
807
808 // The current set of local scopes, for types.
809 type_ribs: Vec<Rib>,
810
811 // The current set of local scopes, for labels.
812 label_ribs: Vec<Rib>,
813
814 // The trait that the current context can refer to.
815 current_trait_ref: Option<(DefId, TraitRef)>,
816
817 // The current self type if inside an impl (used for better errors).
818 current_self_type: Option<Ty>,
819
820 // The idents for the primitive types.
821 primitive_type_table: PrimitiveTypeTable,
822
823 def_map: DefMap,
824 freevars: RefCell<FreevarMap>,
825 freevars_seen: RefCell<NodeMap<NodeSet>>,
826 export_map: ExportMap,
827 trait_map: TraitMap,
828 external_exports: ExternalExports,
829
830 // Whether or not to print error messages. Can be set to true
831 // when getting additional info for error message suggestions,
832 // so as to avoid printing duplicate errors
833 emit_errors: bool,
834
835 make_glob_map: bool,
836 // Maps imports to the names of items actually imported (this actually maps
837 // all imports, but only glob imports are actually interesting).
838 glob_map: GlobMap,
839
840 used_imports: HashSet<(NodeId, Namespace)>,
841 used_crates: HashSet<CrateNum>,
842 }
843
844 #[derive(PartialEq)]
845 enum FallbackChecks {
846 Everything,
847 OnlyTraitAndStatics
848 }
849
850 impl<'a, 'tcx> Resolver<'a, 'tcx> {
851 fn new(session: &'a Session,
852 ast_map: &'a ast_map::Map<'tcx>,
853 crate_span: Span,
854 make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
855 let graph_root = NameBindings::new();
856
857 graph_root.define_module(NoParentLink,
858 Some(DefId { krate: 0, node: 0 }),
859 NormalModuleKind,
860 false,
861 true,
862 crate_span);
863
864 let current_module = graph_root.get_module();
865
866 Resolver {
867 session: session,
868
869 ast_map: ast_map,
870
871 // The outermost module has def ID 0; this is not reflected in the
872 // AST.
873
874 graph_root: graph_root,
875
876 trait_item_map: FnvHashMap(),
877 structs: FnvHashMap(),
878
879 unresolved_imports: 0,
880
881 current_module: current_module,
882 value_ribs: Vec::new(),
883 type_ribs: Vec::new(),
884 label_ribs: Vec::new(),
885
886 current_trait_ref: None,
887 current_self_type: None,
888
889 primitive_type_table: PrimitiveTypeTable::new(),
890
891 def_map: RefCell::new(NodeMap()),
892 freevars: RefCell::new(NodeMap()),
893 freevars_seen: RefCell::new(NodeMap()),
894 export_map: NodeMap(),
895 trait_map: NodeMap(),
896 used_imports: HashSet::new(),
897 used_crates: HashSet::new(),
898 external_exports: DefIdSet(),
899
900 emit_errors: true,
901 make_glob_map: make_glob_map == MakeGlobMap::Yes,
902 glob_map: HashMap::new(),
903 }
904 }
905
906 #[inline]
907 fn record_import_use(&mut self, import_id: NodeId, name: Name) {
908 if !self.make_glob_map {
909 return;
910 }
911 if self.glob_map.contains_key(&import_id) {
912 self.glob_map.get_mut(&import_id).unwrap().insert(name);
913 return;
914 }
915
916 let mut new_set = HashSet::new();
917 new_set.insert(name);
918 self.glob_map.insert(import_id, new_set);
919 }
920
921 fn get_trait_name(&self, did: DefId) -> Name {
922 if did.krate == ast::LOCAL_CRATE {
923 self.ast_map.expect_item(did.node).ident.name
924 } else {
925 csearch::get_trait_name(&self.session.cstore, did)
926 }
927 }
928
929 fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
930 NameBindings {
931 type_def: RefCell::new(Some(TypeNsDef {
932 modifiers: DefModifiers::IMPORTABLE,
933 module_def: Some(module),
934 type_def: None,
935 type_span: None
936 })),
937 value_def: RefCell::new(None),
938 }
939 }
940
941 /// Checks that the names of external crates don't collide with other
942 /// external crates.
943 fn check_for_conflicts_between_external_crates(&self,
944 module: &Module,
945 name: Name,
946 span: Span) {
947 if module.external_module_children.borrow().contains_key(&name) {
948 span_err!(self.session, span, E0259,
949 "an external crate named `{}` has already \
950 been imported into this module",
951 &token::get_name(name));
952 }
953 }
954
955 /// Checks that the names of items don't collide with external crates.
956 fn check_for_conflicts_between_external_crates_and_items(&self,
957 module: &Module,
958 name: Name,
959 span: Span) {
960 if module.external_module_children.borrow().contains_key(&name) {
961 span_err!(self.session, span, E0260,
962 "the name `{}` conflicts with an external \
963 crate that has been imported into this \
964 module",
965 &token::get_name(name));
966 }
967 }
968
969 /// Resolves the given module path from the given root `module_`.
970 fn resolve_module_path_from_root(&mut self,
971 module_: Rc<Module>,
972 module_path: &[Name],
973 index: usize,
974 span: Span,
975 name_search_type: NameSearchType,
976 lp: LastPrivate)
977 -> ResolveResult<(Rc<Module>, LastPrivate)> {
978 fn search_parent_externals(needle: Name, module: &Rc<Module>)
979 -> Option<Rc<Module>> {
980 match module.external_module_children.borrow().get(&needle) {
981 Some(_) => Some(module.clone()),
982 None => match module.parent_link {
983 ModuleParentLink(ref parent, _) => {
984 search_parent_externals(needle, &parent.upgrade().unwrap())
985 }
986 _ => None
987 }
988 }
989 }
990
991 let mut search_module = module_;
992 let mut index = index;
993 let module_path_len = module_path.len();
994 let mut closest_private = lp;
995
996 // Resolve the module part of the path. This does not involve looking
997 // upward though scope chains; we simply resolve names directly in
998 // modules as we go.
999 while index < module_path_len {
1000 let name = module_path[index];
1001 match self.resolve_name_in_module(search_module.clone(),
1002 name,
1003 TypeNS,
1004 name_search_type,
1005 false) {
1006 Failed(None) => {
1007 let segment_name = token::get_name(name);
1008 let module_name = module_to_string(&*search_module);
1009 let mut span = span;
1010 let msg = if "???" == &module_name[..] {
1011 span.hi = span.lo + Pos::from_usize(segment_name.len());
1012
1013 match search_parent_externals(name,
1014 &self.current_module) {
1015 Some(module) => {
1016 let path_str = names_to_string(module_path);
1017 let target_mod_str = module_to_string(&*module);
1018 let current_mod_str =
1019 module_to_string(&*self.current_module);
1020
1021 let prefix = if target_mod_str == current_mod_str {
1022 "self::".to_string()
1023 } else {
1024 format!("{}::", target_mod_str)
1025 };
1026
1027 format!("Did you mean `{}{}`?", prefix, path_str)
1028 },
1029 None => format!("Maybe a missing `extern crate {}`?",
1030 segment_name),
1031 }
1032 } else {
1033 format!("Could not find `{}` in `{}`",
1034 segment_name,
1035 module_name)
1036 };
1037
1038 return Failed(Some((span, msg)));
1039 }
1040 Failed(err) => return Failed(err),
1041 Indeterminate => {
1042 debug!("(resolving module path for import) module \
1043 resolution is indeterminate: {}",
1044 token::get_name(name));
1045 return Indeterminate;
1046 }
1047 Success((target, used_proxy)) => {
1048 // Check to see whether there are type bindings, and, if
1049 // so, whether there is a module within.
1050 match *target.bindings.type_def.borrow() {
1051 Some(ref type_def) => {
1052 match type_def.module_def {
1053 None => {
1054 let msg = format!("Not a module `{}`",
1055 token::get_name(name));
1056
1057 return Failed(Some((span, msg)));
1058 }
1059 Some(ref module_def) => {
1060 search_module = module_def.clone();
1061
1062 // track extern crates for unused_extern_crate lint
1063 if let Some(did) = module_def.def_id.get() {
1064 self.used_crates.insert(did.krate);
1065 }
1066
1067 // Keep track of the closest
1068 // private module used when
1069 // resolving this import chain.
1070 if !used_proxy && !search_module.is_public {
1071 if let Some(did) = search_module.def_id.get() {
1072 closest_private = LastMod(DependsOn(did));
1073 }
1074 }
1075 }
1076 }
1077 }
1078 None => {
1079 // There are no type bindings at all.
1080 let msg = format!("Not a module `{}`",
1081 token::get_name(name));
1082 return Failed(Some((span, msg)));
1083 }
1084 }
1085 }
1086 }
1087
1088 index += 1;
1089 }
1090
1091 return Success((search_module, closest_private));
1092 }
1093
1094 /// Attempts to resolve the module part of an import directive or path
1095 /// rooted at the given module.
1096 ///
1097 /// On success, returns the resolved module, and the closest *private*
1098 /// module found to the destination when resolving this path.
1099 fn resolve_module_path(&mut self,
1100 module_: Rc<Module>,
1101 module_path: &[Name],
1102 use_lexical_scope: UseLexicalScopeFlag,
1103 span: Span,
1104 name_search_type: NameSearchType)
1105 -> ResolveResult<(Rc<Module>, LastPrivate)> {
1106 let module_path_len = module_path.len();
1107 assert!(module_path_len > 0);
1108
1109 debug!("(resolving module path for import) processing `{}` rooted at `{}`",
1110 names_to_string(module_path),
1111 module_to_string(&*module_));
1112
1113 // Resolve the module prefix, if any.
1114 let module_prefix_result = self.resolve_module_prefix(module_.clone(),
1115 module_path);
1116
1117 let search_module;
1118 let start_index;
1119 let last_private;
1120 match module_prefix_result {
1121 Failed(None) => {
1122 let mpath = names_to_string(module_path);
1123 let mpath = &mpath[..];
1124 match mpath.rfind(':') {
1125 Some(idx) => {
1126 let msg = format!("Could not find `{}` in `{}`",
1127 // idx +- 1 to account for the
1128 // colons on either side
1129 &mpath[idx + 1..],
1130 &mpath[..idx - 1]);
1131 return Failed(Some((span, msg)));
1132 },
1133 None => {
1134 return Failed(None)
1135 }
1136 }
1137 }
1138 Failed(err) => return Failed(err),
1139 Indeterminate => {
1140 debug!("(resolving module path for import) indeterminate; \
1141 bailing");
1142 return Indeterminate;
1143 }
1144 Success(NoPrefixFound) => {
1145 // There was no prefix, so we're considering the first element
1146 // of the path. How we handle this depends on whether we were
1147 // instructed to use lexical scope or not.
1148 match use_lexical_scope {
1149 DontUseLexicalScope => {
1150 // This is a crate-relative path. We will start the
1151 // resolution process at index zero.
1152 search_module = self.graph_root.get_module();
1153 start_index = 0;
1154 last_private = LastMod(AllPublic);
1155 }
1156 UseLexicalScope => {
1157 // This is not a crate-relative path. We resolve the
1158 // first component of the path in the current lexical
1159 // scope and then proceed to resolve below that.
1160 match self.resolve_module_in_lexical_scope(module_,
1161 module_path[0]) {
1162 Failed(err) => return Failed(err),
1163 Indeterminate => {
1164 debug!("(resolving module path for import) \
1165 indeterminate; bailing");
1166 return Indeterminate;
1167 }
1168 Success(containing_module) => {
1169 search_module = containing_module;
1170 start_index = 1;
1171 last_private = LastMod(AllPublic);
1172 }
1173 }
1174 }
1175 }
1176 }
1177 Success(PrefixFound(ref containing_module, index)) => {
1178 search_module = containing_module.clone();
1179 start_index = index;
1180 last_private = LastMod(DependsOn(containing_module.def_id
1181 .get()
1182 .unwrap()));
1183 }
1184 }
1185
1186 self.resolve_module_path_from_root(search_module,
1187 module_path,
1188 start_index,
1189 span,
1190 name_search_type,
1191 last_private)
1192 }
1193
1194 /// Invariant: This must only be called during main resolution, not during
1195 /// import resolution.
1196 fn resolve_item_in_lexical_scope(&mut self,
1197 module_: Rc<Module>,
1198 name: Name,
1199 namespace: Namespace)
1200 -> ResolveResult<(Target, bool)> {
1201 debug!("(resolving item in lexical scope) resolving `{}` in \
1202 namespace {:?} in `{}`",
1203 token::get_name(name),
1204 namespace,
1205 module_to_string(&*module_));
1206
1207 // The current module node is handled specially. First, check for
1208 // its immediate children.
1209 build_reduced_graph::populate_module_if_necessary(self, &module_);
1210
1211 match module_.children.borrow().get(&name) {
1212 Some(name_bindings)
1213 if name_bindings.defined_in_namespace(namespace) => {
1214 debug!("top name bindings succeeded");
1215 return Success((Target::new(module_.clone(),
1216 name_bindings.clone(),
1217 Shadowable::Never),
1218 false));
1219 }
1220 Some(_) | None => { /* Not found; continue. */ }
1221 }
1222
1223 // Now check for its import directives. We don't have to have resolved
1224 // all its imports in the usual way; this is because chains of
1225 // adjacent import statements are processed as though they mutated the
1226 // current scope.
1227 if let Some(import_resolution) = module_.import_resolutions.borrow().get(&name) {
1228 match (*import_resolution).target_for_namespace(namespace) {
1229 None => {
1230 // Not found; continue.
1231 debug!("(resolving item in lexical scope) found \
1232 import resolution, but not in namespace {:?}",
1233 namespace);
1234 }
1235 Some(target) => {
1236 debug!("(resolving item in lexical scope) using \
1237 import resolution");
1238 // track used imports and extern crates as well
1239 let id = import_resolution.id(namespace);
1240 self.used_imports.insert((id, namespace));
1241 self.record_import_use(id, name);
1242 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1243 self.used_crates.insert(kid);
1244 }
1245 return Success((target, false));
1246 }
1247 }
1248 }
1249
1250 // Search for external modules.
1251 if namespace == TypeNS {
1252 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1253 let child = module_.external_module_children.borrow().get(&name).cloned();
1254 if let Some(module) = child {
1255 let name_bindings =
1256 Rc::new(Resolver::create_name_bindings_from_module(module));
1257 debug!("lower name bindings succeeded");
1258 return Success((Target::new(module_,
1259 name_bindings,
1260 Shadowable::Never),
1261 false));
1262 }
1263 }
1264
1265 // Finally, proceed up the scope chain looking for parent modules.
1266 let mut search_module = module_;
1267 loop {
1268 // Go to the next parent.
1269 match search_module.parent_link.clone() {
1270 NoParentLink => {
1271 // No more parents. This module was unresolved.
1272 debug!("(resolving item in lexical scope) unresolved \
1273 module");
1274 return Failed(None);
1275 }
1276 ModuleParentLink(parent_module_node, _) => {
1277 match search_module.kind.get() {
1278 NormalModuleKind => {
1279 // We stop the search here.
1280 debug!("(resolving item in lexical \
1281 scope) unresolved module: not \
1282 searching through module \
1283 parents");
1284 return Failed(None);
1285 }
1286 TraitModuleKind |
1287 EnumModuleKind |
1288 TypeModuleKind |
1289 AnonymousModuleKind => {
1290 search_module = parent_module_node.upgrade().unwrap();
1291 }
1292 }
1293 }
1294 BlockParentLink(ref parent_module_node, _) => {
1295 search_module = parent_module_node.upgrade().unwrap();
1296 }
1297 }
1298
1299 // Resolve the name in the parent module.
1300 match self.resolve_name_in_module(search_module.clone(),
1301 name,
1302 namespace,
1303 PathSearch,
1304 true) {
1305 Failed(Some((span, msg))) =>
1306 self.resolve_error(span, &format!("failed to resolve. {}",
1307 msg)),
1308 Failed(None) => (), // Continue up the search chain.
1309 Indeterminate => {
1310 // We couldn't see through the higher scope because of an
1311 // unresolved import higher up. Bail.
1312
1313 debug!("(resolving item in lexical scope) indeterminate \
1314 higher scope; bailing");
1315 return Indeterminate;
1316 }
1317 Success((target, used_reexport)) => {
1318 // We found the module.
1319 debug!("(resolving item in lexical scope) found name \
1320 in module, done");
1321 return Success((target, used_reexport));
1322 }
1323 }
1324 }
1325 }
1326
1327 /// Resolves a module name in the current lexical scope.
1328 fn resolve_module_in_lexical_scope(&mut self,
1329 module_: Rc<Module>,
1330 name: Name)
1331 -> ResolveResult<Rc<Module>> {
1332 // If this module is an anonymous module, resolve the item in the
1333 // lexical scope. Otherwise, resolve the item from the crate root.
1334 let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
1335 match resolve_result {
1336 Success((target, _)) => {
1337 let bindings = &*target.bindings;
1338 match *bindings.type_def.borrow() {
1339 Some(ref type_def) => {
1340 match type_def.module_def {
1341 None => {
1342 debug!("!!! (resolving module in lexical \
1343 scope) module wasn't actually a \
1344 module!");
1345 return Failed(None);
1346 }
1347 Some(ref module_def) => {
1348 return Success(module_def.clone());
1349 }
1350 }
1351 }
1352 None => {
1353 debug!("!!! (resolving module in lexical scope) module
1354 wasn't actually a module!");
1355 return Failed(None);
1356 }
1357 }
1358 }
1359 Indeterminate => {
1360 debug!("(resolving module in lexical scope) indeterminate; \
1361 bailing");
1362 return Indeterminate;
1363 }
1364 Failed(err) => {
1365 debug!("(resolving module in lexical scope) failed to resolve");
1366 return Failed(err);
1367 }
1368 }
1369 }
1370
1371 /// Returns the nearest normal module parent of the given module.
1372 fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
1373 -> Option<Rc<Module>> {
1374 let mut module_ = module_;
1375 loop {
1376 match module_.parent_link.clone() {
1377 NoParentLink => return None,
1378 ModuleParentLink(new_module, _) |
1379 BlockParentLink(new_module, _) => {
1380 let new_module = new_module.upgrade().unwrap();
1381 match new_module.kind.get() {
1382 NormalModuleKind => return Some(new_module),
1383 TraitModuleKind |
1384 EnumModuleKind |
1385 TypeModuleKind |
1386 AnonymousModuleKind => module_ = new_module,
1387 }
1388 }
1389 }
1390 }
1391 }
1392
1393 /// Returns the nearest normal module parent of the given module, or the
1394 /// module itself if it is a normal module.
1395 fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
1396 -> Rc<Module> {
1397 match module_.kind.get() {
1398 NormalModuleKind => return module_,
1399 TraitModuleKind |
1400 EnumModuleKind |
1401 TypeModuleKind |
1402 AnonymousModuleKind => {
1403 match self.get_nearest_normal_module_parent(module_.clone()) {
1404 None => module_,
1405 Some(new_module) => new_module
1406 }
1407 }
1408 }
1409 }
1410
1411 /// Resolves a "module prefix". A module prefix is one or both of (a) `self::`;
1412 /// (b) some chain of `super::`.
1413 /// grammar: (SELF MOD_SEP ) ? (SUPER MOD_SEP) *
1414 fn resolve_module_prefix(&mut self,
1415 module_: Rc<Module>,
1416 module_path: &[Name])
1417 -> ResolveResult<ModulePrefixResult> {
1418 // Start at the current module if we see `self` or `super`, or at the
1419 // top of the crate otherwise.
1420 let mut containing_module;
1421 let mut i;
1422 let first_module_path_string = token::get_name(module_path[0]);
1423 if "self" == &first_module_path_string[..] {
1424 containing_module =
1425 self.get_nearest_normal_module_parent_or_self(module_);
1426 i = 1;
1427 } else if "super" == &first_module_path_string[..] {
1428 containing_module =
1429 self.get_nearest_normal_module_parent_or_self(module_);
1430 i = 0; // We'll handle `super` below.
1431 } else {
1432 return Success(NoPrefixFound);
1433 }
1434
1435 // Now loop through all the `super`s we find.
1436 while i < module_path.len() {
1437 let string = token::get_name(module_path[i]);
1438 if "super" != &string[..] {
1439 break
1440 }
1441 debug!("(resolving module prefix) resolving `super` at {}",
1442 module_to_string(&*containing_module));
1443 match self.get_nearest_normal_module_parent(containing_module) {
1444 None => return Failed(None),
1445 Some(new_module) => {
1446 containing_module = new_module;
1447 i += 1;
1448 }
1449 }
1450 }
1451
1452 debug!("(resolving module prefix) finished resolving prefix at {}",
1453 module_to_string(&*containing_module));
1454
1455 return Success(PrefixFound(containing_module, i));
1456 }
1457
1458 /// Attempts to resolve the supplied name in the given module for the
1459 /// given namespace. If successful, returns the target corresponding to
1460 /// the name.
1461 ///
1462 /// The boolean returned on success is an indicator of whether this lookup
1463 /// passed through a public re-export proxy.
1464 fn resolve_name_in_module(&mut self,
1465 module_: Rc<Module>,
1466 name: Name,
1467 namespace: Namespace,
1468 name_search_type: NameSearchType,
1469 allow_private_imports: bool)
1470 -> ResolveResult<(Target, bool)> {
1471 debug!("(resolving name in module) resolving `{}` in `{}`",
1472 &token::get_name(name),
1473 module_to_string(&*module_));
1474
1475 // First, check the direct children of the module.
1476 build_reduced_graph::populate_module_if_necessary(self, &module_);
1477
1478 match module_.children.borrow().get(&name) {
1479 Some(name_bindings)
1480 if name_bindings.defined_in_namespace(namespace) => {
1481 debug!("(resolving name in module) found node as child");
1482 return Success((Target::new(module_.clone(),
1483 name_bindings.clone(),
1484 Shadowable::Never),
1485 false));
1486 }
1487 Some(_) | None => {
1488 // Continue.
1489 }
1490 }
1491
1492 // Next, check the module's imports if necessary.
1493
1494 // If this is a search of all imports, we should be done with glob
1495 // resolution at this point.
1496 if name_search_type == PathSearch {
1497 assert_eq!(module_.glob_count.get(), 0);
1498 }
1499
1500 // Check the list of resolved imports.
1501 match module_.import_resolutions.borrow().get(&name) {
1502 Some(import_resolution) if allow_private_imports ||
1503 import_resolution.is_public => {
1504
1505 if import_resolution.is_public &&
1506 import_resolution.outstanding_references != 0 {
1507 debug!("(resolving name in module) import \
1508 unresolved; bailing out");
1509 return Indeterminate;
1510 }
1511 match import_resolution.target_for_namespace(namespace) {
1512 None => {
1513 debug!("(resolving name in module) name found, \
1514 but not in namespace {:?}",
1515 namespace);
1516 }
1517 Some(target) => {
1518 debug!("(resolving name in module) resolved to \
1519 import");
1520 // track used imports and extern crates as well
1521 let id = import_resolution.id(namespace);
1522 self.used_imports.insert((id, namespace));
1523 self.record_import_use(id, name);
1524 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
1525 self.used_crates.insert(kid);
1526 }
1527 return Success((target, true));
1528 }
1529 }
1530 }
1531 Some(..) | None => {} // Continue.
1532 }
1533
1534 // Finally, search through external children.
1535 if namespace == TypeNS {
1536 // FIXME (21114): In principle unclear `child` *has* to be lifted.
1537 let child = module_.external_module_children.borrow().get(&name).cloned();
1538 if let Some(module) = child {
1539 let name_bindings =
1540 Rc::new(Resolver::create_name_bindings_from_module(module));
1541 return Success((Target::new(module_,
1542 name_bindings,
1543 Shadowable::Never),
1544 false));
1545 }
1546 }
1547
1548 // We're out of luck.
1549 debug!("(resolving name in module) failed to resolve `{}`",
1550 &token::get_name(name));
1551 return Failed(None);
1552 }
1553
1554 fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
1555 let index = module_.resolved_import_count.get();
1556 let imports = module_.imports.borrow();
1557 let import_count = imports.len();
1558 if index != import_count {
1559 let sn = self.session
1560 .codemap()
1561 .span_to_snippet((*imports)[index].span)
1562 .unwrap();
1563 if sn.contains("::") {
1564 self.resolve_error((*imports)[index].span,
1565 "unresolved import");
1566 } else {
1567 let err = format!("unresolved import (maybe you meant `{}::*`?)",
1568 sn);
1569 self.resolve_error((*imports)[index].span, &err[..]);
1570 }
1571 }
1572
1573 // Descend into children and anonymous children.
1574 build_reduced_graph::populate_module_if_necessary(self, &module_);
1575
1576 for (_, child_node) in module_.children.borrow().iter() {
1577 match child_node.get_module_if_available() {
1578 None => {
1579 // Continue.
1580 }
1581 Some(child_module) => {
1582 self.report_unresolved_imports(child_module);
1583 }
1584 }
1585 }
1586
1587 for (_, module_) in module_.anonymous_children.borrow().iter() {
1588 self.report_unresolved_imports(module_.clone());
1589 }
1590 }
1591
1592 // AST resolution
1593 //
1594 // We maintain a list of value ribs and type ribs.
1595 //
1596 // Simultaneously, we keep track of the current position in the module
1597 // graph in the `current_module` pointer. When we go to resolve a name in
1598 // the value or type namespaces, we first look through all the ribs and
1599 // then query the module graph. When we resolve a name in the module
1600 // namespace, we can skip all the ribs (since nested modules are not
1601 // allowed within blocks in Rust) and jump straight to the current module
1602 // graph node.
1603 //
1604 // Named implementations are handled separately. When we find a method
1605 // call, we consult the module node to find all of the implementations in
1606 // scope. This information is lazily cached in the module node. We then
1607 // generate a fake "implementation scope" containing all the
1608 // implementations thus found, for compatibility with old resolve pass.
1609
1610 fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
1611 F: FnOnce(&mut Resolver),
1612 {
1613 let orig_module = self.current_module.clone();
1614
1615 // Move down in the graph.
1616 match name {
1617 None => {
1618 // Nothing to do.
1619 }
1620 Some(name) => {
1621 build_reduced_graph::populate_module_if_necessary(self, &orig_module);
1622
1623 match orig_module.children.borrow().get(&name) {
1624 None => {
1625 debug!("!!! (with scope) didn't find `{}` in `{}`",
1626 token::get_name(name),
1627 module_to_string(&*orig_module));
1628 }
1629 Some(name_bindings) => {
1630 match (*name_bindings).get_module_if_available() {
1631 None => {
1632 debug!("!!! (with scope) didn't find module \
1633 for `{}` in `{}`",
1634 token::get_name(name),
1635 module_to_string(&*orig_module));
1636 }
1637 Some(module_) => {
1638 self.current_module = module_;
1639 }
1640 }
1641 }
1642 }
1643 }
1644 }
1645
1646 f(self);
1647
1648 self.current_module = orig_module;
1649 }
1650
1651 /// Wraps the given definition in the appropriate number of `DefUpvar`
1652 /// wrappers.
1653 fn upvarify(&self,
1654 ribs: &[Rib],
1655 def_like: DefLike,
1656 span: Span)
1657 -> Option<DefLike> {
1658 let mut def = match def_like {
1659 DlDef(def) => def,
1660 _ => return Some(def_like)
1661 };
1662 match def {
1663 DefUpvar(..) => {
1664 self.session.span_bug(span,
1665 &format!("unexpected {:?} in bindings", def))
1666 }
1667 DefLocal(node_id) => {
1668 for rib in ribs {
1669 match rib.kind {
1670 NormalRibKind => {
1671 // Nothing to do. Continue.
1672 }
1673 ClosureRibKind(function_id) => {
1674 let prev_def = def;
1675 def = DefUpvar(node_id, function_id);
1676
1677 let mut seen = self.freevars_seen.borrow_mut();
1678 let seen = match seen.entry(function_id) {
1679 Occupied(v) => v.into_mut(),
1680 Vacant(v) => v.insert(NodeSet()),
1681 };
1682 if seen.contains(&node_id) {
1683 continue;
1684 }
1685 match self.freevars.borrow_mut().entry(function_id) {
1686 Occupied(v) => v.into_mut(),
1687 Vacant(v) => v.insert(vec![]),
1688 }.push(Freevar { def: prev_def, span: span });
1689 seen.insert(node_id);
1690 }
1691 ItemRibKind | MethodRibKind => {
1692 // This was an attempt to access an upvar inside a
1693 // named function item. This is not allowed, so we
1694 // report an error.
1695
1696 self.resolve_error(span,
1697 "can't capture dynamic environment in a fn item; \
1698 use the || { ... } closure form instead");
1699 return None;
1700 }
1701 ConstantItemRibKind => {
1702 // Still doesn't deal with upvars
1703 self.resolve_error(span,
1704 "attempt to use a non-constant \
1705 value in a constant");
1706 return None;
1707 }
1708 }
1709 }
1710 }
1711 DefTyParam(..) | DefSelfTy(..) => {
1712 for rib in ribs {
1713 match rib.kind {
1714 NormalRibKind | MethodRibKind | ClosureRibKind(..) => {
1715 // Nothing to do. Continue.
1716 }
1717 ItemRibKind => {
1718 // This was an attempt to use a type parameter outside
1719 // its scope.
1720
1721 self.resolve_error(span,
1722 "can't use type parameters from \
1723 outer function; try using a local \
1724 type parameter instead");
1725 return None;
1726 }
1727 ConstantItemRibKind => {
1728 // see #9186
1729 self.resolve_error(span,
1730 "cannot use an outer type \
1731 parameter in this context");
1732 return None;
1733 }
1734 }
1735 }
1736 }
1737 _ => {}
1738 }
1739 Some(DlDef(def))
1740 }
1741
1742 /// Searches the current set of local scopes and
1743 /// applies translations for closures.
1744 fn search_ribs(&self,
1745 ribs: &[Rib],
1746 name: Name,
1747 span: Span)
1748 -> Option<DefLike> {
1749 // FIXME #4950: Try caching?
1750
1751 for (i, rib) in ribs.iter().enumerate().rev() {
1752 if let Some(def_like) = rib.bindings.get(&name).cloned() {
1753 return self.upvarify(&ribs[i + 1..], def_like, span);
1754 }
1755 }
1756
1757 None
1758 }
1759
1760 /// Searches the current set of local scopes for labels.
1761 /// Stops after meeting a closure.
1762 fn search_label(&self, name: Name) -> Option<DefLike> {
1763 for rib in self.label_ribs.iter().rev() {
1764 match rib.kind {
1765 NormalRibKind => {
1766 // Continue
1767 }
1768 _ => {
1769 // Do not resolve labels across function boundary
1770 return None
1771 }
1772 }
1773 let result = rib.bindings.get(&name).cloned();
1774 if result.is_some() {
1775 return result
1776 }
1777 }
1778 None
1779 }
1780
1781 fn resolve_crate(&mut self, krate: &ast::Crate) {
1782 debug!("(resolving crate) starting");
1783
1784 visit::walk_crate(self, krate);
1785 }
1786
1787 fn check_if_primitive_type_name(&self, name: Name, span: Span) {
1788 if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
1789 span_err!(self.session, span, E0317,
1790 "user-defined types or type parameters cannot shadow the primitive types");
1791 }
1792 }
1793
1794 fn resolve_item(&mut self, item: &Item) {
1795 let name = item.ident.name;
1796
1797 debug!("(resolving item) resolving {}",
1798 token::get_name(name));
1799
1800 match item.node {
1801 ItemEnum(_, ref generics) |
1802 ItemTy(_, ref generics) |
1803 ItemStruct(_, ref generics) => {
1804 self.check_if_primitive_type_name(name, item.span);
1805
1806 self.with_type_parameter_rib(HasTypeParameters(generics,
1807 TypeSpace,
1808 ItemRibKind),
1809 |this| visit::walk_item(this, item));
1810 }
1811 ItemFn(_, _, _, _, ref generics, _) => {
1812 self.with_type_parameter_rib(HasTypeParameters(generics,
1813 FnSpace,
1814 ItemRibKind),
1815 |this| visit::walk_item(this, item));
1816 }
1817
1818 ItemDefaultImpl(_, ref trait_ref) => {
1819 self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
1820 }
1821 ItemImpl(_,
1822 _,
1823 ref generics,
1824 ref opt_trait_ref,
1825 ref self_type,
1826 ref impl_items) => {
1827 self.resolve_implementation(generics,
1828 opt_trait_ref,
1829 &**self_type,
1830 item.id,
1831 &impl_items[..]);
1832 }
1833
1834 ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
1835 self.check_if_primitive_type_name(name, item.span);
1836
1837 // Create a new rib for the trait-wide type parameters.
1838 self.with_type_parameter_rib(HasTypeParameters(generics,
1839 TypeSpace,
1840 ItemRibKind),
1841 |this| {
1842 this.with_self_rib(DefSelfTy(Some(local_def(item.id)), None), |this| {
1843 this.visit_generics(generics);
1844 visit::walk_ty_param_bounds_helper(this, bounds);
1845
1846 for trait_item in trait_items {
1847 // Create a new rib for the trait_item-specific type
1848 // parameters.
1849 //
1850 // FIXME #4951: Do we need a node ID here?
1851
1852 match trait_item.node {
1853 ast::ConstTraitItem(_, ref default) => {
1854 // Only impose the restrictions of
1855 // ConstRibKind if there's an actual constant
1856 // expression in a provided default.
1857 if default.is_some() {
1858 this.with_constant_rib(|this| {
1859 visit::walk_trait_item(this, trait_item)
1860 });
1861 } else {
1862 visit::walk_trait_item(this, trait_item)
1863 }
1864 }
1865 ast::MethodTraitItem(ref sig, _) => {
1866 let type_parameters =
1867 HasTypeParameters(&sig.generics,
1868 FnSpace,
1869 MethodRibKind);
1870 this.with_type_parameter_rib(type_parameters, |this| {
1871 visit::walk_trait_item(this, trait_item)
1872 });
1873 }
1874 ast::TypeTraitItem(..) => {
1875 this.check_if_primitive_type_name(trait_item.ident.name,
1876 trait_item.span);
1877 this.with_type_parameter_rib(NoTypeParameters, |this| {
1878 visit::walk_trait_item(this, trait_item)
1879 });
1880 }
1881 };
1882 }
1883 });
1884 });
1885 }
1886
1887 ItemMod(_) | ItemForeignMod(_) => {
1888 self.with_scope(Some(name), |this| {
1889 visit::walk_item(this, item);
1890 });
1891 }
1892
1893 ItemConst(..) | ItemStatic(..) => {
1894 self.with_constant_rib(|this| {
1895 visit::walk_item(this, item);
1896 });
1897 }
1898
1899 ItemUse(ref view_path) => {
1900 // check for imports shadowing primitive types
1901 if let ast::ViewPathSimple(ident, _) = view_path.node {
1902 match self.def_map.borrow().get(&item.id).map(|d| d.full_def()) {
1903 Some(DefTy(..)) | Some(DefStruct(..)) | Some(DefTrait(..)) | None => {
1904 self.check_if_primitive_type_name(ident.name, item.span);
1905 }
1906 _ => {}
1907 }
1908 }
1909 }
1910
1911 ItemExternCrate(_) | ItemMac(..) => {
1912 // do nothing, these are just around to be encoded
1913 }
1914 }
1915 }
1916
1917 fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
1918 F: FnOnce(&mut Resolver),
1919 {
1920 match type_parameters {
1921 HasTypeParameters(generics, space, rib_kind) => {
1922 let mut function_type_rib = Rib::new(rib_kind);
1923 let mut seen_bindings = HashSet::new();
1924 for (index, type_parameter) in generics.ty_params.iter().enumerate() {
1925 let name = type_parameter.ident.name;
1926 debug!("with_type_parameter_rib: {}", type_parameter.id);
1927
1928 if seen_bindings.contains(&name) {
1929 self.resolve_error(type_parameter.span,
1930 &format!("the name `{}` is already \
1931 used for a type \
1932 parameter in this type \
1933 parameter list",
1934 token::get_name(name)))
1935 }
1936 seen_bindings.insert(name);
1937
1938 // plain insert (no renaming)
1939 function_type_rib.bindings.insert(name,
1940 DlDef(DefTyParam(space,
1941 index as u32,
1942 local_def(type_parameter.id),
1943 name)));
1944 }
1945 self.type_ribs.push(function_type_rib);
1946 }
1947
1948 NoTypeParameters => {
1949 // Nothing to do.
1950 }
1951 }
1952
1953 f(self);
1954
1955 match type_parameters {
1956 HasTypeParameters(..) => { self.type_ribs.pop(); }
1957 NoTypeParameters => { }
1958 }
1959 }
1960
1961 fn with_label_rib<F>(&mut self, f: F) where
1962 F: FnOnce(&mut Resolver),
1963 {
1964 self.label_ribs.push(Rib::new(NormalRibKind));
1965 f(self);
1966 self.label_ribs.pop();
1967 }
1968
1969 fn with_constant_rib<F>(&mut self, f: F) where
1970 F: FnOnce(&mut Resolver),
1971 {
1972 self.value_ribs.push(Rib::new(ConstantItemRibKind));
1973 self.type_ribs.push(Rib::new(ConstantItemRibKind));
1974 f(self);
1975 self.type_ribs.pop();
1976 self.value_ribs.pop();
1977 }
1978
1979 fn resolve_function(&mut self,
1980 rib_kind: RibKind,
1981 declaration: &FnDecl,
1982 block: &Block) {
1983 // Create a value rib for the function.
1984 self.value_ribs.push(Rib::new(rib_kind));
1985
1986 // Create a label rib for the function.
1987 self.label_ribs.push(Rib::new(rib_kind));
1988
1989 // Add each argument to the rib.
1990 let mut bindings_list = HashMap::new();
1991 for argument in &declaration.inputs {
1992 self.resolve_pattern(&*argument.pat,
1993 ArgumentIrrefutableMode,
1994 &mut bindings_list);
1995
1996 self.visit_ty(&*argument.ty);
1997
1998 debug!("(resolving function) recorded argument");
1999 }
2000 visit::walk_fn_ret_ty(self, &declaration.output);
2001
2002 // Resolve the function body.
2003 self.visit_block(&*block);
2004
2005 debug!("(resolving function) leaving function");
2006
2007 self.label_ribs.pop();
2008 self.value_ribs.pop();
2009 }
2010
2011 fn resolve_trait_reference(&mut self,
2012 id: NodeId,
2013 trait_path: &Path,
2014 path_depth: usize)
2015 -> Result<PathResolution, ()> {
2016 if let Some(path_res) = self.resolve_path(id, trait_path, path_depth, TypeNS, true) {
2017 if let DefTrait(_) = path_res.base_def {
2018 debug!("(resolving trait) found trait def: {:?}", path_res);
2019 Ok(path_res)
2020 } else {
2021 self.resolve_error(trait_path.span,
2022 &format!("`{}` is not a trait",
2023 path_names_to_string(trait_path, path_depth)));
2024
2025 // If it's a typedef, give a note
2026 if let DefTy(..) = path_res.base_def {
2027 self.session.span_note(trait_path.span,
2028 "`type` aliases cannot be used for traits");
2029 }
2030 Err(())
2031 }
2032 } else {
2033 let msg = format!("use of undeclared trait name `{}`",
2034 path_names_to_string(trait_path, path_depth));
2035 self.resolve_error(trait_path.span, &msg);
2036 Err(())
2037 }
2038 }
2039
2040 fn resolve_generics(&mut self, generics: &Generics) {
2041 for type_parameter in generics.ty_params.iter() {
2042 self.check_if_primitive_type_name(type_parameter.ident.name, type_parameter.span);
2043 }
2044 for predicate in &generics.where_clause.predicates {
2045 match predicate {
2046 &ast::WherePredicate::BoundPredicate(_) |
2047 &ast::WherePredicate::RegionPredicate(_) => {}
2048 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
2049 let path_res = self.resolve_path(eq_pred.id, &eq_pred.path, 0, TypeNS, true);
2050 if let Some(PathResolution { base_def: DefTyParam(..), .. }) = path_res {
2051 self.record_def(eq_pred.id, path_res.unwrap());
2052 } else {
2053 self.resolve_error(eq_pred.path.span, "undeclared associated type");
2054 }
2055 }
2056 }
2057 }
2058 visit::walk_generics(self, generics);
2059 }
2060
2061 fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
2062 where F: FnOnce(&mut Resolver) -> T
2063 {
2064 // Handle nested impls (inside fn bodies)
2065 let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
2066 let result = f(self);
2067 self.current_self_type = previous_value;
2068 result
2069 }
2070
2071 fn with_optional_trait_ref<T, F>(&mut self,
2072 opt_trait_ref: Option<&TraitRef>,
2073 f: F)
2074 -> T
2075 where F: FnOnce(&mut Resolver, Option<DefId>) -> T
2076 {
2077 let mut new_val = None;
2078 let mut new_id = None;
2079 if let Some(trait_ref) = opt_trait_ref {
2080 if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
2081 &trait_ref.path, 0) {
2082 assert!(path_res.depth == 0);
2083 self.record_def(trait_ref.ref_id, path_res);
2084 new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
2085 new_id = Some(path_res.base_def.def_id());
2086 }
2087 visit::walk_trait_ref(self, trait_ref);
2088 }
2089 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2090 let result = f(self, new_id);
2091 self.current_trait_ref = original_trait_ref;
2092 result
2093 }
2094
2095 fn with_self_rib<F>(&mut self, self_def: Def, f: F)
2096 where F: FnOnce(&mut Resolver)
2097 {
2098 let mut self_type_rib = Rib::new(NormalRibKind);
2099
2100 // plain insert (no renaming, types are not currently hygienic....)
2101 let name = special_names::type_self;
2102 self_type_rib.bindings.insert(name, DlDef(self_def));
2103 self.type_ribs.push(self_type_rib);
2104 f(self);
2105 self.type_ribs.pop();
2106 }
2107
2108 fn resolve_implementation(&mut self,
2109 generics: &Generics,
2110 opt_trait_reference: &Option<TraitRef>,
2111 self_type: &Ty,
2112 item_id: NodeId,
2113 impl_items: &[P<ImplItem>]) {
2114 // If applicable, create a rib for the type parameters.
2115 self.with_type_parameter_rib(HasTypeParameters(generics,
2116 TypeSpace,
2117 ItemRibKind),
2118 |this| {
2119 // Resolve the type parameters.
2120 this.visit_generics(generics);
2121
2122 // Resolve the trait reference, if necessary.
2123 this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| {
2124 // Resolve the self type.
2125 this.visit_ty(self_type);
2126
2127 this.with_self_rib(DefSelfTy(trait_id, Some((item_id, self_type.id))), |this| {
2128 this.with_current_self_type(self_type, |this| {
2129 for impl_item in impl_items {
2130 match impl_item.node {
2131 ConstImplItem(..) => {
2132 // If this is a trait impl, ensure the method
2133 // exists in trait
2134 this.check_trait_item(impl_item.ident.name,
2135 impl_item.span);
2136 this.with_constant_rib(|this| {
2137 visit::walk_impl_item(this, impl_item);
2138 });
2139 }
2140 MethodImplItem(ref sig, _) => {
2141 // If this is a trait impl, ensure the method
2142 // exists in trait
2143 this.check_trait_item(impl_item.ident.name,
2144 impl_item.span);
2145
2146 // We also need a new scope for the method-
2147 // specific type parameters.
2148 let type_parameters =
2149 HasTypeParameters(&sig.generics,
2150 FnSpace,
2151 MethodRibKind);
2152 this.with_type_parameter_rib(type_parameters, |this| {
2153 visit::walk_impl_item(this, impl_item);
2154 });
2155 }
2156 TypeImplItem(ref ty) => {
2157 // If this is a trait impl, ensure the method
2158 // exists in trait
2159 this.check_trait_item(impl_item.ident.name,
2160 impl_item.span);
2161
2162 this.visit_ty(ty);
2163 }
2164 ast::MacImplItem(_) => {}
2165 }
2166 }
2167 });
2168 });
2169 });
2170 });
2171 }
2172
2173 fn check_trait_item(&self, name: Name, span: Span) {
2174 // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2175 if let Some((did, ref trait_ref)) = self.current_trait_ref {
2176 if !self.trait_item_map.contains_key(&(name, did)) {
2177 let path_str = path_names_to_string(&trait_ref.path, 0);
2178 self.resolve_error(span,
2179 &format!("method `{}` is not a member of trait `{}`",
2180 token::get_name(name),
2181 path_str));
2182 }
2183 }
2184 }
2185
2186 fn resolve_local(&mut self, local: &Local) {
2187 // Resolve the type.
2188 visit::walk_ty_opt(self, &local.ty);
2189
2190 // Resolve the initializer.
2191 visit::walk_expr_opt(self, &local.init);
2192
2193 // Resolve the pattern.
2194 self.resolve_pattern(&*local.pat,
2195 LocalIrrefutableMode,
2196 &mut HashMap::new());
2197 }
2198
2199 // build a map from pattern identifiers to binding-info's.
2200 // this is done hygienically. This could arise for a macro
2201 // that expands into an or-pattern where one 'x' was from the
2202 // user and one 'x' came from the macro.
2203 fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2204 let mut result = HashMap::new();
2205 pat_bindings(&self.def_map, pat, |binding_mode, _id, sp, path1| {
2206 let name = mtwt::resolve(path1.node);
2207 result.insert(name, BindingInfo {
2208 span: sp,
2209 binding_mode: binding_mode
2210 });
2211 });
2212 return result;
2213 }
2214
2215 // check that all of the arms in an or-pattern have exactly the
2216 // same set of bindings, with the same binding modes for each.
2217 fn check_consistent_bindings(&mut self, arm: &Arm) {
2218 if arm.pats.is_empty() {
2219 return
2220 }
2221 let map_0 = self.binding_mode_map(&*arm.pats[0]);
2222 for (i, p) in arm.pats.iter().enumerate() {
2223 let map_i = self.binding_mode_map(&**p);
2224
2225 for (&key, &binding_0) in &map_0 {
2226 match map_i.get(&key) {
2227 None => {
2228 self.resolve_error(
2229 p.span,
2230 &format!("variable `{}` from pattern #1 is \
2231 not bound in pattern #{}",
2232 token::get_name(key),
2233 i + 1));
2234 }
2235 Some(binding_i) => {
2236 if binding_0.binding_mode != binding_i.binding_mode {
2237 self.resolve_error(
2238 binding_i.span,
2239 &format!("variable `{}` is bound with different \
2240 mode in pattern #{} than in pattern #1",
2241 token::get_name(key),
2242 i + 1));
2243 }
2244 }
2245 }
2246 }
2247
2248 for (&key, &binding) in &map_i {
2249 if !map_0.contains_key(&key) {
2250 self.resolve_error(
2251 binding.span,
2252 &format!("variable `{}` from pattern {}{} is \
2253 not bound in pattern {}1",
2254 token::get_name(key),
2255 "#", i + 1, "#"));
2256 }
2257 }
2258 }
2259 }
2260
2261 fn resolve_arm(&mut self, arm: &Arm) {
2262 self.value_ribs.push(Rib::new(NormalRibKind));
2263
2264 let mut bindings_list = HashMap::new();
2265 for pattern in &arm.pats {
2266 self.resolve_pattern(&**pattern, RefutableMode, &mut bindings_list);
2267 }
2268
2269 // This has to happen *after* we determine which
2270 // pat_idents are variants
2271 self.check_consistent_bindings(arm);
2272
2273 visit::walk_expr_opt(self, &arm.guard);
2274 self.visit_expr(&*arm.body);
2275
2276 self.value_ribs.pop();
2277 }
2278
2279 fn resolve_block(&mut self, block: &Block) {
2280 debug!("(resolving block) entering block");
2281 self.value_ribs.push(Rib::new(NormalRibKind));
2282
2283 // Move down in the graph, if there's an anonymous module rooted here.
2284 let orig_module = self.current_module.clone();
2285 match orig_module.anonymous_children.borrow().get(&block.id) {
2286 None => { /* Nothing to do. */ }
2287 Some(anonymous_module) => {
2288 debug!("(resolving block) found anonymous module, moving \
2289 down");
2290 self.current_module = anonymous_module.clone();
2291 }
2292 }
2293
2294 // Check for imports appearing after non-item statements.
2295 let mut found_non_item = false;
2296 for statement in &block.stmts {
2297 if let ast::StmtDecl(ref declaration, _) = statement.node {
2298 if let ast::DeclItem(ref i) = declaration.node {
2299 match i.node {
2300 ItemExternCrate(_) | ItemUse(_) if found_non_item => {
2301 span_err!(self.session, i.span, E0154,
2302 "imports are not allowed after non-item statements");
2303 }
2304 _ => {}
2305 }
2306 } else {
2307 found_non_item = true
2308 }
2309 } else {
2310 found_non_item = true;
2311 }
2312 }
2313
2314 // Descend into the block.
2315 visit::walk_block(self, block);
2316
2317 // Move back up.
2318 self.current_module = orig_module;
2319
2320 self.value_ribs.pop();
2321 debug!("(resolving block) leaving block");
2322 }
2323
2324 fn resolve_type(&mut self, ty: &Ty) {
2325 match ty.node {
2326 TyPath(ref maybe_qself, ref path) => {
2327 let resolution =
2328 match self.resolve_possibly_assoc_item(ty.id,
2329 maybe_qself.as_ref(),
2330 path,
2331 TypeNS,
2332 true) {
2333 // `<T>::a::b::c` is resolved by typeck alone.
2334 TypecheckRequired => {
2335 // Resolve embedded types.
2336 visit::walk_ty(self, ty);
2337 return;
2338 }
2339 ResolveAttempt(resolution) => resolution,
2340 };
2341
2342 // This is a path in the type namespace. Walk through scopes
2343 // looking for it.
2344 match resolution {
2345 Some(def) => {
2346 // Write the result into the def map.
2347 debug!("(resolving type) writing resolution for `{}` \
2348 (id {}) = {:?}",
2349 path_names_to_string(path, 0),
2350 ty.id, def);
2351 self.record_def(ty.id, def);
2352 }
2353 None => {
2354 // Keep reporting some errors even if they're ignored above.
2355 self.resolve_path(ty.id, path, 0, TypeNS, true);
2356
2357 let kind = if maybe_qself.is_some() {
2358 "associated type"
2359 } else {
2360 "type name"
2361 };
2362
2363 let self_type_name = special_idents::type_self.name;
2364 let is_invalid_self_type_name =
2365 path.segments.len() > 0 &&
2366 maybe_qself.is_none() &&
2367 path.segments[0].identifier.name == self_type_name;
2368 let msg = if is_invalid_self_type_name {
2369 "use of `Self` outside of an impl or trait".to_string()
2370 } else {
2371 format!("use of undeclared {} `{}`",
2372 kind, path_names_to_string(path, 0))
2373 };
2374
2375 self.resolve_error(ty.span, &msg[..]);
2376 }
2377 }
2378 }
2379 _ => {}
2380 }
2381 // Resolve embedded types.
2382 visit::walk_ty(self, ty);
2383 }
2384
2385 fn resolve_pattern(&mut self,
2386 pattern: &Pat,
2387 mode: PatternBindingMode,
2388 // Maps idents to the node ID for the (outermost)
2389 // pattern that binds them
2390 bindings_list: &mut HashMap<Name, NodeId>) {
2391 let pat_id = pattern.id;
2392 walk_pat(pattern, |pattern| {
2393 match pattern.node {
2394 PatIdent(binding_mode, ref path1, _) => {
2395
2396 // The meaning of pat_ident with no type parameters
2397 // depends on whether an enum variant or unit-like struct
2398 // with that name is in scope. The probing lookup has to
2399 // be careful not to emit spurious errors. Only matching
2400 // patterns (match) can match nullary variants or
2401 // unit-like structs. For binding patterns (let), matching
2402 // such a value is simply disallowed (since it's rarely
2403 // what you want).
2404
2405 let ident = path1.node;
2406 let renamed = mtwt::resolve(ident);
2407
2408 match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
2409 FoundStructOrEnumVariant(def, lp)
2410 if mode == RefutableMode => {
2411 debug!("(resolving pattern) resolving `{}` to \
2412 struct or enum variant",
2413 token::get_name(renamed));
2414
2415 self.enforce_default_binding_mode(
2416 pattern,
2417 binding_mode,
2418 "an enum variant");
2419 self.record_def(pattern.id, PathResolution {
2420 base_def: def,
2421 last_private: lp,
2422 depth: 0
2423 });
2424 }
2425 FoundStructOrEnumVariant(..) => {
2426 self.resolve_error(
2427 pattern.span,
2428 &format!("declaration of `{}` shadows an enum \
2429 variant or unit-like struct in \
2430 scope",
2431 token::get_name(renamed)));
2432 }
2433 FoundConst(def, lp) if mode == RefutableMode => {
2434 debug!("(resolving pattern) resolving `{}` to \
2435 constant",
2436 token::get_name(renamed));
2437
2438 self.enforce_default_binding_mode(
2439 pattern,
2440 binding_mode,
2441 "a constant");
2442 self.record_def(pattern.id, PathResolution {
2443 base_def: def,
2444 last_private: lp,
2445 depth: 0
2446 });
2447 }
2448 FoundConst(..) => {
2449 self.resolve_error(pattern.span,
2450 "only irrefutable patterns \
2451 allowed here");
2452 }
2453 BareIdentifierPatternUnresolved => {
2454 debug!("(resolving pattern) binding `{}`",
2455 token::get_name(renamed));
2456
2457 let def = DefLocal(pattern.id);
2458
2459 // Record the definition so that later passes
2460 // will be able to distinguish variants from
2461 // locals in patterns.
2462
2463 self.record_def(pattern.id, PathResolution {
2464 base_def: def,
2465 last_private: LastMod(AllPublic),
2466 depth: 0
2467 });
2468
2469 // Add the binding to the local ribs, if it
2470 // doesn't already exist in the bindings list. (We
2471 // must not add it if it's in the bindings list
2472 // because that breaks the assumptions later
2473 // passes make about or-patterns.)
2474 if !bindings_list.contains_key(&renamed) {
2475 let this = &mut *self;
2476 let last_rib = this.value_ribs.last_mut().unwrap();
2477 last_rib.bindings.insert(renamed, DlDef(def));
2478 bindings_list.insert(renamed, pat_id);
2479 } else if mode == ArgumentIrrefutableMode &&
2480 bindings_list.contains_key(&renamed) {
2481 // Forbid duplicate bindings in the same
2482 // parameter list.
2483 self.resolve_error(pattern.span,
2484 &format!("identifier `{}` \
2485 is bound more \
2486 than once in \
2487 this parameter \
2488 list",
2489 token::get_ident(
2490 ident))
2491 )
2492 } else if bindings_list.get(&renamed) ==
2493 Some(&pat_id) {
2494 // Then this is a duplicate variable in the
2495 // same disjunction, which is an error.
2496 self.resolve_error(pattern.span,
2497 &format!("identifier `{}` is bound \
2498 more than once in the same \
2499 pattern",
2500 token::get_ident(ident)));
2501 }
2502 // Else, not bound in the same pattern: do
2503 // nothing.
2504 }
2505 }
2506 }
2507
2508 PatEnum(ref path, _) => {
2509 // This must be an enum variant, struct or const.
2510 let resolution =
2511 match self.resolve_possibly_assoc_item(pat_id, None,
2512 path, ValueNS,
2513 false) {
2514 // The below shouldn't happen because all
2515 // qualified paths should be in PatQPath.
2516 TypecheckRequired =>
2517 self.session.span_bug(
2518 path.span,
2519 "resolve_possibly_assoc_item claimed
2520 that a path in PatEnum requires typecheck
2521 to resolve, but qualified paths should be
2522 PatQPath"),
2523 ResolveAttempt(resolution) => resolution,
2524 };
2525 if let Some(path_res) = resolution {
2526 match path_res.base_def {
2527 DefVariant(..) | DefStruct(..) | DefConst(..) => {
2528 self.record_def(pattern.id, path_res);
2529 }
2530 DefStatic(..) => {
2531 self.resolve_error(path.span,
2532 "static variables cannot be \
2533 referenced in a pattern, \
2534 use a `const` instead");
2535 }
2536 _ => {
2537 // If anything ends up here entirely resolved,
2538 // it's an error. If anything ends up here
2539 // partially resolved, that's OK, because it may
2540 // be a `T::CONST` that typeck will resolve.
2541 if path_res.depth == 0 {
2542 self.resolve_error(
2543 path.span,
2544 &format!("`{}` is not an enum variant, struct or const",
2545 token::get_ident(
2546 path.segments.last().unwrap().identifier)));
2547 } else {
2548 let const_name = path.segments.last().unwrap()
2549 .identifier.name;
2550 let traits = self.get_traits_containing_item(const_name);
2551 self.trait_map.insert(pattern.id, traits);
2552 self.record_def(pattern.id, path_res);
2553 }
2554 }
2555 }
2556 } else {
2557 self.resolve_error(path.span,
2558 &format!("unresolved enum variant, struct or const `{}`",
2559 token::get_ident(path.segments.last().unwrap().identifier)));
2560 }
2561 visit::walk_path(self, path);
2562 }
2563
2564 PatQPath(ref qself, ref path) => {
2565 // Associated constants only.
2566 let resolution =
2567 match self.resolve_possibly_assoc_item(pat_id, Some(qself),
2568 path, ValueNS,
2569 false) {
2570 TypecheckRequired => {
2571 // All `<T>::CONST` should end up here, and will
2572 // require use of the trait map to resolve
2573 // during typechecking.
2574 let const_name = path.segments.last().unwrap()
2575 .identifier.name;
2576 let traits = self.get_traits_containing_item(const_name);
2577 self.trait_map.insert(pattern.id, traits);
2578 visit::walk_pat(self, pattern);
2579 return true;
2580 }
2581 ResolveAttempt(resolution) => resolution,
2582 };
2583 if let Some(path_res) = resolution {
2584 match path_res.base_def {
2585 // All `<T as Trait>::CONST` should end up here, and
2586 // have the trait already selected.
2587 DefAssociatedConst(..) => {
2588 self.record_def(pattern.id, path_res);
2589 }
2590 _ => {
2591 self.resolve_error(path.span,
2592 &format!("`{}` is not an associated const",
2593 token::get_ident(
2594 path.segments.last().unwrap().identifier)));
2595 }
2596 }
2597 } else {
2598 self.resolve_error(path.span,
2599 &format!("unresolved associated const `{}`",
2600 token::get_ident(path.segments.last().unwrap().identifier)));
2601 }
2602 visit::walk_pat(self, pattern);
2603 }
2604
2605 PatStruct(ref path, _, _) => {
2606 match self.resolve_path(pat_id, path, 0, TypeNS, false) {
2607 Some(definition) => {
2608 self.record_def(pattern.id, definition);
2609 }
2610 result => {
2611 debug!("(resolving pattern) didn't find struct \
2612 def: {:?}", result);
2613 let msg = format!("`{}` does not name a structure",
2614 path_names_to_string(path, 0));
2615 self.resolve_error(path.span, &msg[..]);
2616 }
2617 }
2618 visit::walk_path(self, path);
2619 }
2620
2621 PatLit(_) | PatRange(..) => {
2622 visit::walk_pat(self, pattern);
2623 }
2624
2625 _ => {
2626 // Nothing to do.
2627 }
2628 }
2629 true
2630 });
2631 }
2632
2633 fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
2634 -> BareIdentifierPatternResolution {
2635 let module = self.current_module.clone();
2636 match self.resolve_item_in_lexical_scope(module,
2637 name,
2638 ValueNS) {
2639 Success((target, _)) => {
2640 debug!("(resolve bare identifier pattern) succeeded in \
2641 finding {} at {:?}",
2642 token::get_name(name),
2643 target.bindings.value_def.borrow());
2644 match *target.bindings.value_def.borrow() {
2645 None => {
2646 panic!("resolved name in the value namespace to a \
2647 set of name bindings with no def?!");
2648 }
2649 Some(def) => {
2650 // For the two success cases, this lookup can be
2651 // considered as not having a private component because
2652 // the lookup happened only within the current module.
2653 match def.def {
2654 def @ DefVariant(..) | def @ DefStruct(..) => {
2655 return FoundStructOrEnumVariant(def, LastMod(AllPublic));
2656 }
2657 def @ DefConst(..) | def @ DefAssociatedConst(..) => {
2658 return FoundConst(def, LastMod(AllPublic));
2659 }
2660 DefStatic(..) => {
2661 self.resolve_error(span,
2662 "static variables cannot be \
2663 referenced in a pattern, \
2664 use a `const` instead");
2665 return BareIdentifierPatternUnresolved;
2666 }
2667 _ => {
2668 return BareIdentifierPatternUnresolved;
2669 }
2670 }
2671 }
2672 }
2673 }
2674
2675 Indeterminate => {
2676 panic!("unexpected indeterminate result");
2677 }
2678 Failed(err) => {
2679 match err {
2680 Some((span, msg)) => {
2681 self.resolve_error(span, &format!("failed to resolve: {}",
2682 msg));
2683 }
2684 None => ()
2685 }
2686
2687 debug!("(resolve bare identifier pattern) failed to find {}",
2688 token::get_name(name));
2689 return BareIdentifierPatternUnresolved;
2690 }
2691 }
2692 }
2693
2694 /// Handles paths that may refer to associated items
2695 fn resolve_possibly_assoc_item(&mut self,
2696 id: NodeId,
2697 maybe_qself: Option<&ast::QSelf>,
2698 path: &Path,
2699 namespace: Namespace,
2700 check_ribs: bool)
2701 -> AssocItemResolveResult
2702 {
2703 let max_assoc_types;
2704
2705 match maybe_qself {
2706 Some(qself) => {
2707 if qself.position == 0 {
2708 return TypecheckRequired;
2709 }
2710 max_assoc_types = path.segments.len() - qself.position;
2711 // Make sure the trait is valid.
2712 let _ = self.resolve_trait_reference(id, path, max_assoc_types);
2713 }
2714 None => {
2715 max_assoc_types = path.segments.len();
2716 }
2717 }
2718
2719 let mut resolution = self.with_no_errors(|this| {
2720 this.resolve_path(id, path, 0, namespace, check_ribs)
2721 });
2722 for depth in 1..max_assoc_types {
2723 if resolution.is_some() {
2724 break;
2725 }
2726 self.with_no_errors(|this| {
2727 resolution = this.resolve_path(id, path, depth,
2728 TypeNS, true);
2729 });
2730 }
2731 if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
2732 // A module is not a valid type or value.
2733 resolution = None;
2734 }
2735 ResolveAttempt(resolution)
2736 }
2737
2738 /// If `check_ribs` is true, checks the local definitions first; i.e.
2739 /// doesn't skip straight to the containing module.
2740 /// Skips `path_depth` trailing segments, which is also reflected in the
2741 /// returned value. See `middle::def::PathResolution` for more info.
2742 fn resolve_path(&mut self,
2743 id: NodeId,
2744 path: &Path,
2745 path_depth: usize,
2746 namespace: Namespace,
2747 check_ribs: bool) -> Option<PathResolution> {
2748 let span = path.span;
2749 let segments = &path.segments[..path.segments.len()-path_depth];
2750
2751 let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
2752
2753 if path.global {
2754 let def = self.resolve_crate_relative_path(span, segments, namespace);
2755 return def.map(mk_res);
2756 }
2757
2758 // Try to find a path to an item in a module.
2759 let unqualified_def =
2760 self.resolve_identifier(segments.last().unwrap().identifier,
2761 namespace,
2762 check_ribs,
2763 span);
2764
2765 if segments.len() <= 1 {
2766 return unqualified_def.map(mk_res);
2767 }
2768
2769 let def = self.resolve_module_relative_path(span, segments, namespace);
2770 match (def, unqualified_def) {
2771 (Some((ref d, _)), Some((ref ud, _))) if *d == *ud => {
2772 self.session
2773 .add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
2774 id, span,
2775 "unnecessary qualification".to_string());
2776 }
2777 _ => {}
2778 }
2779
2780 def.map(mk_res)
2781 }
2782
2783 // Resolve a single identifier.
2784 fn resolve_identifier(&mut self,
2785 identifier: Ident,
2786 namespace: Namespace,
2787 check_ribs: bool,
2788 span: Span)
2789 -> Option<(Def, LastPrivate)> {
2790 // First, check to see whether the name is a primitive type.
2791 if namespace == TypeNS {
2792 if let Some(&prim_ty) = self.primitive_type_table
2793 .primitive_types
2794 .get(&identifier.name) {
2795 return Some((DefPrimTy(prim_ty), LastMod(AllPublic)));
2796 }
2797 }
2798
2799 if check_ribs {
2800 if let Some(def) = self.resolve_identifier_in_local_ribs(identifier,
2801 namespace,
2802 span) {
2803 return Some((def, LastMod(AllPublic)));
2804 }
2805 }
2806
2807 self.resolve_item_by_name_in_lexical_scope(identifier.name, namespace)
2808 }
2809
2810 // FIXME #4952: Merge me with resolve_name_in_module?
2811 fn resolve_definition_of_name_in_module(&mut self,
2812 containing_module: Rc<Module>,
2813 name: Name,
2814 namespace: Namespace)
2815 -> NameDefinition {
2816 // First, search children.
2817 build_reduced_graph::populate_module_if_necessary(self, &containing_module);
2818
2819 match containing_module.children.borrow().get(&name) {
2820 Some(child_name_bindings) => {
2821 match child_name_bindings.def_for_namespace(namespace) {
2822 Some(def) => {
2823 // Found it. Stop the search here.
2824 let p = child_name_bindings.defined_in_public_namespace(namespace);
2825 let lp = if p {LastMod(AllPublic)} else {
2826 LastMod(DependsOn(def.def_id()))
2827 };
2828 return ChildNameDefinition(def, lp);
2829 }
2830 None => {}
2831 }
2832 }
2833 None => {}
2834 }
2835
2836 // Next, search import resolutions.
2837 match containing_module.import_resolutions.borrow().get(&name) {
2838 Some(import_resolution) if import_resolution.is_public => {
2839 if let Some(target) = (*import_resolution).target_for_namespace(namespace) {
2840 match target.bindings.def_for_namespace(namespace) {
2841 Some(def) => {
2842 // Found it.
2843 let id = import_resolution.id(namespace);
2844 // track imports and extern crates as well
2845 self.used_imports.insert((id, namespace));
2846 self.record_import_use(id, name);
2847 match target.target_module.def_id.get() {
2848 Some(DefId{krate: kid, ..}) => {
2849 self.used_crates.insert(kid);
2850 },
2851 _ => {}
2852 }
2853 return ImportNameDefinition(def, LastMod(AllPublic));
2854 }
2855 None => {
2856 // This can happen with external impls, due to
2857 // the imperfect way we read the metadata.
2858 }
2859 }
2860 }
2861 }
2862 Some(..) | None => {} // Continue.
2863 }
2864
2865 // Finally, search through external children.
2866 if namespace == TypeNS {
2867 if let Some(module) = containing_module.external_module_children.borrow()
2868 .get(&name).cloned() {
2869 if let Some(def_id) = module.def_id.get() {
2870 // track used crates
2871 self.used_crates.insert(def_id.krate);
2872 let lp = if module.is_public {LastMod(AllPublic)} else {
2873 LastMod(DependsOn(def_id))
2874 };
2875 return ChildNameDefinition(DefMod(def_id), lp);
2876 }
2877 }
2878 }
2879
2880 return NoNameDefinition;
2881 }
2882
2883 // resolve a "module-relative" path, e.g. a::b::c
2884 fn resolve_module_relative_path(&mut self,
2885 span: Span,
2886 segments: &[ast::PathSegment],
2887 namespace: Namespace)
2888 -> Option<(Def, LastPrivate)> {
2889 let module_path = segments.init().iter()
2890 .map(|ps| ps.identifier.name)
2891 .collect::<Vec<_>>();
2892
2893 let containing_module;
2894 let last_private;
2895 let current_module = self.current_module.clone();
2896 match self.resolve_module_path(current_module,
2897 &module_path[..],
2898 UseLexicalScope,
2899 span,
2900 PathSearch) {
2901 Failed(err) => {
2902 let (span, msg) = match err {
2903 Some((span, msg)) => (span, msg),
2904 None => {
2905 let msg = format!("Use of undeclared type or module `{}`",
2906 names_to_string(&module_path));
2907 (span, msg)
2908 }
2909 };
2910
2911 self.resolve_error(span, &format!("failed to resolve. {}",
2912 msg));
2913 return None;
2914 }
2915 Indeterminate => panic!("indeterminate unexpected"),
2916 Success((resulting_module, resulting_last_private)) => {
2917 containing_module = resulting_module;
2918 last_private = resulting_last_private;
2919 }
2920 }
2921
2922 let name = segments.last().unwrap().identifier.name;
2923 let def = match self.resolve_definition_of_name_in_module(containing_module.clone(),
2924 name,
2925 namespace) {
2926 NoNameDefinition => {
2927 // We failed to resolve the name. Report an error.
2928 return None;
2929 }
2930 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
2931 (def, last_private.or(lp))
2932 }
2933 };
2934 if let Some(DefId{krate: kid, ..}) = containing_module.def_id.get() {
2935 self.used_crates.insert(kid);
2936 }
2937 return Some(def);
2938 }
2939
2940 /// Invariant: This must be called only during main resolution, not during
2941 /// import resolution.
2942 fn resolve_crate_relative_path(&mut self,
2943 span: Span,
2944 segments: &[ast::PathSegment],
2945 namespace: Namespace)
2946 -> Option<(Def, LastPrivate)> {
2947 let module_path = segments.init().iter()
2948 .map(|ps| ps.identifier.name)
2949 .collect::<Vec<_>>();
2950
2951 let root_module = self.graph_root.get_module();
2952
2953 let containing_module;
2954 let last_private;
2955 match self.resolve_module_path_from_root(root_module,
2956 &module_path[..],
2957 0,
2958 span,
2959 PathSearch,
2960 LastMod(AllPublic)) {
2961 Failed(err) => {
2962 let (span, msg) = match err {
2963 Some((span, msg)) => (span, msg),
2964 None => {
2965 let msg = format!("Use of undeclared module `::{}`",
2966 names_to_string(&module_path[..]));
2967 (span, msg)
2968 }
2969 };
2970
2971 self.resolve_error(span, &format!("failed to resolve. {}",
2972 msg));
2973 return None;
2974 }
2975
2976 Indeterminate => {
2977 panic!("indeterminate unexpected");
2978 }
2979
2980 Success((resulting_module, resulting_last_private)) => {
2981 containing_module = resulting_module;
2982 last_private = resulting_last_private;
2983 }
2984 }
2985
2986 let name = segments.last().unwrap().identifier.name;
2987 match self.resolve_definition_of_name_in_module(containing_module,
2988 name,
2989 namespace) {
2990 NoNameDefinition => {
2991 // We failed to resolve the name. Report an error.
2992 return None;
2993 }
2994 ChildNameDefinition(def, lp) | ImportNameDefinition(def, lp) => {
2995 return Some((def, last_private.or(lp)));
2996 }
2997 }
2998 }
2999
3000 fn resolve_identifier_in_local_ribs(&mut self,
3001 ident: Ident,
3002 namespace: Namespace,
3003 span: Span)
3004 -> Option<Def> {
3005 // Check the local set of ribs.
3006 let search_result = match namespace {
3007 ValueNS => {
3008 let renamed = mtwt::resolve(ident);
3009 self.search_ribs(&self.value_ribs, renamed, span)
3010 }
3011 TypeNS => {
3012 let name = ident.name;
3013 self.search_ribs(&self.type_ribs, name, span)
3014 }
3015 };
3016
3017 match search_result {
3018 Some(DlDef(def)) => {
3019 debug!("(resolving path in local ribs) resolved `{}` to local: {:?}",
3020 token::get_ident(ident),
3021 def);
3022 Some(def)
3023 }
3024 Some(DlField) | Some(DlImpl(_)) | None => {
3025 None
3026 }
3027 }
3028 }
3029
3030 fn resolve_item_by_name_in_lexical_scope(&mut self,
3031 name: Name,
3032 namespace: Namespace)
3033 -> Option<(Def, LastPrivate)> {
3034 // Check the items.
3035 let module = self.current_module.clone();
3036 match self.resolve_item_in_lexical_scope(module,
3037 name,
3038 namespace) {
3039 Success((target, _)) => {
3040 match (*target.bindings).def_for_namespace(namespace) {
3041 None => {
3042 // This can happen if we were looking for a type and
3043 // found a module instead. Modules don't have defs.
3044 debug!("(resolving item path by identifier in lexical \
3045 scope) failed to resolve {} after success...",
3046 token::get_name(name));
3047 return None;
3048 }
3049 Some(def) => {
3050 debug!("(resolving item path in lexical scope) \
3051 resolved `{}` to item",
3052 token::get_name(name));
3053 // This lookup is "all public" because it only searched
3054 // for one identifier in the current module (couldn't
3055 // have passed through reexports or anything like that.
3056 return Some((def, LastMod(AllPublic)));
3057 }
3058 }
3059 }
3060 Indeterminate => {
3061 panic!("unexpected indeterminate result");
3062 }
3063 Failed(err) => {
3064 debug!("(resolving item path by identifier in lexical scope) \
3065 failed to resolve {}", token::get_name(name));
3066
3067 if let Some((span, msg)) = err {
3068 self.resolve_error(span, &format!("failed to resolve. {}", msg))
3069 }
3070
3071 return None;
3072 }
3073 }
3074 }
3075
3076 fn with_no_errors<T, F>(&mut self, f: F) -> T where
3077 F: FnOnce(&mut Resolver) -> T,
3078 {
3079 self.emit_errors = false;
3080 let rs = f(self);
3081 self.emit_errors = true;
3082 rs
3083 }
3084
3085 fn resolve_error(&self, span: Span, s: &str) {
3086 if self.emit_errors {
3087 self.session.span_err(span, s);
3088 }
3089 }
3090
3091 fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
3092 fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
3093 -> Option<(Path, NodeId, FallbackChecks)> {
3094 match t.node {
3095 TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
3096 TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
3097 TyRptr(_, ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, allow),
3098 // This doesn't handle the remaining `Ty` variants as they are not
3099 // that commonly the self_type, it might be interesting to provide
3100 // support for those in future.
3101 _ => None,
3102 }
3103 }
3104
3105 fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
3106 -> Option<Rc<Module>> {
3107 let root = this.current_module.clone();
3108 let last_name = name_path.last().unwrap();
3109
3110 if name_path.len() == 1 {
3111 match this.primitive_type_table.primitive_types.get(last_name) {
3112 Some(_) => None,
3113 None => {
3114 match this.current_module.children.borrow().get(last_name) {
3115 Some(child) => child.get_module_if_available(),
3116 None => None
3117 }
3118 }
3119 }
3120 } else {
3121 match this.resolve_module_path(root,
3122 &name_path[..],
3123 UseLexicalScope,
3124 span,
3125 PathSearch) {
3126 Success((module, _)) => Some(module),
3127 _ => None
3128 }
3129 }
3130 }
3131
3132 fn is_static_method(this: &Resolver, did: DefId) -> bool {
3133 if did.krate == ast::LOCAL_CRATE {
3134 let sig = match this.ast_map.get(did.node) {
3135 ast_map::NodeTraitItem(trait_item) => match trait_item.node {
3136 ast::MethodTraitItem(ref sig, _) => sig,
3137 _ => return false
3138 },
3139 ast_map::NodeImplItem(impl_item) => match impl_item.node {
3140 ast::MethodImplItem(ref sig, _) => sig,
3141 _ => return false
3142 },
3143 _ => return false
3144 };
3145 sig.explicit_self.node == ast::SelfStatic
3146 } else {
3147 csearch::is_static_method(&this.session.cstore, did)
3148 }
3149 }
3150
3151 let (path, node_id, allowed) = match self.current_self_type {
3152 Some(ref ty) => match extract_path_and_node_id(ty, Everything) {
3153 Some(x) => x,
3154 None => return NoSuggestion,
3155 },
3156 None => return NoSuggestion,
3157 };
3158
3159 if allowed == Everything {
3160 // Look for a field with the same name in the current self_type.
3161 match self.def_map.borrow().get(&node_id).map(|d| d.full_def()) {
3162 Some(DefTy(did, _)) |
3163 Some(DefStruct(did)) |
3164 Some(DefVariant(_, did, _)) => match self.structs.get(&did) {
3165 None => {}
3166 Some(fields) => {
3167 if fields.iter().any(|&field_name| name == field_name) {
3168 return Field;
3169 }
3170 }
3171 },
3172 _ => {} // Self type didn't resolve properly
3173 }
3174 }
3175
3176 let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>();
3177
3178 // Look for a method in the current self type's impl module.
3179 if let Some(module) = get_module(self, path.span, &name_path) {
3180 if let Some(binding) = module.children.borrow().get(&name) {
3181 if let Some(DefMethod(did, _)) = binding.def_for_namespace(ValueNS) {
3182 if is_static_method(self, did) {
3183 return StaticMethod(path_names_to_string(&path, 0))
3184 }
3185 if self.current_trait_ref.is_some() {
3186 return TraitItem;
3187 } else if allowed == Everything {
3188 return Method;
3189 }
3190 }
3191 }
3192 }
3193
3194 // Look for a method in the current trait.
3195 if let Some((trait_did, ref trait_ref)) = self.current_trait_ref {
3196 if let Some(&did) = self.trait_item_map.get(&(name, trait_did)) {
3197 if is_static_method(self, did) {
3198 return TraitMethod(path_names_to_string(&trait_ref.path, 0));
3199 } else {
3200 return TraitItem;
3201 }
3202 }
3203 }
3204
3205 NoSuggestion
3206 }
3207
3208 fn find_best_match_for_name(&mut self, name: &str) -> Option<String> {
3209 let mut maybes: Vec<token::InternedString> = Vec::new();
3210 let mut values: Vec<usize> = Vec::new();
3211
3212 for rib in self.value_ribs.iter().rev() {
3213 for (&k, _) in &rib.bindings {
3214 maybes.push(token::get_name(k));
3215 values.push(usize::MAX);
3216 }
3217 }
3218
3219 let mut smallest = 0;
3220 for (i, other) in maybes.iter().enumerate() {
3221 values[i] = lev_distance(name, &other);
3222
3223 if values[i] <= values[smallest] {
3224 smallest = i;
3225 }
3226 }
3227
3228 // As a loose rule to avoid obviously incorrect suggestions, clamp the
3229 // maximum edit distance we will accept for a suggestion to one third of
3230 // the typo'd name's length.
3231 let max_distance = std::cmp::max(name.len(), 3) / 3;
3232
3233 if !values.is_empty() &&
3234 values[smallest] <= max_distance &&
3235 name != &maybes[smallest][..] {
3236
3237 Some(maybes[smallest].to_string())
3238
3239 } else {
3240 None
3241 }
3242 }
3243
3244 fn resolve_expr(&mut self, expr: &Expr) {
3245 // First, record candidate traits for this expression if it could
3246 // result in the invocation of a method call.
3247
3248 self.record_candidate_traits_for_expr_if_necessary(expr);
3249
3250 // Next, resolve the node.
3251 match expr.node {
3252 ExprPath(ref maybe_qself, ref path) => {
3253 let resolution =
3254 match self.resolve_possibly_assoc_item(expr.id,
3255 maybe_qself.as_ref(),
3256 path,
3257 ValueNS,
3258 true) {
3259 // `<T>::a::b::c` is resolved by typeck alone.
3260 TypecheckRequired => {
3261 let method_name = path.segments.last().unwrap().identifier.name;
3262 let traits = self.get_traits_containing_item(method_name);
3263 self.trait_map.insert(expr.id, traits);
3264 visit::walk_expr(self, expr);
3265 return;
3266 }
3267 ResolveAttempt(resolution) => resolution,
3268 };
3269
3270 // This is a local path in the value namespace. Walk through
3271 // scopes looking for it.
3272 if let Some(path_res) = resolution {
3273 // Check if struct variant
3274 if let DefVariant(_, _, true) = path_res.base_def {
3275 let path_name = path_names_to_string(path, 0);
3276 self.resolve_error(expr.span,
3277 &format!("`{}` is a struct variant name, but \
3278 this expression \
3279 uses it like a function name",
3280 path_name));
3281
3282 let msg = format!("did you mean to write: \
3283 `{} {{ /* fields */ }}`?",
3284 path_name);
3285 if self.emit_errors {
3286 self.session.fileline_help(expr.span, &msg);
3287 } else {
3288 self.session.span_help(expr.span, &msg);
3289 }
3290 } else {
3291 // Write the result into the def map.
3292 debug!("(resolving expr) resolved `{}`",
3293 path_names_to_string(path, 0));
3294
3295 // Partial resolutions will need the set of traits in scope,
3296 // so they can be completed during typeck.
3297 if path_res.depth != 0 {
3298 let method_name = path.segments.last().unwrap().identifier.name;
3299 let traits = self.get_traits_containing_item(method_name);
3300 self.trait_map.insert(expr.id, traits);
3301 }
3302
3303 self.record_def(expr.id, path_res);
3304 }
3305 } else {
3306 // Be helpful if the name refers to a struct
3307 // (The pattern matching def_tys where the id is in self.structs
3308 // matches on regular structs while excluding tuple- and enum-like
3309 // structs, which wouldn't result in this error.)
3310 let path_name = path_names_to_string(path, 0);
3311 let type_res = self.with_no_errors(|this| {
3312 this.resolve_path(expr.id, path, 0, TypeNS, false)
3313 });
3314 match type_res.map(|r| r.base_def) {
3315 Some(DefTy(struct_id, _))
3316 if self.structs.contains_key(&struct_id) => {
3317 self.resolve_error(expr.span,
3318 &format!("`{}` is a structure name, but \
3319 this expression \
3320 uses it like a function name",
3321 path_name));
3322
3323 let msg = format!("did you mean to write: \
3324 `{} {{ /* fields */ }}`?",
3325 path_name);
3326 if self.emit_errors {
3327 self.session.fileline_help(expr.span, &msg);
3328 } else {
3329 self.session.span_help(expr.span, &msg);
3330 }
3331 }
3332 _ => {
3333 // Keep reporting some errors even if they're ignored above.
3334 self.resolve_path(expr.id, path, 0, ValueNS, true);
3335
3336 let mut method_scope = false;
3337 self.value_ribs.iter().rev().all(|rib| {
3338 method_scope = match rib.kind {
3339 MethodRibKind => true,
3340 ItemRibKind | ConstantItemRibKind => false,
3341 _ => return true, // Keep advancing
3342 };
3343 false // Stop advancing
3344 });
3345
3346 if method_scope &&
3347 &token::get_name(special_names::self_)[..] == path_name {
3348 self.resolve_error(
3349 expr.span,
3350 "`self` is not available \
3351 in a static method. Maybe a \
3352 `self` argument is missing?");
3353 } else {
3354 let last_name = path.segments.last().unwrap().identifier.name;
3355 let mut msg = match self.find_fallback_in_self_type(last_name) {
3356 NoSuggestion => {
3357 // limit search to 5 to reduce the number
3358 // of stupid suggestions
3359 self.find_best_match_for_name(&path_name)
3360 .map_or("".to_string(),
3361 |x| format!("`{}`", x))
3362 }
3363 Field => format!("`self.{}`", path_name),
3364 Method |
3365 TraitItem =>
3366 format!("to call `self.{}`", path_name),
3367 TraitMethod(path_str) |
3368 StaticMethod(path_str) =>
3369 format!("to call `{}::{}`", path_str, path_name)
3370 };
3371
3372 if !msg.is_empty() {
3373 msg = format!(". Did you mean {}?", msg)
3374 }
3375
3376 self.resolve_error(
3377 expr.span,
3378 &format!("unresolved name `{}`{}",
3379 path_name, msg));
3380 }
3381 }
3382 }
3383 }
3384
3385 visit::walk_expr(self, expr);
3386 }
3387
3388 ExprStruct(ref path, _, _) => {
3389 // Resolve the path to the structure it goes to. We don't
3390 // check to ensure that the path is actually a structure; that
3391 // is checked later during typeck.
3392 match self.resolve_path(expr.id, path, 0, TypeNS, false) {
3393 Some(definition) => self.record_def(expr.id, definition),
3394 None => {
3395 debug!("(resolving expression) didn't find struct def",);
3396 let msg = format!("`{}` does not name a structure",
3397 path_names_to_string(path, 0));
3398 self.resolve_error(path.span, &msg[..]);
3399 }
3400 }
3401
3402 visit::walk_expr(self, expr);
3403 }
3404
3405 ExprLoop(_, Some(label)) | ExprWhile(_, _, Some(label)) => {
3406 self.with_label_rib(|this| {
3407 let def_like = DlDef(DefLabel(expr.id));
3408
3409 {
3410 let rib = this.label_ribs.last_mut().unwrap();
3411 let renamed = mtwt::resolve(label);
3412 rib.bindings.insert(renamed, def_like);
3413 }
3414
3415 visit::walk_expr(this, expr);
3416 })
3417 }
3418
3419 ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
3420 let renamed = mtwt::resolve(label);
3421 match self.search_label(renamed) {
3422 None => {
3423 self.resolve_error(
3424 expr.span,
3425 &format!("use of undeclared label `{}`",
3426 token::get_ident(label)))
3427 }
3428 Some(DlDef(def @ DefLabel(_))) => {
3429 // Since this def is a label, it is never read.
3430 self.record_def(expr.id, PathResolution {
3431 base_def: def,
3432 last_private: LastMod(AllPublic),
3433 depth: 0
3434 })
3435 }
3436 Some(_) => {
3437 self.session.span_bug(expr.span,
3438 "label wasn't mapped to a \
3439 label def!")
3440 }
3441 }
3442 }
3443
3444 _ => {
3445 visit::walk_expr(self, expr);
3446 }
3447 }
3448 }
3449
3450 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
3451 match expr.node {
3452 ExprField(_, ident) => {
3453 // FIXME(#6890): Even though you can't treat a method like a
3454 // field, we need to add any trait methods we find that match
3455 // the field name so that we can do some nice error reporting
3456 // later on in typeck.
3457 let traits = self.get_traits_containing_item(ident.node.name);
3458 self.trait_map.insert(expr.id, traits);
3459 }
3460 ExprMethodCall(ident, _, _) => {
3461 debug!("(recording candidate traits for expr) recording \
3462 traits for {}",
3463 expr.id);
3464 let traits = self.get_traits_containing_item(ident.node.name);
3465 self.trait_map.insert(expr.id, traits);
3466 }
3467 _ => {
3468 // Nothing to do.
3469 }
3470 }
3471 }
3472
3473 fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3474 debug!("(getting traits containing item) looking for '{}'",
3475 token::get_name(name));
3476
3477 fn add_trait_info(found_traits: &mut Vec<DefId>,
3478 trait_def_id: DefId,
3479 name: Name) {
3480 debug!("(adding trait info) found trait {}:{} for method '{}'",
3481 trait_def_id.krate,
3482 trait_def_id.node,
3483 token::get_name(name));
3484 found_traits.push(trait_def_id);
3485 }
3486
3487 let mut found_traits = Vec::new();
3488 let mut search_module = self.current_module.clone();
3489 loop {
3490 // Look for the current trait.
3491 match self.current_trait_ref {
3492 Some((trait_def_id, _)) => {
3493 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3494 add_trait_info(&mut found_traits, trait_def_id, name);
3495 }
3496 }
3497 None => {} // Nothing to do.
3498 }
3499
3500 // Look for trait children.
3501 build_reduced_graph::populate_module_if_necessary(self, &search_module);
3502
3503 {
3504 for (_, child_names) in search_module.children.borrow().iter() {
3505 let def = match child_names.def_for_namespace(TypeNS) {
3506 Some(def) => def,
3507 None => continue
3508 };
3509 let trait_def_id = match def {
3510 DefTrait(trait_def_id) => trait_def_id,
3511 _ => continue,
3512 };
3513 if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3514 add_trait_info(&mut found_traits, trait_def_id, name);
3515 }
3516 }
3517 }
3518
3519 // Look for imports.
3520 for (_, import) in search_module.import_resolutions.borrow().iter() {
3521 let target = match import.target_for_namespace(TypeNS) {
3522 None => continue,
3523 Some(target) => target,
3524 };
3525 let did = match target.bindings.def_for_namespace(TypeNS) {
3526 Some(DefTrait(trait_def_id)) => trait_def_id,
3527 Some(..) | None => continue,
3528 };
3529 if self.trait_item_map.contains_key(&(name, did)) {
3530 add_trait_info(&mut found_traits, did, name);
3531 let id = import.type_id;
3532 self.used_imports.insert((id, TypeNS));
3533 let trait_name = self.get_trait_name(did);
3534 self.record_import_use(id, trait_name);
3535 if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
3536 self.used_crates.insert(kid);
3537 }
3538 }
3539 }
3540
3541 match search_module.parent_link.clone() {
3542 NoParentLink | ModuleParentLink(..) => break,
3543 BlockParentLink(parent_module, _) => {
3544 search_module = parent_module.upgrade().unwrap();
3545 }
3546 }
3547 }
3548
3549 found_traits
3550 }
3551
3552 fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
3553 debug!("(recording def) recording {:?} for {}", resolution, node_id);
3554 assert!(match resolution.last_private {LastImport{..} => false, _ => true},
3555 "Import should only be used for `use` directives");
3556
3557 if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
3558 let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
3559 self.session.span_bug(span, &format!("path resolved multiple times \
3560 ({:?} before, {:?} now)",
3561 prev_res, resolution));
3562 }
3563 }
3564
3565 fn enforce_default_binding_mode(&mut self,
3566 pat: &Pat,
3567 pat_binding_mode: BindingMode,
3568 descr: &str) {
3569 match pat_binding_mode {
3570 BindByValue(_) => {}
3571 BindByRef(..) => {
3572 self.resolve_error(pat.span,
3573 &format!("cannot use `ref` binding mode \
3574 with {}",
3575 descr));
3576 }
3577 }
3578 }
3579
3580 //
3581 // Diagnostics
3582 //
3583 // Diagnostics are not particularly efficient, because they're rarely
3584 // hit.
3585 //
3586
3587 #[allow(dead_code)] // useful for debugging
3588 fn dump_module(&mut self, module_: Rc<Module>) {
3589 debug!("Dump of module `{}`:", module_to_string(&*module_));
3590
3591 debug!("Children:");
3592 build_reduced_graph::populate_module_if_necessary(self, &module_);
3593 for (&name, _) in module_.children.borrow().iter() {
3594 debug!("* {}", token::get_name(name));
3595 }
3596
3597 debug!("Import resolutions:");
3598 let import_resolutions = module_.import_resolutions.borrow();
3599 for (&name, import_resolution) in import_resolutions.iter() {
3600 let value_repr;
3601 match import_resolution.target_for_namespace(ValueNS) {
3602 None => { value_repr = "".to_string(); }
3603 Some(_) => {
3604 value_repr = " value:?".to_string();
3605 // FIXME #4954
3606 }
3607 }
3608
3609 let type_repr;
3610 match import_resolution.target_for_namespace(TypeNS) {
3611 None => { type_repr = "".to_string(); }
3612 Some(_) => {
3613 type_repr = " type:?".to_string();
3614 // FIXME #4954
3615 }
3616 }
3617
3618 debug!("* {}:{}{}", token::get_name(name), value_repr, type_repr);
3619 }
3620 }
3621 }
3622
3623
3624 fn names_to_string(names: &[Name]) -> String {
3625 let mut first = true;
3626 let mut result = String::new();
3627 for name in names {
3628 if first {
3629 first = false
3630 } else {
3631 result.push_str("::")
3632 }
3633 result.push_str(&token::get_name(*name));
3634 };
3635 result
3636 }
3637
3638 fn path_names_to_string(path: &Path, depth: usize) -> String {
3639 let names: Vec<ast::Name> = path.segments[..path.segments.len()-depth]
3640 .iter()
3641 .map(|seg| seg.identifier.name)
3642 .collect();
3643 names_to_string(&names[..])
3644 }
3645
3646 /// A somewhat inefficient routine to obtain the name of a module.
3647 fn module_to_string(module: &Module) -> String {
3648 let mut names = Vec::new();
3649
3650 fn collect_mod(names: &mut Vec<ast::Name>, module: &Module) {
3651 match module.parent_link {
3652 NoParentLink => {}
3653 ModuleParentLink(ref module, name) => {
3654 names.push(name);
3655 collect_mod(names, &*module.upgrade().unwrap());
3656 }
3657 BlockParentLink(ref module, _) => {
3658 // danger, shouldn't be ident?
3659 names.push(special_idents::opaque.name);
3660 collect_mod(names, &*module.upgrade().unwrap());
3661 }
3662 }
3663 }
3664 collect_mod(&mut names, module);
3665
3666 if names.is_empty() {
3667 return "???".to_string();
3668 }
3669 names_to_string(&names.into_iter().rev().collect::<Vec<ast::Name>>())
3670 }
3671
3672
3673 pub struct CrateMap {
3674 pub def_map: DefMap,
3675 pub freevars: RefCell<FreevarMap>,
3676 pub export_map: ExportMap,
3677 pub trait_map: TraitMap,
3678 pub external_exports: ExternalExports,
3679 pub glob_map: Option<GlobMap>
3680 }
3681
3682 #[derive(PartialEq,Copy, Clone)]
3683 pub enum MakeGlobMap {
3684 Yes,
3685 No
3686 }
3687
3688 /// Entry point to crate resolution.
3689 pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
3690 ast_map: &'a ast_map::Map<'tcx>,
3691 make_glob_map: MakeGlobMap)
3692 -> CrateMap {
3693 let krate = ast_map.krate();
3694 let mut resolver = Resolver::new(session, ast_map, krate.span, make_glob_map);
3695
3696 build_reduced_graph::build_reduced_graph(&mut resolver, krate);
3697 session.abort_if_errors();
3698
3699 resolve_imports::resolve_imports(&mut resolver);
3700 session.abort_if_errors();
3701
3702 record_exports::record(&mut resolver);
3703 session.abort_if_errors();
3704
3705 resolver.resolve_crate(krate);
3706 session.abort_if_errors();
3707
3708 check_unused::check_crate(&mut resolver, krate);
3709
3710 CrateMap {
3711 def_map: resolver.def_map,
3712 freevars: resolver.freevars,
3713 export_map: resolver.export_map,
3714 trait_map: resolver.trait_map,
3715 external_exports: resolver.external_exports,
3716 glob_map: if resolver.make_glob_map {
3717 Some(resolver.glob_map)
3718 } else {
3719 None
3720 },
3721 }
3722 }
3723
3724 __build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }