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.
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.
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")]
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/")]
22 #![feature(associated_consts)]
24 #![feature(rustc_diagnostic_macros)]
25 #![feature(rustc_private)]
26 #![feature(slice_extras)]
27 #![feature(staged_api)]
29 #[macro_use] extern crate log;
30 #[macro_use] extern crate syntax;
31 #[macro_use] #[no_link] extern crate rustc_bitflags;
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
::*;
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
::*;
53 use rustc
::session
::Session
;
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
;
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
;
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}
;
88 use syntax
::codemap
::{self, Span, Pos}
;
89 use syntax
::visit
::{self, Visitor}
;
91 use std
::collections
::{HashMap, HashSet}
;
92 use std
::collections
::hash_map
::Entry
::{Occupied, Vacant}
;
93 use std
::cell
::{Cell, RefCell}
;
95 use std
::mem
::replace
;
96 use std
::rc
::{Rc, Weak}
;
99 use resolve_imports
::{Target, ImportDirective, ImportResolution}
;
100 use resolve_imports
::Shadowable
;
103 // NB: This module needs to be declared first so diagnostics are
104 // registered before they are used.
109 mod build_reduced_graph
;
112 #[derive(Copy, Clone)]
115 binding_mode
: BindingMode
,
118 // Map from the name in a pattern to its binding mode.
119 type BindingMap
= HashMap
<Name
, BindingInfo
>;
121 #[derive(Copy, Clone, PartialEq)]
122 enum PatternBindingMode
{
124 LocalIrrefutableMode
,
125 ArgumentIrrefutableMode
,
128 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
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.
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.)
143 /// Means that resolve has determined that the name is definitely
144 /// not bound in the namespace.
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
>)
151 impl NamespaceResult
{
152 fn is_unknown(&self) -> bool
{
154 UnknownResult
=> true,
158 fn is_unbound(&self) -> bool
{
160 UnboundResult
=> true,
166 enum NameDefinition
{
167 // The name was unbound.
169 // The name identifies an immediate child.
170 ChildNameDefinition(Def
, LastPrivate
),
171 // The name identifies an import.
172 ImportNameDefinition(Def
, LastPrivate
),
175 impl<'a
, 'v
, 'tcx
> Visitor
<'v
> for Resolver
<'a
, 'tcx
> {
176 fn visit_item(&mut self, item
: &Item
) {
177 self.resolve_item(item
);
179 fn visit_arm(&mut self, arm
: &Arm
) {
180 self.resolve_arm(arm
);
182 fn visit_block(&mut self, block
: &Block
) {
183 self.resolve_block(block
);
185 fn visit_expr(&mut self, expr
: &Expr
) {
186 self.resolve_expr(expr
);
188 fn visit_local(&mut self, local
: &Local
) {
189 self.resolve_local(local
);
191 fn visit_ty(&mut self, ty
: &Ty
) {
192 self.resolve_type(ty
);
194 fn visit_generics(&mut self, generics
: &Generics
) {
195 self.resolve_generics(generics
);
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 */ }
204 visit
::walk_poly_trait_ref(self, tref
, m
);
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
);
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
);
221 ast
::StructVariantKind(ref struct_definition
) => {
222 self.visit_struct_def(&**struct_definition
,
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
)
234 ForeignItemStatic(..) => NoTypeParameters
236 self.with_type_parameter_rib(type_parameters
, |this
| {
237 visit
::walk_foreign_item(this
, foreign_item
);
240 fn visit_fn(&mut self,
241 function_kind
: visit
::FnKind
<'v
>,
242 declaration
: &'v FnDecl
,
246 let rib_kind
= match function_kind
{
247 visit
::FkItemFn(_
, generics
, _
, _
, _
, _
) => {
248 self.visit_generics(generics
);
251 visit
::FkMethod(_
, sig
, _
) => {
252 self.visit_generics(&sig
.generics
);
253 self.visit_explicit_self(&sig
.explicit_self
);
256 visit
::FkFnBlock(..) => ClosureRibKind(node_id
)
258 self.resolve_function(rib_kind
, declaration
, block
);
262 type ErrorMessage
= Option
<(Span
, String
)>;
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.
270 impl<T
> ResolveResult
<T
> {
271 fn indeterminate(&self) -> bool
{
272 match *self { Indeterminate => true, _ => false }
276 enum FallbackSuggestion
{
281 StaticMethod(String
),
285 #[derive(Copy, Clone)]
286 enum TypeParameters
<'a
> {
292 // Identifies the things that these parameters
293 // were declared on (type, fn, etc)
296 // The kind of the rib used for type parameters.
300 // The rib kind controls the translation of local
301 // definitions (`DefLocal`) to upvars (`DefUpvar`).
302 #[derive(Copy, Clone, Debug)]
304 // No translation needs to be applied.
307 // We passed through a closure scope at the given node ID.
308 // Translate upvars as appropriate.
309 ClosureRibKind(NodeId
/* func id */),
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
317 // We passed through an item scope. Disallow upvars.
320 // We're in a constant item. Can't refer to dynamic stuff.
324 #[derive(Copy, Clone)]
325 enum UseLexicalScopeFlag
{
330 enum ModulePrefixResult
{
332 PrefixFound(Rc
<Module
>, usize)
335 #[derive(Copy, Clone)]
336 enum AssocItemResolveResult
{
337 /// Syntax such as `<T>::item`, which can't be resolved until type
340 /// We should have been able to resolve the associated item.
341 ResolveAttempt(Option
<PathResolution
>),
344 #[derive(Copy, Clone, PartialEq)]
345 enum NameSearchType
{
346 /// We're doing a name search in order to resolve a `use` directive.
349 /// We're doing a name search in order to resolve a path type, a path
350 /// expression, or a path pattern.
354 #[derive(Copy, Clone)]
355 enum BareIdentifierPatternResolution
{
356 FoundStructOrEnumVariant(Def
, LastPrivate
),
357 FoundConst(Def
, LastPrivate
),
358 BareIdentifierPatternUnresolved
364 bindings
: HashMap
<Name
, DefLike
>,
369 fn new(kind
: RibKind
) -> Rib
{
371 bindings
: HashMap
::new(),
377 /// The link from a module up to its nearest parent node.
378 #[derive(Clone,Debug)]
381 ModuleParentLink(Weak
<Module
>, Name
),
382 BlockParentLink(Weak
<Module
>, NodeId
)
385 /// The type of module this is.
386 #[derive(Copy, Clone, PartialEq, Debug)]
395 /// One node in the tree of modules.
397 parent_link
: ParentLink
,
398 def_id
: Cell
<Option
<DefId
>>,
399 kind
: Cell
<ModuleKind
>,
402 children
: RefCell
<HashMap
<Name
, Rc
<NameBindings
>>>,
403 imports
: RefCell
<Vec
<ImportDirective
>>,
405 // The external module children of this node that were declared with
407 external_module_children
: RefCell
<HashMap
<Name
, Rc
<Module
>>>,
409 // The anonymous children of this node. Anonymous children are pseudo-
410 // modules that are implicitly created around items contained within
413 // For example, if we have this:
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
>>>,
425 // The status of resolving each import in this module.
426 import_resolutions
: RefCell
<HashMap
<Name
, ImportResolution
>>,
428 // The number of unresolved globs that this module exports.
429 glob_count
: Cell
<usize>,
431 // The index of the import we're resolving.
432 resolved_import_count
: Cell
<usize>,
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
>,
441 fn new(parent_link
: ParentLink
,
442 def_id
: Option
<DefId
>,
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
),
463 fn all_imports_resolved(&self) -> bool
{
464 self.imports
.borrow().len() == self.resolved_import_count
.get()
468 impl fmt
::Debug
for Module
{
469 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
470 write
!(f
, "{:?}, kind: {:?}, {}",
473 if self.is_public { "public" }
else { "private" }
)
479 flags DefModifiers
: u8 {
480 const PUBLIC
= 1 << 0,
481 const IMPORTABLE
= 1 << 1,
485 // Records a possibly-private type definition.
486 #[derive(Clone,Debug)]
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
>
494 // Records a possibly-private value definition.
495 #[derive(Clone, Copy, Debug)]
497 modifiers
: DefModifiers
, // see note in ImportResolution about how to use this
499 value_span
: Option
<Span
>,
502 // Records the definitions (at most one for each namespace) that a name is
505 pub struct NameBindings
{
506 type_def
: RefCell
<Option
<TypeNsDef
>>, //< Meaning in type namespace.
507 value_def
: RefCell
<Option
<ValueNsDef
>>, //< Meaning in value namespace.
511 fn new() -> NameBindings
{
513 type_def
: RefCell
::new(None
),
514 value_def
: RefCell
::new(None
),
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
>,
526 // Merges the module with the existing type def or creates a new one.
527 let modifiers
= if is_public
{
530 DefModifiers
::empty()
531 } | DefModifiers
::IMPORTABLE
;
532 let module_
= Rc
::new(Module
::new(parent_link
,
537 let type_def
= self.type_def
.borrow().clone();
540 *self.type_def
.borrow_mut() = Some(TypeNsDef
{
541 modifiers
: modifiers
,
542 module_def
: Some(module_
),
548 *self.type_def
.borrow_mut() = Some(TypeNsDef
{
549 modifiers
: modifiers
,
550 module_def
: Some(module_
),
552 type_def
: type_def
.type_def
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
>,
566 let modifiers
= if is_public
{
569 DefModifiers
::empty()
570 } | DefModifiers
::IMPORTABLE
;
571 let type_def
= self.type_def
.borrow().clone();
574 let module
= Module
::new(parent_link
,
579 *self.type_def
.borrow_mut() = Some(TypeNsDef
{
580 modifiers
: modifiers
,
581 module_def
: Some(Rc
::new(module
)),
587 match type_def
.module_def
{
589 let module
= Module
::new(parent_link
,
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
,
601 Some(module_def
) => module_def
.kind
.set(kind
),
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();
614 *self.type_def
.borrow_mut() = Some(TypeNsDef
{
618 modifiers
: modifiers
,
622 *self.type_def
.borrow_mut() = Some(TypeNsDef
{
623 module_def
: type_def
.module_def
,
626 modifiers
: modifiers
,
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
{
637 value_span
: Some(sp
),
638 modifiers
: modifiers
,
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(),
650 /// Returns the module node. Panics if this node does not have a module
652 fn get_module(&self) -> Rc
<Module
> {
653 match self.get_module_if_available() {
655 panic
!("get_module called on a node with no module \
658 Some(module_def
) => module_def
662 fn defined_in_namespace(&self, namespace
: Namespace
) -> bool
{
664 TypeNS
=> return self.type_def
.borrow().is_some(),
665 ValueNS
=> return self.value_def
.borrow().is_some()
669 fn defined_in_public_namespace(&self, namespace
: Namespace
) -> bool
{
670 self.defined_in_namespace_with(namespace
, DefModifiers
::PUBLIC
)
673 fn defined_in_namespace_with(&self, namespace
: Namespace
, modifiers
: DefModifiers
) -> bool
{
675 TypeNS
=> match *self.type_def
.borrow() {
676 Some(ref def
) => def
.modifiers
.contains(modifiers
), None
=> false
678 ValueNS
=> match *self.value_def
.borrow() {
679 Some(ref def
) => def
.modifiers
.contains(modifiers
), None
=> false
684 fn def_for_namespace(&self, namespace
: Namespace
) -> Option
<Def
> {
687 match *self.type_def
.borrow() {
689 Some(ref type_def
) => {
690 match type_def
.type_def
{
691 Some(type_def
) => Some(type_def
),
693 match type_def
.module_def
{
694 Some(ref module
) => {
695 match module
.def_id
.get() {
696 Some(did
) => Some(DefMod(did
)),
708 match *self.value_def
.borrow() {
710 Some(value_def
) => Some(value_def
.def
)
716 fn span_for_namespace(&self, namespace
: Namespace
) -> Option
<Span
> {
717 if self.defined_in_namespace(namespace
) {
720 match *self.type_def
.borrow() {
722 Some(ref type_def
) => type_def
.type_span
726 match *self.value_def
.borrow() {
728 Some(ref value_def
) => value_def
.value_span
737 fn is_public(&self, namespace
: Namespace
) -> bool
{
740 let type_def
= self.type_def
.borrow();
741 type_def
.as_ref().unwrap().modifiers
.contains(DefModifiers
::PUBLIC
)
744 let value_def
= self.value_def
.borrow();
745 value_def
.as_ref().unwrap().modifiers
.contains(DefModifiers
::PUBLIC
)
751 /// Interns the names of the primitive types.
752 struct PrimitiveTypeTable
{
753 primitive_types
: HashMap
<Name
, PrimTy
>,
756 impl PrimitiveTypeTable
{
757 fn new() -> PrimitiveTypeTable
{
758 let mut table
= PrimitiveTypeTable
{
759 primitive_types
: HashMap
::new()
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
));
781 fn intern(&mut self, string
: &str, primitive_type
: PrimTy
) {
782 self.primitive_types
.insert(token
::intern(string
), primitive_type
);
786 /// The main resolver class.
787 pub struct Resolver
<'a
, 'tcx
:'a
> {
788 session
: &'a Session
,
790 ast_map
: &'a ast_map
::Map
<'tcx
>,
792 graph_root
: NameBindings
,
794 trait_item_map
: FnvHashMap
<(Name
, DefId
), DefId
>,
796 structs
: FnvHashMap
<DefId
, Vec
<Name
>>,
798 // The number of imports that are currently unresolved.
799 unresolved_imports
: usize,
801 // The module that represents the current item scope.
802 current_module
: Rc
<Module
>,
804 // The current set of local scopes, for values.
805 // FIXME #4948: Reuse ribs to avoid allocation.
806 value_ribs
: Vec
<Rib
>,
808 // The current set of local scopes, for types.
811 // The current set of local scopes, for labels.
812 label_ribs
: Vec
<Rib
>,
814 // The trait that the current context can refer to.
815 current_trait_ref
: Option
<(DefId
, TraitRef
)>,
817 // The current self type if inside an impl (used for better errors).
818 current_self_type
: Option
<Ty
>,
820 // The idents for the primitive types.
821 primitive_type_table
: PrimitiveTypeTable
,
824 freevars
: RefCell
<FreevarMap
>,
825 freevars_seen
: RefCell
<NodeMap
<NodeSet
>>,
826 export_map
: ExportMap
,
828 external_exports
: ExternalExports
,
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
836 // Maps imports to the names of items actually imported (this actually maps
837 // all imports, but only glob imports are actually interesting).
840 used_imports
: HashSet
<(NodeId
, Namespace
)>,
841 used_crates
: HashSet
<CrateNum
>,
845 enum FallbackChecks
{
850 impl<'a
, 'tcx
> Resolver
<'a
, 'tcx
> {
851 fn new(session
: &'a Session
,
852 ast_map
: &'a ast_map
::Map
<'tcx
>,
854 make_glob_map
: MakeGlobMap
) -> Resolver
<'a
, 'tcx
> {
855 let graph_root
= NameBindings
::new();
857 graph_root
.define_module(NoParentLink
,
858 Some(DefId { krate: 0, node: 0 }
),
864 let current_module
= graph_root
.get_module();
871 // The outermost module has def ID 0; this is not reflected in the
874 graph_root
: graph_root
,
876 trait_item_map
: FnvHashMap(),
877 structs
: FnvHashMap(),
879 unresolved_imports
: 0,
881 current_module
: current_module
,
882 value_ribs
: Vec
::new(),
883 type_ribs
: Vec
::new(),
884 label_ribs
: Vec
::new(),
886 current_trait_ref
: None
,
887 current_self_type
: None
,
889 primitive_type_table
: PrimitiveTypeTable
::new(),
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(),
901 make_glob_map
: make_glob_map
== MakeGlobMap
::Yes
,
902 glob_map
: HashMap
::new(),
907 fn record_import_use(&mut self, import_id
: NodeId
, name
: Name
) {
908 if !self.make_glob_map
{
911 if self.glob_map
.contains_key(&import_id
) {
912 self.glob_map
.get_mut(&import_id
).unwrap().insert(name
);
916 let mut new_set
= HashSet
::new();
917 new_set
.insert(name
);
918 self.glob_map
.insert(import_id
, new_set
);
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
925 csearch
::get_trait_name(&self.session
.cstore
, did
)
929 fn create_name_bindings_from_module(module
: Rc
<Module
>) -> NameBindings
{
931 type_def
: RefCell
::new(Some(TypeNsDef
{
932 modifiers
: DefModifiers
::IMPORTABLE
,
933 module_def
: Some(module
),
937 value_def
: RefCell
::new(None
),
941 /// Checks that the names of external crates don't collide with other
943 fn check_for_conflicts_between_external_crates(&self,
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
));
955 /// Checks that the names of items don't collide with external crates.
956 fn check_for_conflicts_between_external_crates_and_items(&self,
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 \
965 &token
::get_name(name
));
969 /// Resolves the given module path from the given root `module_`.
970 fn resolve_module_path_from_root(&mut self,
972 module_path
: &[Name
],
975 name_search_type
: NameSearchType
,
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())
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
;
996 // Resolve the module part of the path. This does not involve looking
997 // upward though scope chains; we simply resolve names directly in
999 while index
< module_path_len
{
1000 let name
= module_path
[index
];
1001 match self.resolve_name_in_module(search_module
.clone(),
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());
1013 match search_parent_externals(name
,
1014 &self.current_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
);
1021 let prefix
= if target_mod_str
== current_mod_str
{
1022 "self::".to_string()
1024 format
!("{}::", target_mod_str
)
1027 format
!("Did you mean `{}{}`?", prefix
, path_str
)
1029 None
=> format
!("Maybe a missing `extern crate {}`?",
1033 format
!("Could not find `{}` in `{}`",
1038 return Failed(Some((span
, msg
)));
1040 Failed(err
) => return Failed(err
),
1042 debug
!("(resolving module path for import) module \
1043 resolution is indeterminate: {}",
1044 token
::get_name(name
));
1045 return Indeterminate
;
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
{
1054 let msg
= format
!("Not a module `{}`",
1055 token
::get_name(name
));
1057 return Failed(Some((span
, msg
)));
1059 Some(ref module_def
) => {
1060 search_module
= module_def
.clone();
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
);
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
));
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
)));
1091 return Success((search_module
, closest_private
));
1094 /// Attempts to resolve the module part of an import directive or path
1095 /// rooted at the given module.
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
,
1104 name_search_type
: NameSearchType
)
1105 -> ResolveResult
<(Rc
<Module
>, LastPrivate
)> {
1106 let module_path_len
= module_path
.len();
1107 assert
!(module_path_len
> 0);
1109 debug
!("(resolving module path for import) processing `{}` rooted at `{}`",
1110 names_to_string(module_path
),
1111 module_to_string(&*module_
));
1113 // Resolve the module prefix, if any.
1114 let module_prefix_result
= self.resolve_module_prefix(module_
.clone(),
1120 match module_prefix_result
{
1122 let mpath
= names_to_string(module_path
);
1123 let mpath
= &mpath
[..];
1124 match mpath
.rfind('
:'
) {
1126 let msg
= format
!("Could not find `{}` in `{}`",
1127 // idx +- 1 to account for the
1128 // colons on either side
1131 return Failed(Some((span
, msg
)));
1138 Failed(err
) => return Failed(err
),
1140 debug
!("(resolving module path for import) indeterminate; \
1142 return Indeterminate
;
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();
1154 last_private
= LastMod(AllPublic
);
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_
,
1162 Failed(err
) => return Failed(err
),
1164 debug
!("(resolving module path for import) \
1165 indeterminate; bailing");
1166 return Indeterminate
;
1168 Success(containing_module
) => {
1169 search_module
= containing_module
;
1171 last_private
= LastMod(AllPublic
);
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
1186 self.resolve_module_path_from_root(search_module
,
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
>,
1199 namespace
: Namespace
)
1200 -> ResolveResult
<(Target
, bool
)> {
1201 debug
!("(resolving item in lexical scope) resolving `{}` in \
1202 namespace {:?} in `{}`",
1203 token
::get_name(name
),
1205 module_to_string(&*module_
));
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_
);
1211 match module_
.children
.borrow().get(&name
) {
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(),
1220 Some(_
) | None
=> { /* Not found; continue. */ }
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
1227 if let Some(import_resolution
) = module_
.import_resolutions
.borrow().get(&name
) {
1228 match (*import_resolution
).target_for_namespace(namespace
) {
1230 // Not found; continue.
1231 debug
!("(resolving item in lexical scope) found \
1232 import resolution, but not in namespace {:?}",
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
);
1245 return Success((target
, false));
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
{
1256 Rc
::new(Resolver
::create_name_bindings_from_module(module
));
1257 debug
!("lower name bindings succeeded");
1258 return Success((Target
::new(module_
,
1265 // Finally, proceed up the scope chain looking for parent modules.
1266 let mut search_module
= module_
;
1268 // Go to the next parent.
1269 match search_module
.parent_link
.clone() {
1271 // No more parents. This module was unresolved.
1272 debug
!("(resolving item in lexical scope) unresolved \
1274 return Failed(None
);
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 \
1284 return Failed(None
);
1289 AnonymousModuleKind
=> {
1290 search_module
= parent_module_node
.upgrade().unwrap();
1294 BlockParentLink(ref parent_module_node
, _
) => {
1295 search_module
= parent_module_node
.upgrade().unwrap();
1299 // Resolve the name in the parent module.
1300 match self.resolve_name_in_module(search_module
.clone(),
1305 Failed(Some((span
, msg
))) =>
1306 self.resolve_error(span
, &format
!("failed to resolve. {}",
1308 Failed(None
) => (), // Continue up the search chain.
1310 // We couldn't see through the higher scope because of an
1311 // unresolved import higher up. Bail.
1313 debug
!("(resolving item in lexical scope) indeterminate \
1314 higher scope; bailing");
1315 return Indeterminate
;
1317 Success((target
, used_reexport
)) => {
1318 // We found the module.
1319 debug
!("(resolving item in lexical scope) found name \
1321 return Success((target
, used_reexport
));
1327 /// Resolves a module name in the current lexical scope.
1328 fn resolve_module_in_lexical_scope(&mut self,
1329 module_
: Rc
<Module
>,
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
{
1342 debug
!("!!! (resolving module in lexical \
1343 scope) module wasn't actually a \
1345 return Failed(None
);
1347 Some(ref module_def
) => {
1348 return Success(module_def
.clone());
1353 debug
!("!!! (resolving module in lexical scope) module
1354 wasn't actually a module!");
1355 return Failed(None
);
1360 debug
!("(resolving module in lexical scope) indeterminate; \
1362 return Indeterminate
;
1365 debug
!("(resolving module in lexical scope) failed to resolve");
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_
;
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
),
1386 AnonymousModuleKind
=> module_
= new_module
,
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
>)
1397 match module_
.kind
.get() {
1398 NormalModuleKind
=> return module_
,
1402 AnonymousModuleKind
=> {
1403 match self.get_nearest_normal_module_parent(module_
.clone()) {
1405 Some(new_module
) => new_module
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
;
1422 let first_module_path_string
= token
::get_name(module_path
[0]);
1423 if "self" == &first_module_path_string
[..] {
1425 self.get_nearest_normal_module_parent_or_self(module_
);
1427 } else if "super" == &first_module_path_string
[..] {
1429 self.get_nearest_normal_module_parent_or_self(module_
);
1430 i
= 0; // We'll handle `super` below.
1432 return Success(NoPrefixFound
);
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
[..] {
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
;
1452 debug
!("(resolving module prefix) finished resolving prefix at {}",
1453 module_to_string(&*containing_module
));
1455 return Success(PrefixFound(containing_module
, i
));
1458 /// Attempts to resolve the supplied name in the given module for the
1459 /// given namespace. If successful, returns the target corresponding to
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
>,
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_
));
1475 // First, check the direct children of the module.
1476 build_reduced_graph
::populate_module_if_necessary(self, &module_
);
1478 match module_
.children
.borrow().get(&name
) {
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(),
1492 // Next, check the module's imports if necessary.
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);
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
=> {
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
;
1511 match import_resolution
.target_for_namespace(namespace
) {
1513 debug
!("(resolving name in module) name found, \
1514 but not in namespace {:?}",
1518 debug
!("(resolving name in module) resolved to \
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
);
1527 return Success((target
, true));
1531 Some(..) | None
=> {}
// Continue.
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
{
1540 Rc
::new(Resolver
::create_name_bindings_from_module(module
));
1541 return Success((Target
::new(module_
,
1548 // We're out of luck.
1549 debug
!("(resolving name in module) failed to resolve `{}`",
1550 &token
::get_name(name
));
1551 return Failed(None
);
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
1561 .span_to_snippet((*imports
)[index
].span
)
1563 if sn
.contains("::") {
1564 self.resolve_error((*imports
)[index
].span
,
1565 "unresolved import");
1567 let err
= format
!("unresolved import (maybe you meant `{}::*`?)",
1569 self.resolve_error((*imports
)[index
].span
, &err
[..]);
1573 // Descend into children and anonymous children.
1574 build_reduced_graph
::populate_module_if_necessary(self, &module_
);
1576 for (_
, child_node
) in module_
.children
.borrow().iter() {
1577 match child_node
.get_module_if_available() {
1581 Some(child_module
) => {
1582 self.report_unresolved_imports(child_module
);
1587 for (_
, module_
) in module_
.anonymous_children
.borrow().iter() {
1588 self.report_unresolved_imports(module_
.clone());
1594 // We maintain a list of value ribs and type ribs.
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
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.
1610 fn with_scope
<F
>(&mut self, name
: Option
<Name
>, f
: F
) where
1611 F
: FnOnce(&mut Resolver
),
1613 let orig_module
= self.current_module
.clone();
1615 // Move down in the graph.
1621 build_reduced_graph
::populate_module_if_necessary(self, &orig_module
);
1623 match orig_module
.children
.borrow().get(&name
) {
1625 debug
!("!!! (with scope) didn't find `{}` in `{}`",
1626 token
::get_name(name
),
1627 module_to_string(&*orig_module
));
1629 Some(name_bindings
) => {
1630 match (*name_bindings
).get_module_if_available() {
1632 debug
!("!!! (with scope) didn't find module \
1634 token
::get_name(name
),
1635 module_to_string(&*orig_module
));
1638 self.current_module
= module_
;
1648 self.current_module
= orig_module
;
1651 /// Wraps the given definition in the appropriate number of `DefUpvar`
1657 -> Option
<DefLike
> {
1658 let mut def
= match def_like
{
1660 _
=> return Some(def_like
)
1664 self.session
.span_bug(span
,
1665 &format
!("unexpected {:?} in bindings", def
))
1667 DefLocal(node_id
) => {
1671 // Nothing to do. Continue.
1673 ClosureRibKind(function_id
) => {
1675 def
= DefUpvar(node_id
, function_id
);
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()),
1682 if seen
.contains(&node_id
) {
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
);
1691 ItemRibKind
| MethodRibKind
=> {
1692 // This was an attempt to access an upvar inside a
1693 // named function item. This is not allowed, so we
1696 self.resolve_error(span
,
1697 "can't capture dynamic environment in a fn item; \
1698 use the || { ... } closure form instead");
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");
1711 DefTyParam(..) | DefSelfTy(..) => {
1714 NormalRibKind
| MethodRibKind
| ClosureRibKind(..) => {
1715 // Nothing to do. Continue.
1718 // This was an attempt to use a type parameter outside
1721 self.resolve_error(span
,
1722 "can't use type parameters from \
1723 outer function; try using a local \
1724 type parameter instead");
1727 ConstantItemRibKind
=> {
1729 self.resolve_error(span
,
1730 "cannot use an outer type \
1731 parameter in this context");
1742 /// Searches the current set of local scopes and
1743 /// applies translations for closures.
1744 fn search_ribs(&self,
1748 -> Option
<DefLike
> {
1749 // FIXME #4950: Try caching?
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
);
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() {
1769 // Do not resolve labels across function boundary
1773 let result
= rib
.bindings
.get(&name
).cloned();
1774 if result
.is_some() {
1781 fn resolve_crate(&mut self, krate
: &ast
::Crate
) {
1782 debug
!("(resolving crate) starting");
1784 visit
::walk_crate(self, krate
);
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");
1794 fn resolve_item(&mut self, item
: &Item
) {
1795 let name
= item
.ident
.name
;
1797 debug
!("(resolving item) resolving {}",
1798 token
::get_name(name
));
1801 ItemEnum(_
, ref generics
) |
1802 ItemTy(_
, ref generics
) |
1803 ItemStruct(_
, ref generics
) => {
1804 self.check_if_primitive_type_name(name
, item
.span
);
1806 self.with_type_parameter_rib(HasTypeParameters(generics
,
1809 |this
| visit
::walk_item(this
, item
));
1811 ItemFn(_
, _
, _
, _
, ref generics
, _
) => {
1812 self.with_type_parameter_rib(HasTypeParameters(generics
,
1815 |this
| visit
::walk_item(this
, item
));
1818 ItemDefaultImpl(_
, ref trait_ref
) => {
1819 self.with_optional_trait_ref(Some(trait_ref
), |_
, _
| {}
);
1826 ref impl_items
) => {
1827 self.resolve_implementation(generics
,
1834 ItemTrait(_
, ref generics
, ref bounds
, ref trait_items
) => {
1835 self.check_if_primitive_type_name(name
, item
.span
);
1837 // Create a new rib for the trait-wide type parameters.
1838 self.with_type_parameter_rib(HasTypeParameters(generics
,
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
);
1846 for trait_item
in trait_items
{
1847 // Create a new rib for the trait_item-specific type
1850 // FIXME #4951: Do we need a node ID here?
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
)
1862 visit
::walk_trait_item(this
, trait_item
)
1865 ast
::MethodTraitItem(ref sig
, _
) => {
1866 let type_parameters
=
1867 HasTypeParameters(&sig
.generics
,
1870 this
.with_type_parameter_rib(type_parameters
, |this
| {
1871 visit
::walk_trait_item(this
, trait_item
)
1874 ast
::TypeTraitItem(..) => {
1875 this
.check_if_primitive_type_name(trait_item
.ident
.name
,
1877 this
.with_type_parameter_rib(NoTypeParameters
, |this
| {
1878 visit
::walk_trait_item(this
, trait_item
)
1887 ItemMod(_
) | ItemForeignMod(_
) => {
1888 self.with_scope(Some(name
), |this
| {
1889 visit
::walk_item(this
, item
);
1893 ItemConst(..) | ItemStatic(..) => {
1894 self.with_constant_rib(|this
| {
1895 visit
::walk_item(this
, item
);
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
);
1911 ItemExternCrate(_
) | ItemMac(..) => {
1912 // do nothing, these are just around to be encoded
1917 fn with_type_parameter_rib
<F
>(&mut self, type_parameters
: TypeParameters
, f
: F
) where
1918 F
: FnOnce(&mut Resolver
),
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
);
1928 if seen_bindings
.contains(&name
) {
1929 self.resolve_error(type_parameter
.span
,
1930 &format
!("the name `{}` is already \
1932 parameter in this type \
1934 token
::get_name(name
)))
1936 seen_bindings
.insert(name
);
1938 // plain insert (no renaming)
1939 function_type_rib
.bindings
.insert(name
,
1940 DlDef(DefTyParam(space
,
1942 local_def(type_parameter
.id
),
1945 self.type_ribs
.push(function_type_rib
);
1948 NoTypeParameters
=> {
1955 match type_parameters
{
1956 HasTypeParameters(..) => { self.type_ribs.pop(); }
1957 NoTypeParameters
=> { }
1961 fn with_label_rib
<F
>(&mut self, f
: F
) where
1962 F
: FnOnce(&mut Resolver
),
1964 self.label_ribs
.push(Rib
::new(NormalRibKind
));
1966 self.label_ribs
.pop();
1969 fn with_constant_rib
<F
>(&mut self, f
: F
) where
1970 F
: FnOnce(&mut Resolver
),
1972 self.value_ribs
.push(Rib
::new(ConstantItemRibKind
));
1973 self.type_ribs
.push(Rib
::new(ConstantItemRibKind
));
1975 self.type_ribs
.pop();
1976 self.value_ribs
.pop();
1979 fn resolve_function(&mut self,
1981 declaration
: &FnDecl
,
1983 // Create a value rib for the function.
1984 self.value_ribs
.push(Rib
::new(rib_kind
));
1986 // Create a label rib for the function.
1987 self.label_ribs
.push(Rib
::new(rib_kind
));
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
);
1996 self.visit_ty(&*argument
.ty
);
1998 debug
!("(resolving function) recorded argument");
2000 visit
::walk_fn_ret_ty(self, &declaration
.output
);
2002 // Resolve the function body.
2003 self.visit_block(&*block
);
2005 debug
!("(resolving function) leaving function");
2007 self.label_ribs
.pop();
2008 self.value_ribs
.pop();
2011 fn resolve_trait_reference(&mut self,
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
);
2021 self.resolve_error(trait_path
.span
,
2022 &format
!("`{}` is not a trait",
2023 path_names_to_string(trait_path
, path_depth
)));
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");
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
);
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
);
2044 for predicate
in &generics
.where_clause
.predicates
{
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());
2053 self.resolve_error(eq_pred
.path
.span
, "undeclared associated type");
2058 visit
::walk_generics(self, generics
);
2061 fn with_current_self_type
<T
, F
>(&mut self, self_type
: &Ty
, f
: F
) -> T
2062 where F
: FnOnce(&mut Resolver
) -> T
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
;
2071 fn with_optional_trait_ref
<T
, F
>(&mut self,
2072 opt_trait_ref
: Option
<&TraitRef
>,
2075 where F
: FnOnce(&mut Resolver
, Option
<DefId
>) -> T
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());
2087 visit
::walk_trait_ref(self, trait_ref
);
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
;
2095 fn with_self_rib
<F
>(&mut self, self_def
: Def
, f
: F
)
2096 where F
: FnOnce(&mut Resolver
)
2098 let mut self_type_rib
= Rib
::new(NormalRibKind
);
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
);
2105 self.type_ribs
.pop();
2108 fn resolve_implementation(&mut self,
2109 generics
: &Generics
,
2110 opt_trait_reference
: &Option
<TraitRef
>,
2113 impl_items
: &[P
<ImplItem
>]) {
2114 // If applicable, create a rib for the type parameters.
2115 self.with_type_parameter_rib(HasTypeParameters(generics
,
2119 // Resolve the type parameters.
2120 this
.visit_generics(generics
);
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
);
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
2134 this
.check_trait_item(impl_item
.ident
.name
,
2136 this
.with_constant_rib(|this
| {
2137 visit
::walk_impl_item(this
, impl_item
);
2140 MethodImplItem(ref sig
, _
) => {
2141 // If this is a trait impl, ensure the method
2143 this
.check_trait_item(impl_item
.ident
.name
,
2146 // We also need a new scope for the method-
2147 // specific type parameters.
2148 let type_parameters
=
2149 HasTypeParameters(&sig
.generics
,
2152 this
.with_type_parameter_rib(type_parameters
, |this
| {
2153 visit
::walk_impl_item(this
, impl_item
);
2156 TypeImplItem(ref ty
) => {
2157 // If this is a trait impl, ensure the method
2159 this
.check_trait_item(impl_item
.ident
.name
,
2164 ast
::MacImplItem(_
) => {}
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
),
2186 fn resolve_local(&mut self, local
: &Local
) {
2187 // Resolve the type.
2188 visit
::walk_ty_opt(self, &local
.ty
);
2190 // Resolve the initializer.
2191 visit
::walk_expr_opt(self, &local
.init
);
2193 // Resolve the pattern.
2194 self.resolve_pattern(&*local
.pat
,
2195 LocalIrrefutableMode
,
2196 &mut HashMap
::new());
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
{
2209 binding_mode
: binding_mode
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() {
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
);
2225 for (&key
, &binding_0
) in &map_0
{
2226 match map_i
.get(&key
) {
2230 &format
!("variable `{}` from pattern #1 is \
2231 not bound in pattern #{}",
2232 token
::get_name(key
),
2235 Some(binding_i
) => {
2236 if binding_0
.binding_mode
!= binding_i
.binding_mode
{
2239 &format
!("variable `{}` is bound with different \
2240 mode in pattern #{} than in pattern #1",
2241 token
::get_name(key
),
2248 for (&key
, &binding
) in &map_i
{
2249 if !map_0
.contains_key(&key
) {
2252 &format
!("variable `{}` from pattern {}{} is \
2253 not bound in pattern {}1",
2254 token
::get_name(key
),
2261 fn resolve_arm(&mut self, arm
: &Arm
) {
2262 self.value_ribs
.push(Rib
::new(NormalRibKind
));
2264 let mut bindings_list
= HashMap
::new();
2265 for pattern
in &arm
.pats
{
2266 self.resolve_pattern(&**pattern
, RefutableMode
, &mut bindings_list
);
2269 // This has to happen *after* we determine which
2270 // pat_idents are variants
2271 self.check_consistent_bindings(arm
);
2273 visit
::walk_expr_opt(self, &arm
.guard
);
2274 self.visit_expr(&*arm
.body
);
2276 self.value_ribs
.pop();
2279 fn resolve_block(&mut self, block
: &Block
) {
2280 debug
!("(resolving block) entering block");
2281 self.value_ribs
.push(Rib
::new(NormalRibKind
));
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 \
2290 self.current_module
= anonymous_module
.clone();
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
{
2300 ItemExternCrate(_
) | ItemUse(_
) if found_non_item
=> {
2301 span_err
!(self.session
, i
.span
, E0154
,
2302 "imports are not allowed after non-item statements");
2307 found_non_item
= true
2310 found_non_item
= true;
2314 // Descend into the block.
2315 visit
::walk_block(self, block
);
2318 self.current_module
= orig_module
;
2320 self.value_ribs
.pop();
2321 debug
!("(resolving block) leaving block");
2324 fn resolve_type(&mut self, ty
: &Ty
) {
2326 TyPath(ref maybe_qself
, ref path
) => {
2328 match self.resolve_possibly_assoc_item(ty
.id
,
2329 maybe_qself
.as_ref(),
2333 // `<T>::a::b::c` is resolved by typeck alone.
2334 TypecheckRequired
=> {
2335 // Resolve embedded types.
2336 visit
::walk_ty(self, ty
);
2339 ResolveAttempt(resolution
) => resolution
,
2342 // This is a path in the type namespace. Walk through scopes
2346 // Write the result into the def map.
2347 debug
!("(resolving type) writing resolution for `{}` \
2349 path_names_to_string(path
, 0),
2351 self.record_def(ty
.id
, def
);
2354 // Keep reporting some errors even if they're ignored above.
2355 self.resolve_path(ty
.id
, path
, 0, TypeNS
, true);
2357 let kind
= if maybe_qself
.is_some() {
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()
2371 format
!("use of undeclared {} `{}`",
2372 kind
, path_names_to_string(path
, 0))
2375 self.resolve_error(ty
.span
, &msg
[..]);
2381 // Resolve embedded types.
2382 visit
::walk_ty(self, ty
);
2385 fn resolve_pattern(&mut self,
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
, _
) => {
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
2405 let ident
= path1
.node
;
2406 let renamed
= mtwt
::resolve(ident
);
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
));
2415 self.enforce_default_binding_mode(
2419 self.record_def(pattern
.id
, PathResolution
{
2425 FoundStructOrEnumVariant(..) => {
2428 &format
!("declaration of `{}` shadows an enum \
2429 variant or unit-like struct in \
2431 token
::get_name(renamed
)));
2433 FoundConst(def
, lp
) if mode
== RefutableMode
=> {
2434 debug
!("(resolving pattern) resolving `{}` to \
2436 token
::get_name(renamed
));
2438 self.enforce_default_binding_mode(
2442 self.record_def(pattern
.id
, PathResolution
{
2449 self.resolve_error(pattern
.span
,
2450 "only irrefutable patterns \
2453 BareIdentifierPatternUnresolved
=> {
2454 debug
!("(resolving pattern) binding `{}`",
2455 token
::get_name(renamed
));
2457 let def
= DefLocal(pattern
.id
);
2459 // Record the definition so that later passes
2460 // will be able to distinguish variants from
2461 // locals in patterns.
2463 self.record_def(pattern
.id
, PathResolution
{
2465 last_private
: LastMod(AllPublic
),
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
2483 self.resolve_error(pattern
.span
,
2484 &format
!("identifier `{}` \
2492 } else if bindings_list
.get(&renamed
) ==
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 \
2500 token
::get_ident(ident
)));
2502 // Else, not bound in the same pattern: do
2508 PatEnum(ref path
, _
) => {
2509 // This must be an enum variant, struct or const.
2511 match self.resolve_possibly_assoc_item(pat_id
, None
,
2514 // The below shouldn't happen because all
2515 // qualified paths should be in PatQPath.
2516 TypecheckRequired
=>
2517 self.session
.span_bug(
2519 "resolve_possibly_assoc_item claimed
2520 that a path in PatEnum requires typecheck
2521 to resolve, but qualified paths should be
2523 ResolveAttempt(resolution
) => resolution
,
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
);
2531 self.resolve_error(path
.span
,
2532 "static variables cannot be \
2533 referenced in a pattern, \
2534 use a `const` instead");
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 {
2544 &format
!("`{}` is not an enum variant, struct or const",
2546 path
.segments
.last().unwrap().identifier
)));
2548 let const_name
= path
.segments
.last().unwrap()
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
);
2557 self.resolve_error(path
.span
,
2558 &format
!("unresolved enum variant, struct or const `{}`",
2559 token
::get_ident(path
.segments
.last().unwrap().identifier
)));
2561 visit
::walk_path(self, path
);
2564 PatQPath(ref qself
, ref path
) => {
2565 // Associated constants only.
2567 match self.resolve_possibly_assoc_item(pat_id
, Some(qself
),
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()
2576 let traits
= self.get_traits_containing_item(const_name
);
2577 self.trait_map
.insert(pattern
.id
, traits
);
2578 visit
::walk_pat(self, pattern
);
2581 ResolveAttempt(resolution
) => resolution
,
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
);
2591 self.resolve_error(path
.span
,
2592 &format
!("`{}` is not an associated const",
2594 path
.segments
.last().unwrap().identifier
)));
2598 self.resolve_error(path
.span
,
2599 &format
!("unresolved associated const `{}`",
2600 token
::get_ident(path
.segments
.last().unwrap().identifier
)));
2602 visit
::walk_pat(self, pattern
);
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
);
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
[..]);
2618 visit
::walk_path(self, path
);
2621 PatLit(_
) | PatRange(..) => {
2622 visit
::walk_pat(self, pattern
);
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
,
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() {
2646 panic
!("resolved name in the value namespace to a \
2647 set of name bindings with no 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.
2654 def @
DefVariant(..) | def @
DefStruct(..) => {
2655 return FoundStructOrEnumVariant(def
, LastMod(AllPublic
));
2657 def @
DefConst(..) | def @
DefAssociatedConst(..) => {
2658 return FoundConst(def
, LastMod(AllPublic
));
2661 self.resolve_error(span
,
2662 "static variables cannot be \
2663 referenced in a pattern, \
2664 use a `const` instead");
2665 return BareIdentifierPatternUnresolved
;
2668 return BareIdentifierPatternUnresolved
;
2676 panic
!("unexpected indeterminate result");
2680 Some((span
, msg
)) => {
2681 self.resolve_error(span
, &format
!("failed to resolve: {}",
2687 debug
!("(resolve bare identifier pattern) failed to find {}",
2688 token
::get_name(name
));
2689 return BareIdentifierPatternUnresolved
;
2694 /// Handles paths that may refer to associated items
2695 fn resolve_possibly_assoc_item(&mut self,
2697 maybe_qself
: Option
<&ast
::QSelf
>,
2699 namespace
: Namespace
,
2701 -> AssocItemResolveResult
2703 let max_assoc_types
;
2707 if qself
.position
== 0 {
2708 return TypecheckRequired
;
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
);
2715 max_assoc_types
= path
.segments
.len();
2719 let mut resolution
= self.with_no_errors(|this
| {
2720 this
.resolve_path(id
, path
, 0, namespace
, check_ribs
)
2722 for depth
in 1..max_assoc_types
{
2723 if resolution
.is_some() {
2726 self.with_no_errors(|this
| {
2727 resolution
= this
.resolve_path(id
, path
, depth
,
2731 if let Some(DefMod(_
)) = resolution
.map(|r
| r
.base_def
) {
2732 // A module is not a valid type or value.
2735 ResolveAttempt(resolution
)
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,
2746 namespace
: Namespace
,
2747 check_ribs
: bool
) -> Option
<PathResolution
> {
2748 let span
= path
.span
;
2749 let segments
= &path
.segments
[..path
.segments
.len()-path_depth
];
2751 let mk_res
= |(def
, lp
)| PathResolution
::new(def
, lp
, path_depth
);
2754 let def
= self.resolve_crate_relative_path(span
, segments
, namespace
);
2755 return def
.map(mk_res
);
2758 // Try to find a path to an item in a module.
2759 let unqualified_def
=
2760 self.resolve_identifier(segments
.last().unwrap().identifier
,
2765 if segments
.len() <= 1 {
2766 return unqualified_def
.map(mk_res
);
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
=> {
2773 .add_lint(lint
::builtin
::UNUSED_QUALIFICATIONS
,
2775 "unnecessary qualification".to_string());
2783 // Resolve a single identifier.
2784 fn resolve_identifier(&mut self,
2786 namespace
: Namespace
,
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
2794 .get(&identifier
.name
) {
2795 return Some((DefPrimTy(prim_ty
), LastMod(AllPublic
)));
2800 if let Some(def
) = self.resolve_identifier_in_local_ribs(identifier
,
2803 return Some((def
, LastMod(AllPublic
)));
2807 self.resolve_item_by_name_in_lexical_scope(identifier
.name
, namespace
)
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
>,
2814 namespace
: Namespace
)
2816 // First, search children.
2817 build_reduced_graph
::populate_module_if_necessary(self, &containing_module
);
2819 match containing_module
.children
.borrow().get(&name
) {
2820 Some(child_name_bindings
) => {
2821 match child_name_bindings
.def_for_namespace(namespace
) {
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()))
2828 return ChildNameDefinition(def
, lp
);
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
) {
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
);
2853 return ImportNameDefinition(def
, LastMod(AllPublic
));
2856 // This can happen with external impls, due to
2857 // the imperfect way we read the metadata.
2862 Some(..) | None
=> {}
// Continue.
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
))
2875 return ChildNameDefinition(DefMod(def_id
), lp
);
2880 return NoNameDefinition
;
2883 // resolve a "module-relative" path, e.g. a::b::c
2884 fn resolve_module_relative_path(&mut self,
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
<_
>>();
2893 let containing_module
;
2895 let current_module
= self.current_module
.clone();
2896 match self.resolve_module_path(current_module
,
2902 let (span
, msg
) = match err
{
2903 Some((span
, msg
)) => (span
, msg
),
2905 let msg
= format
!("Use of undeclared type or module `{}`",
2906 names_to_string(&module_path
));
2911 self.resolve_error(span
, &format
!("failed to resolve. {}",
2915 Indeterminate
=> panic
!("indeterminate unexpected"),
2916 Success((resulting_module
, resulting_last_private
)) => {
2917 containing_module
= resulting_module
;
2918 last_private
= resulting_last_private
;
2922 let name
= segments
.last().unwrap().identifier
.name
;
2923 let def
= match self.resolve_definition_of_name_in_module(containing_module
.clone(),
2926 NoNameDefinition
=> {
2927 // We failed to resolve the name. Report an error.
2930 ChildNameDefinition(def
, lp
) | ImportNameDefinition(def
, lp
) => {
2931 (def
, last_private
.or(lp
))
2934 if let Some(DefId{krate: kid, ..}
) = containing_module
.def_id
.get() {
2935 self.used_crates
.insert(kid
);
2940 /// Invariant: This must be called only during main resolution, not during
2941 /// import resolution.
2942 fn resolve_crate_relative_path(&mut self,
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
<_
>>();
2951 let root_module
= self.graph_root
.get_module();
2953 let containing_module
;
2955 match self.resolve_module_path_from_root(root_module
,
2960 LastMod(AllPublic
)) {
2962 let (span
, msg
) = match err
{
2963 Some((span
, msg
)) => (span
, msg
),
2965 let msg
= format
!("Use of undeclared module `::{}`",
2966 names_to_string(&module_path
[..]));
2971 self.resolve_error(span
, &format
!("failed to resolve. {}",
2977 panic
!("indeterminate unexpected");
2980 Success((resulting_module
, resulting_last_private
)) => {
2981 containing_module
= resulting_module
;
2982 last_private
= resulting_last_private
;
2986 let name
= segments
.last().unwrap().identifier
.name
;
2987 match self.resolve_definition_of_name_in_module(containing_module
,
2990 NoNameDefinition
=> {
2991 // We failed to resolve the name. Report an error.
2994 ChildNameDefinition(def
, lp
) | ImportNameDefinition(def
, lp
) => {
2995 return Some((def
, last_private
.or(lp
)));
3000 fn resolve_identifier_in_local_ribs(&mut self,
3002 namespace
: Namespace
,
3005 // Check the local set of ribs.
3006 let search_result
= match namespace
{
3008 let renamed
= mtwt
::resolve(ident
);
3009 self.search_ribs(&self.value_ribs
, renamed
, span
)
3012 let name
= ident
.name
;
3013 self.search_ribs(&self.type_ribs
, name
, span
)
3017 match search_result
{
3018 Some(DlDef(def
)) => {
3019 debug
!("(resolving path in local ribs) resolved `{}` to local: {:?}",
3020 token
::get_ident(ident
),
3024 Some(DlField
) | Some(DlImpl(_
)) | None
=> {
3030 fn resolve_item_by_name_in_lexical_scope(&mut self,
3032 namespace
: Namespace
)
3033 -> Option
<(Def
, LastPrivate
)> {
3035 let module
= self.current_module
.clone();
3036 match self.resolve_item_in_lexical_scope(module
,
3039 Success((target
, _
)) => {
3040 match (*target
.bindings
).def_for_namespace(namespace
) {
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
));
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
)));
3061 panic
!("unexpected indeterminate result");
3064 debug
!("(resolving item path by identifier in lexical scope) \
3065 failed to resolve {}", token
::get_name(name
));
3067 if let Some((span
, msg
)) = err
{
3068 self.resolve_error(span
, &format
!("failed to resolve. {}", msg
))
3076 fn with_no_errors
<T
, F
>(&mut self, f
: F
) -> T
where
3077 F
: FnOnce(&mut Resolver
) -> T
,
3079 self.emit_errors
= false;
3081 self.emit_errors
= true;
3085 fn resolve_error(&self, span
: Span
, s
: &str) {
3086 if self.emit_errors
{
3087 self.session
.span_err(span
, s
);
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
)> {
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.
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();
3110 if name_path
.len() == 1 {
3111 match this
.primitive_type_table
.primitive_types
.get(last_name
) {
3114 match this
.current_module
.children
.borrow().get(last_name
) {
3115 Some(child
) => child
.get_module_if_available(),
3121 match this
.resolve_module_path(root
,
3126 Success((module
, _
)) => Some(module
),
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
,
3139 ast_map
::NodeImplItem(impl_item
) => match impl_item
.node
{
3140 ast
::MethodImplItem(ref sig
, _
) => sig
,
3145 sig
.explicit_self
.node
== ast
::SelfStatic
3147 csearch
::is_static_method(&this
.session
.cstore
, did
)
3151 let (path
, node_id
, allowed
) = match self.current_self_type
{
3152 Some(ref ty
) => match extract_path_and_node_id(ty
, Everything
) {
3154 None
=> return NoSuggestion
,
3156 None
=> return NoSuggestion
,
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
) {
3167 if fields
.iter().any(|&field_name
| name
== field_name
) {
3172 _
=> {}
// Self type didn't resolve properly
3176 let name_path
= path
.segments
.iter().map(|seg
| seg
.identifier
.name
).collect
::<Vec
<_
>>();
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))
3185 if self.current_trait_ref
.is_some() {
3187 } else if allowed
== Everything
{
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));
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();
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
);
3219 let mut smallest
= 0;
3220 for (i
, other
) in maybes
.iter().enumerate() {
3221 values
[i
] = lev_distance(name
, &other
);
3223 if values
[i
] <= values
[smallest
] {
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;
3233 if !values
.is_empty() &&
3234 values
[smallest
] <= max_distance
&&
3235 name
!= &maybes
[smallest
][..] {
3237 Some(maybes
[smallest
].to_string())
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.
3248 self.record_candidate_traits_for_expr_if_necessary(expr
);
3250 // Next, resolve the node.
3252 ExprPath(ref maybe_qself
, ref path
) => {
3254 match self.resolve_possibly_assoc_item(expr
.id
,
3255 maybe_qself
.as_ref(),
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
);
3267 ResolveAttempt(resolution
) => resolution
,
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 \
3279 uses it like a function name",
3282 let msg
= format
!("did you mean to write: \
3283 `{} {{ /* fields */ }}`?",
3285 if self.emit_errors
{
3286 self.session
.fileline_help(expr
.span
, &msg
);
3288 self.session
.span_help(expr
.span
, &msg
);
3291 // Write the result into the def map.
3292 debug
!("(resolving expr) resolved `{}`",
3293 path_names_to_string(path
, 0));
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
);
3303 self.record_def(expr
.id
, path_res
);
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)
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 \
3320 uses it like a function name",
3323 let msg
= format
!("did you mean to write: \
3324 `{} {{ /* fields */ }}`?",
3326 if self.emit_errors
{
3327 self.session
.fileline_help(expr
.span
, &msg
);
3329 self.session
.span_help(expr
.span
, &msg
);
3333 // Keep reporting some errors even if they're ignored above.
3334 self.resolve_path(expr
.id
, path
, 0, ValueNS
, true);
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
3343 false // Stop advancing
3347 &token
::get_name(special_names
::self_
)[..] == path_name
{
3350 "`self` is not available \
3351 in a static method. Maybe a \
3352 `self` argument is missing?");
3354 let last_name
= path
.segments
.last().unwrap().identifier
.name
;
3355 let mut msg
= match self.find_fallback_in_self_type(last_name
) {
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
))
3363 Field
=> format
!("`self.{}`", path_name
),
3366 format
!("to call `self.{}`", path_name
),
3367 TraitMethod(path_str
) |
3368 StaticMethod(path_str
) =>
3369 format
!("to call `{}::{}`", path_str
, path_name
)
3372 if !msg
.is_empty() {
3373 msg
= format
!(". Did you mean {}?", msg
)
3378 &format
!("unresolved name `{}`{}",
3385 visit
::walk_expr(self, expr
);
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
),
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
[..]);
3402 visit
::walk_expr(self, expr
);
3405 ExprLoop(_
, Some(label
)) | ExprWhile(_
, _
, Some(label
)) => {
3406 self.with_label_rib(|this
| {
3407 let def_like
= DlDef(DefLabel(expr
.id
));
3410 let rib
= this
.label_ribs
.last_mut().unwrap();
3411 let renamed
= mtwt
::resolve(label
);
3412 rib
.bindings
.insert(renamed
, def_like
);
3415 visit
::walk_expr(this
, expr
);
3419 ExprBreak(Some(label
)) | ExprAgain(Some(label
)) => {
3420 let renamed
= mtwt
::resolve(label
);
3421 match self.search_label(renamed
) {
3425 &format
!("use of undeclared label `{}`",
3426 token
::get_ident(label
)))
3428 Some(DlDef(def @
DefLabel(_
))) => {
3429 // Since this def is a label, it is never read.
3430 self.record_def(expr
.id
, PathResolution
{
3432 last_private
: LastMod(AllPublic
),
3437 self.session
.span_bug(expr
.span
,
3438 "label wasn't mapped to a \
3445 visit
::walk_expr(self, expr
);
3450 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr
: &Expr
) {
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
);
3460 ExprMethodCall(ident
, _
, _
) => {
3461 debug
!("(recording candidate traits for expr) recording \
3464 let traits
= self.get_traits_containing_item(ident
.node
.name
);
3465 self.trait_map
.insert(expr
.id
, traits
);
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
));
3477 fn add_trait_info(found_traits
: &mut Vec
<DefId
>,
3478 trait_def_id
: DefId
,
3480 debug
!("(adding trait info) found trait {}:{} for method '{}'",
3483 token
::get_name(name
));
3484 found_traits
.push(trait_def_id
);
3487 let mut found_traits
= Vec
::new();
3488 let mut search_module
= self.current_module
.clone();
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
);
3497 None
=> {}
// Nothing to do.
3500 // Look for trait children.
3501 build_reduced_graph
::populate_module_if_necessary(self, &search_module
);
3504 for (_
, child_names
) in search_module
.children
.borrow().iter() {
3505 let def
= match child_names
.def_for_namespace(TypeNS
) {
3509 let trait_def_id
= match def
{
3510 DefTrait(trait_def_id
) => trait_def_id
,
3513 if self.trait_item_map
.contains_key(&(name
, trait_def_id
)) {
3514 add_trait_info(&mut found_traits
, trait_def_id
, name
);
3519 // Look for imports.
3520 for (_
, import
) in search_module
.import_resolutions
.borrow().iter() {
3521 let target
= match import
.target_for_namespace(TypeNS
) {
3523 Some(target
) => target
,
3525 let did
= match target
.bindings
.def_for_namespace(TypeNS
) {
3526 Some(DefTrait(trait_def_id
)) => trait_def_id
,
3527 Some(..) | None
=> continue,
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
);
3541 match search_module
.parent_link
.clone() {
3542 NoParentLink
| ModuleParentLink(..) => break,
3543 BlockParentLink(parent_module
, _
) => {
3544 search_module
= parent_module
.upgrade().unwrap();
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");
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
));
3565 fn enforce_default_binding_mode(&mut self,
3567 pat_binding_mode
: BindingMode
,
3569 match pat_binding_mode
{
3570 BindByValue(_
) => {}
3572 self.resolve_error(pat
.span
,
3573 &format
!("cannot use `ref` binding mode \
3583 // Diagnostics are not particularly efficient, because they're rarely
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_
));
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
));
3597 debug
!("Import resolutions:");
3598 let import_resolutions
= module_
.import_resolutions
.borrow();
3599 for (&name
, import_resolution
) in import_resolutions
.iter() {
3601 match import_resolution
.target_for_namespace(ValueNS
) {
3602 None
=> { value_repr = "".to_string(); }
3604 value_repr
= " value:?".to_string();
3610 match import_resolution
.target_for_namespace(TypeNS
) {
3611 None
=> { type_repr = "".to_string(); }
3613 type_repr
= " type:?".to_string();
3618 debug
!("* {}:{}{}", token
::get_name(name
), value_repr
, type_repr
);
3624 fn names_to_string(names
: &[Name
]) -> String
{
3625 let mut first
= true;
3626 let mut result
= String
::new();
3631 result
.push_str("::")
3633 result
.push_str(&token
::get_name(*name
));
3638 fn path_names_to_string(path
: &Path
, depth
: usize) -> String
{
3639 let names
: Vec
<ast
::Name
> = path
.segments
[..path
.segments
.len()-depth
]
3641 .map(|seg
| seg
.identifier
.name
)
3643 names_to_string(&names
[..])
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();
3650 fn collect_mod(names
: &mut Vec
<ast
::Name
>, module
: &Module
) {
3651 match module
.parent_link
{
3653 ModuleParentLink(ref module
, name
) => {
3655 collect_mod(names
, &*module
.upgrade().unwrap());
3657 BlockParentLink(ref module
, _
) => {
3658 // danger, shouldn't be ident?
3659 names
.push(special_idents
::opaque
.name
);
3660 collect_mod(names
, &*module
.upgrade().unwrap());
3664 collect_mod(&mut names
, module
);
3666 if names
.is_empty() {
3667 return "???".to_string();
3669 names_to_string(&names
.into_iter().rev().collect
::<Vec
<ast
::Name
>>())
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
>
3682 #[derive(PartialEq,Copy, Clone)]
3683 pub enum MakeGlobMap
{
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
)
3693 let krate
= ast_map
.krate();
3694 let mut resolver
= Resolver
::new(session
, ast_map
, krate
.span
, make_glob_map
);
3696 build_reduced_graph
::build_reduced_graph(&mut resolver
, krate
);
3697 session
.abort_if_errors();
3699 resolve_imports
::resolve_imports(&mut resolver
);
3700 session
.abort_if_errors();
3702 record_exports
::record(&mut resolver
);
3703 session
.abort_if_errors();
3705 resolver
.resolve_crate(krate
);
3706 session
.abort_if_errors();
3708 check_unused
::check_crate(&mut resolver
, krate
);
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
)
3724 __build_diagnostic_array
! { librustc_resolve, DIAGNOSTICS }