1 // Copyright 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 //! For each definition, we track the following data. A definition
12 //! here is defined somewhat circularly as "something with a def-id",
13 //! but it generally corresponds to things like structs, enums, etc.
14 //! There are also some rather random cases (like const initializer
15 //! expressions) that are mostly just leftovers.
17 use hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE};
18 use rustc_data_structures::fx::FxHashMap;
19 use rustc_data_structures::stable_hasher::StableHasher;
20 use serialize::{Encodable, Decodable, Encoder, Decoder};
22 use std::hash::{Hash, Hasher};
24 use syntax::symbol::{Symbol, InternedString};
26 use util::nodemap::NodeMap;
28 /// The DefPathTable maps DefIndexes to DefKeys and vice versa.
29 /// Internally the DefPathTable holds a tree of DefKeys, where each DefKey
30 /// stores the DefIndex of its parent.
31 /// There is one DefPathTable for each crate.
33 pub struct DefPathTable {
34 index_to_key: Vec<DefKey>,
35 key_to_index: FxHashMap<DefKey, DefIndex>,
39 fn insert(&mut self, key: DefKey) -> DefIndex {
40 let index = DefIndex::new(self.index_to_key.len());
41 debug!("DefPathTable::insert() - {:?} <-> {:?}", key, index);
42 self.index_to_key.push(key.clone());
43 self.key_to_index.insert(key, index);
48 pub fn def_key(&self, index: DefIndex) -> DefKey {
49 self.index_to_key[index.as_usize()].clone()
53 pub fn def_index_for_def_key(&self, key: &DefKey) -> Option<DefIndex> {
54 self.key_to_index.get(key).cloned()
58 pub fn contains_key(&self, key: &DefKey) -> bool {
59 self.key_to_index.contains_key(key)
62 pub fn retrace_path(&self,
63 path_data: &[DisambiguatedDefPathData])
65 let root_key = DefKey {
67 disambiguated_data: DisambiguatedDefPathData {
68 data: DefPathData::CrateRoot,
73 let root_index = self.key_to_index
75 .expect("no root key?")
78 debug!("retrace_path: root_index={:?}", root_index);
80 let mut index = root_index;
81 for data in path_data {
82 let key = DefKey { parent: Some(index), disambiguated_data: data.clone() };
83 debug!("retrace_path: key={:?}", key);
84 match self.key_to_index.get(&key) {
85 Some(&i) => index = i,
95 impl Encodable for DefPathTable {
96 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
97 self.index_to_key.encode(s)
101 impl Decodable for DefPathTable {
102 fn decode<D: Decoder>(d: &mut D) -> Result<DefPathTable, D::Error> {
103 let index_to_key: Vec<DefKey> = Decodable::decode(d)?;
104 let key_to_index = index_to_key.iter()
106 .map(|(index, key)| (key.clone(), DefIndex::new(index)))
109 index_to_key: index_to_key,
110 key_to_index: key_to_index,
116 /// The definition table containing node definitions.
117 /// It holds the DefPathTable for local DefIds/DefPaths and it also stores a
118 /// mapping from NodeIds to local DefIds.
120 pub struct Definitions {
122 node_to_def_index: NodeMap<DefIndex>,
123 def_index_to_node: Vec<ast::NodeId>,
126 /// A unique identifier that we can use to lookup a definition
127 /// precisely. It combines the index of the definition's parent (if
128 /// any) with a `DisambiguatedDefPathData`.
129 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
132 pub parent: Option<DefIndex>,
134 /// Identifier of this node.
135 pub disambiguated_data: DisambiguatedDefPathData,
138 /// Pair of `DefPathData` and an integer disambiguator. The integer is
139 /// normally 0, but in the event that there are multiple defs with the
140 /// same `parent` and `data`, we use this field to disambiguate
141 /// between them. This introduces some artificial ordering dependency
142 /// but means that if you have (e.g.) two impls for the same type in
143 /// the same module, they do get distinct def-ids.
144 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
145 pub struct DisambiguatedDefPathData {
146 pub data: DefPathData,
147 pub disambiguator: u32
150 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
152 /// the path leading from the crate root to the item
153 pub data: Vec<DisambiguatedDefPathData>,
155 /// what krate root is this path relative to?
160 pub fn is_local(&self) -> bool {
161 self.krate == LOCAL_CRATE
164 pub fn make<FN>(krate: CrateNum,
165 start_index: DefIndex,
166 mut get_key: FN) -> DefPath
167 where FN: FnMut(DefIndex) -> DefKey
169 let mut data = vec![];
170 let mut index = Some(start_index);
172 debug!("DefPath::make: krate={:?} index={:?}", krate, index);
173 let p = index.unwrap();
174 let key = get_key(p);
175 debug!("DefPath::make: key={:?}", key);
176 match key.disambiguated_data.data {
177 DefPathData::CrateRoot => {
178 assert!(key.parent.is_none());
182 data.push(key.disambiguated_data);
188 DefPath { data: data, krate: krate }
191 pub fn to_string(&self, tcx: TyCtxt) -> String {
192 let mut s = String::with_capacity(self.data.len() * 16);
194 s.push_str(&tcx.original_crate_name(self.krate).as_str());
196 s.push_str(&tcx.crate_disambiguator(self.krate).as_str());
198 for component in &self.data {
201 component.data.as_interned_str(),
202 component.disambiguator)
209 pub fn deterministic_hash(&self, tcx: TyCtxt) -> u64 {
210 debug!("deterministic_hash({:?})", self);
211 let mut state = StableHasher::new();
212 self.deterministic_hash_to(tcx, &mut state);
216 pub fn deterministic_hash_to<H: Hasher>(&self, tcx: TyCtxt, state: &mut H) {
217 tcx.original_crate_name(self.krate).as_str().hash(state);
218 tcx.crate_disambiguator(self.krate).as_str().hash(state);
219 self.data.hash(state);
223 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
224 pub enum DefPathData {
225 // Root: these should only be used for the root nodes, because
226 // they are treated specially by the `def_path` function.
227 /// The crate root (marker)
230 // Catch-all for random DefId things like DUMMY_NODE_ID
233 // Different kinds of items and item-like things:
236 /// Something in the type NS
237 TypeNs(InternedString),
238 /// Something in the value NS
239 ValueNs(InternedString),
240 /// A module declaration
241 Module(InternedString),
243 MacroDef(InternedString),
244 /// A closure expression
247 // Subportions of items
248 /// A type parameter (generic parameter)
249 TypeParam(InternedString),
250 /// A lifetime definition
251 LifetimeDef(InternedString),
252 /// A variant of a enum
253 EnumVariant(InternedString),
255 Field(InternedString),
256 /// Implicit ctor for a tuple-like struct
258 /// Initializer for a const
261 Binding(InternedString),
262 /// An `impl Trait` type node.
267 /// Create new empty definition map.
268 pub fn new() -> Definitions {
270 table: DefPathTable {
271 index_to_key: vec![],
272 key_to_index: FxHashMap(),
274 node_to_def_index: NodeMap(),
275 def_index_to_node: vec![],
279 pub fn def_path_table(&self) -> &DefPathTable {
283 /// Get the number of definitions.
284 pub fn len(&self) -> usize {
285 self.def_index_to_node.len()
288 pub fn def_key(&self, index: DefIndex) -> DefKey {
289 self.table.def_key(index)
292 pub fn def_index_for_def_key(&self, key: DefKey) -> Option<DefIndex> {
293 self.table.def_index_for_def_key(&key)
296 /// Returns the path from the crate root to `index`. The root
297 /// nodes are not included in the path (i.e., this will be an
298 /// empty vector for the crate root). For an inlined item, this
299 /// will be the path of the item in the external crate (but the
300 /// path will begin with the path to the external crate).
301 pub fn def_path(&self, index: DefIndex) -> DefPath {
302 DefPath::make(LOCAL_CRATE, index, |p| self.def_key(p))
305 pub fn opt_def_index(&self, node: ast::NodeId) -> Option<DefIndex> {
306 self.node_to_def_index.get(&node).cloned()
309 pub fn opt_local_def_id(&self, node: ast::NodeId) -> Option<DefId> {
310 self.opt_def_index(node).map(DefId::local)
313 pub fn local_def_id(&self, node: ast::NodeId) -> DefId {
314 self.opt_local_def_id(node).unwrap()
317 pub fn as_local_node_id(&self, def_id: DefId) -> Option<ast::NodeId> {
318 if def_id.krate == LOCAL_CRATE {
319 assert!(def_id.index.as_usize() < self.def_index_to_node.len());
320 Some(self.def_index_to_node[def_id.index.as_usize()])
326 /// Add a definition with a parent definition.
327 pub fn create_def_with_parent(&mut self,
328 parent: Option<DefIndex>,
329 node_id: ast::NodeId,
332 debug!("create_def_with_parent(parent={:?}, node_id={:?}, data={:?})",
333 parent, node_id, data);
335 assert!(!self.node_to_def_index.contains_key(&node_id),
336 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
339 self.table.def_key(self.node_to_def_index[&node_id]));
341 assert_eq!(parent.is_some(), data != DefPathData::CrateRoot);
343 // Find a unique DefKey. This basically means incrementing the disambiguator
344 // until we get no match.
345 let mut key = DefKey {
347 disambiguated_data: DisambiguatedDefPathData {
353 while self.table.contains_key(&key) {
354 key.disambiguated_data.disambiguator += 1;
357 debug!("create_def_with_parent: after disambiguation, key = {:?}", key);
359 // Create the definition.
360 let index = self.table.insert(key);
361 debug!("create_def_with_parent: def_index_to_node[{:?} <-> {:?}", index, node_id);
362 self.node_to_def_index.insert(node_id, index);
363 assert_eq!(index.as_usize(), self.def_index_to_node.len());
364 self.def_index_to_node.push(node_id);
371 pub fn get_opt_name(&self) -> Option<ast::Name> {
372 use self::DefPathData::*;
378 TypeParam(ref name) |
379 LifetimeDef(ref name) |
380 EnumVariant(ref name) |
382 Field(ref name) => Some(Symbol::intern(name)),
394 pub fn as_interned_str(&self) -> InternedString {
395 use self::DefPathData::*;
396 let s = match *self {
401 TypeParam(ref name) |
402 LifetimeDef(ref name) |
403 EnumVariant(ref name) |
409 // note that this does not show up in user printouts
410 CrateRoot => "{{root}}",
414 ClosureExpr => "{{closure}}",
415 StructCtor => "{{constructor}}",
416 Initializer => "{{initializer}}",
417 ImplTrait => "{{impl-Trait}}",
420 Symbol::intern(s).as_str()
423 pub fn to_string(&self) -> String {
424 self.as_interned_str().to_string()