From b49da276b307a58c7b3e5d5332fa32bccfb32f77 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Thu, 6 Sep 2018 19:24:33 +1200 Subject: [PATCH] Store a resolved def on hir::PathSegment --- src/librustc/hir/lowering.rs | 14 +- src/librustc/hir/mod.rs | 5 +- src/librustc/ich/impls_hir.rs | 1 + src/librustc_resolve/build_reduced_graph.rs | 51 +++--- src/librustc_resolve/lib.rs | 171 ++++++++++++-------- src/librustc_resolve/macros.rs | 24 ++- src/librustc_resolve/resolve_imports.rs | 25 +-- src/libsyntax/ast.rs | 2 +- 8 files changed, 182 insertions(+), 111 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index afb5f23db5b83..23004d8035c64 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -143,8 +143,13 @@ pub struct LoweringContext<'a> { } pub trait Resolver { - /// Resolve a hir path generated by the lowerer when expanding `for`, `if let`, etc. - fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool); + /// Resolve a path generated by the lowerer when expanding `for`, `if let`, etc. + fn resolve_hir_path( + &mut self, + path: &ast::Path, + args: Option>, + is_value: bool, + ) -> hir::Path; /// Obtain the resolution for a node id fn get_resolution(&mut self, id: NodeId) -> Option; @@ -163,7 +168,7 @@ pub trait Resolver { span: Span, crate_root: Option<&str>, components: &[&str], - params: Option>, + args: Option>, is_value: bool, ) -> hir::Path; } @@ -1380,6 +1385,7 @@ impl<'a> LoweringContext<'a> { // does not actually exist in the AST. lctx.items.insert(exist_ty_id.node_id, exist_ty_item); + let def = Def::Existential(DefId::local(exist_ty_def_index)); // `impl Trait` now just becomes `Foo<'a, 'b, ..>` hir::TyKind::Def(hir::ItemId { id: exist_ty_id.node_id }, lifetimes) }) @@ -1852,8 +1858,10 @@ impl<'a> LoweringContext<'a> { } } + let def = self.expect_full_def(segment.id); hir::PathSegment::new( segment.ident, + Some(def), generic_args, infer_types, ) diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index d5de6197a2e48..e3c8f1eadf198 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -347,6 +347,7 @@ impl fmt::Display for Path { pub struct PathSegment { /// The identifier portion of this path segment. pub ident: Ident, + pub def: Option, /// Type/lifetime parameters attached to this path. They come in /// two flavors: `Path` and `Path(A,B) -> C`. Note that @@ -367,14 +368,16 @@ impl PathSegment { pub fn from_ident(ident: Ident) -> PathSegment { PathSegment { ident, + def: None, infer_types: true, args: None, } } - pub fn new(ident: Ident, args: GenericArgs, infer_types: bool) -> Self { + pub fn new(ident: Ident, def: Option, args: GenericArgs, infer_types: bool) -> Self { PathSegment { ident, + def, infer_types, args: if args.is_empty() { None diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index a48bd4eeb09a3..f30cb365eb7f4 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -174,6 +174,7 @@ impl_stable_hash_for!(struct hir::Path { impl_stable_hash_for!(struct hir::PathSegment { ident -> (ident.name), + def, infer_types, args }); diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index aa7bfeae5f48b..3164f3a83f04f 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -141,7 +141,7 @@ impl<'a, 'cl> Resolver<'a, 'cl> { let prefix_iter = || parent_prefix.iter().cloned() .chain(use_tree.prefix.segments.iter().map(|seg| seg.ident)); let prefix_start = prefix_iter().next(); - let starts_with_non_keyword = prefix_start.map_or(false, |ident| { + let starts_with_non_keyword = prefix_start.map_or(false, |(ident, _)| { !ident.is_path_segment_keyword() }); @@ -202,13 +202,13 @@ impl<'a, 'cl> Resolver<'a, 'cl> { let source = prefix_start.unwrap(); // Helper closure to emit a canary with the given base path. - let emit = |this: &mut Self, base: Option| { + let emit = |this: &mut Self, base: Option<(Ident, Option)>| { let subclass = SingleImport { target: Ident { name: keywords::Underscore.name().gensymed(), - span: source.span, + span: source.0.span, }, - source, + source: source.0, result: PerNS { type_ns: Cell::new(Err(Undetermined)), value_ns: Cell::new(Err(Undetermined)), @@ -219,7 +219,7 @@ impl<'a, 'cl> Resolver<'a, 'cl> { this.add_import_directive( base.into_iter().collect(), subclass.clone(), - source.span, + source.0.span, id, root_use_tree.span, root_id, @@ -230,15 +230,15 @@ impl<'a, 'cl> Resolver<'a, 'cl> { }; // A single simple `self::x` canary. - emit(self, Some(Ident { + emit(self, Some((Ident { name: keywords::SelfValue.name(), - span: source.span, - })); + span: source.0.span, + }, source.1))); // One special unprefixed canary per block scope around // the import, to detect items unreachable by `self::x`. let orig_current_module = self.current_module; - let mut span = source.span.modern(); + let mut span = source.0.span.modern(); loop { match self.current_module.kind { ModuleKind::Block(..) => emit(self, None), @@ -265,10 +265,10 @@ impl<'a, 'cl> Resolver<'a, 'cl> { if nested { // Correctly handle `self` - if source.name == keywords::SelfValue.name() { + if source.0.name == keywords::SelfValue.name() { type_ns_only = true; - let empty_prefix = module_path.last().map_or(true, |ident| { + let empty_prefix = module_path.last().map_or(true, |(ident, _)| { ident.name == keywords::CrateRoot.name() }); if empty_prefix { @@ -284,20 +284,20 @@ impl<'a, 'cl> Resolver<'a, 'cl> { // Replace `use foo::self;` with `use foo;` source = module_path.pop().unwrap(); if rename.is_none() { - ident = source; + ident = source.0; } } } else { // Disallow `self` - if source.name == keywords::SelfValue.name() { + if source.0.name == keywords::SelfValue.name() { resolve_error(self, use_tree.span, ResolutionError::SelfImportsOnlyAllowedWithin); } // Disallow `use $crate;` - if source.name == keywords::DollarCrate.name() && module_path.is_empty() { - let crate_root = self.resolve_crate_root(source); + if source.0.name == keywords::DollarCrate.name() && module_path.is_empty() { + let crate_root = self.resolve_crate_root(source.0); let crate_name = match crate_root.kind { ModuleKind::Def(_, name) => name, ModuleKind::Block(..) => unreachable!(), @@ -307,11 +307,11 @@ impl<'a, 'cl> Resolver<'a, 'cl> { // while the current crate doesn't have a valid `crate_name`. if crate_name != keywords::Invalid.name() { // `crate_name` should not be interpreted as relative. - module_path.push(Ident { + module_path.push((Ident { name: keywords::CrateRoot.name(), - span: source.span, - }); - source.name = crate_name; + span: source.0.span, + }, Some(self.session.next_node_id()))); + source.0.name = crate_name; } if rename.is_none() { ident.name = crate_name; @@ -332,7 +332,7 @@ impl<'a, 'cl> Resolver<'a, 'cl> { let subclass = SingleImport { target: ident, - source, + source: source.0, result: PerNS { type_ns: Cell::new(Err(Undetermined)), value_ns: Cell::new(Err(Undetermined)), @@ -393,6 +393,17 @@ impl<'a, 'cl> Resolver<'a, 'cl> { } for &(ref tree, id) in items { + let prefix = ast::Path { + segments: module_path.iter() + .map(|ident| { + let mut seg = ast::PathSegment::from_ident(ident.0); + seg.id = self.session.next_node_id(); + seg + }) + .collect(), + span: path.span, + }; + self.build_reduced_graph_for_use_tree( root_use_tree, root_id, diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 2c21067bd58c8..96ebd82df3a32 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -1534,8 +1534,13 @@ impl<'a, 'b: 'a, 'cl: 'b> ty::DefIdTree for &'a Resolver<'b, 'cl> { /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that /// the resolver is no longer needed as all the relevant information is inline. impl<'a, 'cl> hir::lowering::Resolver for Resolver<'a, 'cl> { - fn resolve_hir_path(&mut self, path: &mut hir::Path, is_value: bool) { - self.resolve_hir_path_cb(path, is_value, + fn resolve_hir_path( + &mut self, + path: &ast::Path, + args: Option>, + is_value: bool, + ) -> hir::Path { + self.resolve_hir_path_cb(path, args, is_value, |resolver, span, error| resolve_error(resolver, span, error)) } @@ -1547,30 +1552,20 @@ impl<'a, 'cl> hir::lowering::Resolver for Resolver<'a, 'cl> { args: Option>, is_value: bool ) -> hir::Path { - let mut segments = iter::once(keywords::CrateRoot.ident()) + let segments = iter::once(keywords::CrateRoot.ident()) .chain( crate_root.into_iter() .chain(components.iter().cloned()) .map(Ident::from_str) - ).map(hir::PathSegment::from_ident).collect::>(); + ).map(|i| self.new_ast_path_segment(i)).collect::>(); - if let Some(args) = args { - let ident = segments.last().unwrap().ident; - *segments.last_mut().unwrap() = hir::PathSegment { - ident, - args: Some(args), - infer_types: true, - }; - } - let mut path = hir::Path { + let path = ast::Path { span, - def: Def::Err, - segments: segments.into(), + segments, }; - self.resolve_hir_path(&mut path, is_value); - path + self.resolve_hir_path(&path, args, is_value) } fn get_resolution(&mut self, id: NodeId) -> Option { @@ -1596,23 +1591,27 @@ impl<'a, 'crateloader> Resolver<'a, 'crateloader> { use std::iter; let mut errored = false; - let mut path = if path_str.starts_with("::") { - hir::Path { + let path = if path_str.starts_with("::") { + ast::Path { span, - def: Def::Err, - segments: iter::once(keywords::CrateRoot.ident()).chain({ - path_str.split("::").skip(1).map(Ident::from_str) - }).map(hir::PathSegment::from_ident).collect(), + segments: iter::once(keywords::CrateRoot.ident()) + .chain({ + path_str.split("::").skip(1).map(Ident::from_str) + }) + .map(|i| self.new_ast_path_segment(i)) + .collect(), } } else { - hir::Path { + ast::Path { span, - def: Def::Err, - segments: path_str.split("::").map(Ident::from_str) - .map(hir::PathSegment::from_ident).collect(), + segments: path_str + .split("::") + .map(Ident::from_str) + .map(|i| self.new_ast_path_segment(i)) + .collect(), } }; - self.resolve_hir_path_cb(&mut path, is_value, |_, _, _| errored = true); + let path = self.resolve_hir_path_cb(&path, None, is_value, |_, _, _| errored = true); if errored || path.def == Def::Err { Err(()) } else { @@ -1621,16 +1620,23 @@ impl<'a, 'crateloader> Resolver<'a, 'crateloader> { } /// resolve_hir_path, but takes a callback in case there was an error - fn resolve_hir_path_cb(&mut self, path: &mut hir::Path, is_value: bool, error_callback: F) + fn resolve_hir_path_cb( + &mut self, + path: &ast::Path, + args: Option>, + is_value: bool, + error_callback: F, + ) -> hir::Path where F: for<'c, 'b> FnOnce(&'c mut Resolver, Span, ResolutionError<'b>) { let namespace = if is_value { ValueNS } else { TypeNS }; - let hir::Path { ref segments, span, ref mut def } = *path; - let path: Vec<_> = segments.iter().map(|seg| seg.ident).collect(); + let span = path.span; + let segments = &path.segments; + let path: Vec<_> = segments.iter().map(|seg| (seg.ident, Some(seg.id))).collect(); // FIXME (Manishearth): Intra doc links won't get warned of epoch changes - match self.resolve_path(None, &path, Some(namespace), true, span, CrateLint::No) { + let def = match self.resolve_path(None, &path, Some(namespace), true, span, CrateLint::No) { PathResult::Module(ModuleOrUniformRoot::Module(module)) => - *def = module.def().unwrap(), + module.def().unwrap(), PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => *def = path_res.base_def(), PathResult::NonModule(..) => @@ -1648,9 +1654,28 @@ impl<'a, 'crateloader> Resolver<'a, 'crateloader> { PathResult::Indeterminate => unreachable!(), PathResult::Failed(span, msg, _) => { error_callback(self, span, ResolutionError::FailedToResolve(&msg)); + Def::Err } + }; + + let mut segments: Vec<_> = segments.iter().map(|seg| { + let mut hir_seg = hir::PathSegment::from_ident(seg.ident); + hir_seg.def = Some(self.def_map.get(&seg.id).map_or(Def::Err, |p| p.base_def())); + hir_seg + }).collect(); + segments.last_mut().unwrap().args = args; + hir::Path { + span, + def, + segments: segments.into(), } } + + fn new_ast_path_segment(&self, ident: Ident) -> ast::PathSegment { + let mut seg = ast::PathSegment::from_ident(ident); + seg.id = self.session.next_node_id(); + seg + } } impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { @@ -2458,7 +2483,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { let mut new_id = None; if let Some(trait_ref) = opt_trait_ref { let path: Vec<_> = trait_ref.path.segments.iter() - .map(|seg| seg.ident) + .map(|seg| (seg.ident, Some(seg.id))) .collect(); let def = self.smart_resolve_path_fragment( trait_ref.ref_id, @@ -2956,7 +2981,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { crate_lint: CrateLint ) -> PathResolution { let segments = &path.segments.iter() - .map(|seg| seg.ident) + .map(|seg| (seg.ident, Some(seg.id))) .collect::>(); self.smart_resolve_path_fragment(id, qself, segments, path.span, source, crate_lint) } @@ -2964,12 +2989,12 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { fn smart_resolve_path_fragment(&mut self, id: NodeId, qself: Option<&QSelf>, - path: &[Ident], + path: &[(Ident, Option)], span: Span, source: PathSource, crate_lint: CrateLint) -> PathResolution { - let ident_span = path.last().map_or(span, |ident| ident.span); + let ident_span = path.last().map_or(span, |ident| ident.0.span); let ns = source.namespace(); let is_expected = &|def| source.is_expected(def); let is_enum_variant = &|def| if let Def::Variant(..) = def { true } else { false }; @@ -2979,17 +3004,17 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { // Make the base error. let expected = source.descr_expected(); let path_str = names_to_string(path); - let item_str = path.last().unwrap(); + let item_str = path.last().unwrap().0; let code = source.error_code(def.is_some()); let (base_msg, fallback_label, base_span) = if let Some(def) = def { (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str), format!("not a {}", expected), span) } else { - let item_span = path.last().unwrap().span; + let item_span = path.last().unwrap().0.span; let (mod_prefix, mod_str) = if path.len() == 1 { (String::new(), "this scope".to_string()) - } else if path.len() == 2 && path[0].name == keywords::CrateRoot.name() { + } else if path.len() == 2 && path[0].0.name == keywords::CrateRoot.name() { (String::new(), "the crate root".to_string()) } else { let mod_path = &path[..path.len() - 1]; @@ -2999,7 +3024,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { module.def(), _ => None, }.map_or(String::new(), |def| format!("{} ", def.kind_name())); - (mod_prefix, format!("`{}`", names_to_string(mod_path))) + (mod_prefix, format!("`{}`", names_and_ids_to_string(mod_path))) }; (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str), format!("not found in {}", mod_str), @@ -3045,7 +3070,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { } // Try to lookup the name in more relaxed fashion for better error reporting. - let ident = *path.last().unwrap(); + let ident = path.last().unwrap().0; let candidates = this.lookup_import_candidates(ident.name, ns, is_expected); if candidates.is_empty() && is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) { let enum_candidates = @@ -3072,7 +3097,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { } if path.len() == 1 && this.self_type_is_available(span) { if let Some(candidate) = this.lookup_assoc_candidate(ident, ns, is_expected) { - let self_is_available = this.self_value_is_available(path[0].span, span); + let self_is_available = this.self_value_is_available(path[0].0.span, span); match candidate { AssocSuggestion::Field => { err.span_suggestion_with_applicability( @@ -3307,7 +3332,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { // or `::A::B`. If `B` should be resolved in value namespace then // it needs to be added to the trait map. if ns == ValueNS { - let item_name = *path.last().unwrap(); + let item_name = path.last().unwrap().0; let traits = self.get_traits_containing_item(item_name, ns); self.trait_map.insert(id, traits); } @@ -3377,7 +3402,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { fn resolve_qpath_anywhere(&mut self, id: NodeId, qself: Option<&QSelf>, - path: &[Ident], + path: &[(Ident, Option)], primary_ns: Namespace, span: Span, defer_to_typeck: bool, @@ -3399,10 +3424,10 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { } } if primary_ns != MacroNS && - (self.macro_names.contains(&path[0].modern()) || - self.builtin_macros.get(&path[0].name).cloned() + (self.macro_names.contains(&path[0].0.modern()) || + self.builtin_macros.get(&path[0].0.name).cloned() .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang) || - self.macro_use_prelude.get(&path[0].name).cloned() + self.macro_use_prelude.get(&path[0].0.name).cloned() .and_then(NameBinding::macro_kind) == Some(MacroKind::Bang)) { // Return some dummy definition, it's enough for error reporting. return Some( @@ -3416,7 +3441,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { fn resolve_qpath(&mut self, id: NodeId, qself: Option<&QSelf>, - path: &[Ident], + path: &[(Ident, Option)], ns: Namespace, span: Span, global_by_default: bool, @@ -3506,8 +3531,8 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { PathResult::Failed(..) if (ns == TypeNS || path.len() > 1) && self.primitive_type_table.primitive_types - .contains_key(&path[0].name) => { - let prim = self.primitive_type_table.primitive_types[&path[0].name]; + .contains_key(&path[0].0.name) => { + let prim = self.primitive_type_table.primitive_types[&path[0].0.name]; PathResolution::with_unresolved_segments(Def::PrimTy(prim), path.len() - 1) } PathResult::Module(ModuleOrUniformRoot::Module(module)) => @@ -3522,8 +3547,8 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { }; if path.len() > 1 && !global_by_default && result.base_def() != Def::Err && - path[0].name != keywords::CrateRoot.name() && - path[0].name != keywords::DollarCrate.name() { + path[0].0.name != keywords::CrateRoot.name() && + path[0].0.name != keywords::DollarCrate.name() { let unqualified_result = { match self.resolve_path( None, @@ -3551,7 +3576,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { fn resolve_path( &mut self, base_module: Option>, - path: &[Ident], + path: &[(Ident, Option)], opt_ns: Option, // `None` indicates a module path record_used: bool, path_span: Span, @@ -3587,7 +3612,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { crate_lint, ); - for (i, &ident) in path.iter().enumerate() { + for (i, &(ident, id)) in path.iter().enumerate() { debug!("resolve_path ident {} {:?}", i, ident); let is_last = i == path.len() - 1; let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS }; @@ -3648,7 +3673,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { } else { format!("`{}`", name) }; - let msg = if i == 1 && path[0].name == keywords::CrateRoot.name() { + let msg = if i == 1 && path[0].0.name == keywords::CrateRoot.name() { format!("global paths cannot start with {}", name_str) } else { format!("{} in paths can only be used in start position", name_str) @@ -3688,6 +3713,12 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(def); if let Some(next_module) = binding.module() { module = Some(ModuleOrUniformRoot::Module(next_module)); + if !is_last && record_used { + if let Some(id) = id { + assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id"); + self.record_def(id, PathResolution::new(def)); + } + } } else if def == Def::ToolMod && i + 1 != path.len() { let def = Def::NonMacroAttr(NonMacroAttrKind::Tool); return PathResult::NonModule(PathResolution::new(def)); @@ -3737,7 +3768,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { } else if i == 0 { format!("Use of undeclared type or module `{}`", ident) } else { - format!("Could not find `{}` in `{}`", ident, path[i - 1]) + format!("Could not find `{}` in `{}`", ident, path[i - 1].0) }; return PathResult::Failed(ident.span, msg, is_last); } @@ -3755,7 +3786,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { fn lint_if_path_starts_with_module( &self, crate_lint: CrateLint, - path: &[Ident], + path: &[(Ident, Option)], path_span: Span, second_binding: Option<&NameBinding>, ) { @@ -3772,7 +3803,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { }; let first_name = match path.get(0) { - Some(ident) => ident.name, + Some(ident) => ident.0.name, None => return, }; @@ -3784,7 +3815,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { match path.get(1) { // If this import looks like `crate::...` it's already good - Some(ident) if ident.name == keywords::Crate.name() => return, + Some((ident, _)) if ident.name == keywords::Crate.name() => return, // Otherwise go below to see if it's an extern crate Some(_) => {} // If the path has length one (and it's `CrateRoot` most likely) @@ -3977,7 +4008,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { } fn lookup_typo_candidate(&mut self, - path: &[Ident], + path: &[(Ident, Option)], ns: Namespace, filter_fn: FilterFn, span: Span) @@ -4041,7 +4072,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { } } - let name = path[path.len() - 1].name; + let name = path[path.len() - 1].0.name; // Make sure error reporting is deterministic. names.sort_by_cached_key(|name| name.as_str()); match find_best_match_for_name(names.iter(), &name.as_str(), None) { @@ -4558,7 +4589,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { ast::VisibilityKind::Restricted { ref path, id, .. } => { // Visibilities are resolved as global by default, add starting root segment. let segments = path.make_root().iter().chain(path.segments.iter()) - .map(|seg| seg.ident) + .map(|seg| (seg.ident, Some(seg.id))) .collect::>(); let def = self.smart_resolve_path_fragment( id, @@ -4851,12 +4882,12 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { } } -fn is_self_type(path: &[Ident], namespace: Namespace) -> bool { - namespace == TypeNS && path.len() == 1 && path[0].name == keywords::SelfType.name() +fn is_self_type(path: &[(Ident, Option)], namespace: Namespace) -> bool { + namespace == TypeNS && path.len() == 1 && path[0].0.name == keywords::SelfType.name() } -fn is_self_value(path: &[Ident], namespace: Namespace) -> bool { - namespace == ValueNS && path.len() == 1 && path[0].name == keywords::SelfValue.name() +fn is_self_value(path: &[(Ident, Option)], namespace: Namespace) -> bool { + namespace == ValueNS && path.len() == 1 && path[0].0.name == keywords::SelfValue.name() } fn names_to_string(idents: &[Ident]) -> String { @@ -4872,6 +4903,12 @@ fn names_to_string(idents: &[Ident]) -> String { result } +fn names_and_ids_to_string(segments: &[(Ident, Option)]) -> String { + names_to_string(&segments.iter() + .map(|seg| seg.0) + .collect::>()) +} + fn path_names_to_string(path: &Path) -> String { names_to_string(&path.segments.iter() .map(|seg| seg.ident) diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index 3345e01a929c7..f462542f1d3e0 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -462,13 +462,13 @@ impl<'a, 'cl> Resolver<'a, 'cl> { force: bool, ) -> Result { let ast::Path { ref segments, span } = *path; - let mut path: Vec<_> = segments.iter().map(|seg| seg.ident).collect(); + let mut path: Vec<_> = segments.iter().map(|seg| (seg.ident, Some(seg.id))).collect(); // Possibly apply the macro helper hack if kind == MacroKind::Bang && path.len() == 1 && - path[0].span.ctxt().outer().expn_info().map_or(false, |info| info.local_inner_macros) { - let root = Ident::new(keywords::DollarCrate.name(), path[0].span); - path.insert(0, root); + path[0].0.span.ctxt().outer().expn_info().map_or(false, |info| info.local_inner_macros) { + let root = Ident::new(keywords::DollarCrate.name(), path[0].0.span); + path.insert(0, (root, None)); } if path.len() > 1 { @@ -496,12 +496,16 @@ impl<'a, 'cl> Resolver<'a, 'cl> { }; parent_scope.module.macro_resolutions.borrow_mut() - .push((path.into_boxed_slice(), span)); + .push((path + .iter() + .map(|(ident, _)| *ident) + .collect::>() + .into_boxed_slice(), span)); def } else { let binding = self.early_resolve_ident_in_lexical_scope( - path[0], MacroNS, Some(kind), parent_scope, false, force, span + path[0].0, MacroNS, Some(kind), parent_scope, false, force, span ); match binding { Ok(..) => {} @@ -510,7 +514,7 @@ impl<'a, 'cl> Resolver<'a, 'cl> { } parent_scope.module.legacy_macro_resolutions.borrow_mut() - .push((path[0], kind, parent_scope.clone(), binding.ok())); + .push((path[0].0, kind, parent_scope.clone(), binding.ok())); binding.map(|binding| binding.def_ignoring_ambiguity()) } @@ -846,6 +850,10 @@ impl<'a, 'cl> Resolver<'a, 'cl> { pub fn finalize_current_module_macro_resolutions(&mut self) { let module = self.current_module; for &(ref path, span) in module.macro_resolutions.borrow().iter() { + let path = path + .iter() + .map(|ident| (*ident, None)) + .collect::)>>(); match self.resolve_path(None, &path, Some(MacroNS), true, span, CrateLint::No) { PathResult::NonModule(_) => {}, PathResult::Failed(span, msg, _) => { @@ -938,7 +946,7 @@ impl<'a, 'cl> Resolver<'a, 'cl> { } }; let ident = Ident::new(Symbol::intern(name), span); - self.lookup_typo_candidate(&[ident], MacroNS, is_macro, span) + self.lookup_typo_candidate(&[(ident, None)], MacroNS, is_macro, span) }); if let Some(suggestion) = suggestion { diff --git a/src/librustc_resolve/resolve_imports.rs b/src/librustc_resolve/resolve_imports.rs index 6c73f1bd0f8c5..4d3a67d4a892e 100644 --- a/src/librustc_resolve/resolve_imports.rs +++ b/src/librustc_resolve/resolve_imports.rs @@ -14,7 +14,7 @@ use {AmbiguityError, CrateLint, Module, ModuleOrUniformRoot, PerNS}; use Namespace::{self, TypeNS, MacroNS}; use {NameBinding, NameBindingKind, ToNameBinding, PathResult, PrivacyError}; use Resolver; -use {names_to_string, module_to_string}; +use {names_to_string, names_and_ids_to_string, module_to_string}; use {resolve_error, ResolutionError}; use rustc_data_structures::ptr_key::PtrKey; @@ -89,7 +89,7 @@ pub struct ImportDirective<'a> { pub root_span: Span, pub parent: Module<'a>, - pub module_path: Vec, + pub module_path: Vec<(Ident, Option)>, /// The resolution of `module_path`. pub imported_module: Cell>>, pub subclass: ImportDirectiveSubclass<'a>, @@ -393,7 +393,7 @@ impl<'a, 'crateloader> Resolver<'a, 'crateloader> { // Add an import directive to the current module. pub fn add_import_directive(&mut self, - module_path: Vec, + module_path: Vec<(Ident, Option)>, subclass: ImportDirectiveSubclass<'a>, span: Span, id: NodeId, @@ -679,7 +679,7 @@ impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> { let has_explicit_self = !import.module_path.is_empty() && - import.module_path[0].name == keywords::SelfValue.name(); + import.module_path[0].0.name == keywords::SelfValue.name(); self.per_ns(|_, ns| { if let Some(result) = result[ns].get().ok() { @@ -728,9 +728,11 @@ impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> { self.throw_unresolved_import_error(empty_vec, None); } if !seen_spans.contains(&span) { - let path = import_path_to_string(&import.module_path[..], - &import.subclass, - span); + let path = import_path_to_string( + &import.module_path.iter().map(|(ident, _)| *ident).collect::>(), + &import.subclass, + span, + ); error_vec.push((span, path, err)); seen_spans.insert(span); prev_root_id = import.root_id; @@ -851,7 +853,7 @@ impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> { /// If successful, the resolved bindings are written into the module. fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool { debug!("(resolving import for module) resolving import `{}::...` in `{}`", - names_to_string(&directive.module_path[..]), + names_and_ids_to_string(&directive.module_path[..]), module_to_string(self.current_module).unwrap_or_else(|| "???".to_string())); self.current_module = directive.parent; @@ -982,7 +984,7 @@ impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> { // HACK(eddyb) `lint_if_path_starts_with_module` needs at least // 2 segments, so the `resolve_path` above won't trigger it. let mut full_path = module_path.clone(); - full_path.push(keywords::Invalid.ident()); + full_path.push((keywords::Invalid.ident(), None)); self.lint_if_path_starts_with_module( directive.crate_lint(), &full_path, @@ -1146,7 +1148,7 @@ impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> { // HACK(eddyb) `lint_if_path_starts_with_module` needs at least // 2 segments, so the `resolve_path` above won't trigger it. let mut full_path = module_path.clone(); - full_path.push(ident); + full_path.push((ident, None)); self.per_ns(|this, ns| { if let Ok(binding) = result[ns].get() { this.lint_if_path_starts_with_module( @@ -1288,7 +1290,7 @@ impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> { let resolutions = imported_module.parent.expect("parent should exist") .resolutions.borrow(); let enum_path_segment_index = directive.module_path.len() - 1; - let enum_ident = directive.module_path[enum_path_segment_index]; + let enum_ident = directive.module_path[enum_path_segment_index].0; let enum_resolution = resolutions.get(&(enum_ident, TypeNS)) .expect("resolution should exist"); @@ -1311,6 +1313,7 @@ impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> { "consider making the enum public", suggestion); err.emit(); + } } } } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 7548c2988547b..d33077b336b46 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -147,7 +147,7 @@ impl PathSegment { pub fn crate_root(span: Span) -> Self { PathSegment { ident: Ident::new(keywords::CrateRoot.name(), span), - id: CRATE_NODE_ID, + id: DUMMY_NODE_ID, args: None, } }