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 use middle::cstore::LOCAL_CRATE;
12 use middle::def_id::{DefId, DefIndex};
13 use rustc_data_structures::fnv::FnvHashMap;
15 use syntax::parse::token::InternedString;
16 use util::nodemap::NodeMap;
19 pub struct Definitions {
21 key_map: FnvHashMap<DefKey, DefIndex>,
22 node_map: NodeMap<DefIndex>,
25 /// A unique identifier that we can use to lookup a definition
26 /// precisely. It combines the index of the definition's parent (if
27 /// any) with a `DisambiguatedDefPathData`.
28 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
31 pub parent: Option<DefIndex>,
33 /// Identifier of this node.
34 pub disambiguated_data: DisambiguatedDefPathData,
37 /// Pair of `DefPathData` and an integer disambiguator. The integer is
38 /// normally 0, but in the event that there are multiple defs with the
39 /// same `parent` and `data`, we use this field to disambiguate
40 /// between them. This introduces some artificial ordering dependency
41 /// but means that if you have (e.g.) two impls for the same type in
42 /// the same module, they do get distinct def-ids.
43 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
44 pub struct DisambiguatedDefPathData {
45 pub data: DefPathData,
46 pub disambiguator: u32
49 /// For each definition, we track the following data. A definition
50 /// here is defined somewhat circularly as "something with a def-id",
51 /// but it generally corresponds to things like structs, enums, etc.
52 /// There are also some rather random cases (like const initializer
53 /// expressions) that are mostly just leftovers.
54 #[derive(Clone, Debug)]
58 /// Local ID within the HIR.
59 pub node_id: ast::NodeId,
62 pub type DefPath = Vec<DisambiguatedDefPathData>;
63 /// Root of an inlined item. We track the `DefPath` of the item within
64 /// the original crate but also its def-id. This is kind of an
65 /// augmented version of a `DefPath` that includes a `DefId`. This is
66 /// all sort of ugly but the hope is that inlined items will be going
69 /// Some of the constraints that led to the current approach:
71 /// - I don't want to have a `DefId` in the main `DefPath` because
72 /// that gets serialized for incr. comp., and when reloaded the
73 /// `DefId` is no longer valid. I'd rather maintain the invariant
74 /// that every `DefId` is valid, and a potentially outdated `DefId` is
75 /// represented as a `DefPath`.
76 /// - (We don't serialize def-paths from inlined items, so it's ok to have one here.)
77 /// - We need to be able to extract the def-id from inline items to
78 /// make the symbol name. In theory we could retrace it from the
79 /// data, but the metadata doesn't have the required indices, and I
80 /// don't want to write the code to create one just for this.
81 /// - It may be that we don't actually need `data` at all. We'll have
82 /// to see about that.
83 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
84 pub struct InlinedRootPath {
85 pub data: Vec<DisambiguatedDefPathData>,
89 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
90 pub enum DefPathData {
91 // Root: these should only be used for the root nodes, because
92 // they are treated specially by the `def_path` function.
94 InlinedRoot(Box<InlinedRootPath>),
96 // Catch-all for random DefId things like DUMMY_NODE_ID
99 // Different kinds of items and item-like things:
107 // Subportions of items
108 TypeParam(ast::Name),
109 LifetimeDef(ast::Name),
110 EnumVariant(ast::Name),
112 StructCtor, // implicit ctor for a tuple-like struct
113 Initializer, // initializer for a const
114 Binding(ast::Name), // pattern binding
116 // An external crate that does not have an `extern crate` in this
118 DetachedCrate(ast::Name),
122 pub fn new() -> Definitions {
125 key_map: FnvHashMap(),
130 pub fn len(&self) -> usize {
134 pub fn def_key(&self, index: DefIndex) -> DefKey {
135 self.data[index.as_usize()].key.clone()
138 /// Returns the path from the crate root to `index`. The root
139 /// nodes are not included in the path (i.e., this will be an
140 /// empty vector for the crate root). For an inlined item, this
141 /// will be the path of the item in the external crate (but the
142 /// path will begin with the path to the external crate).
143 pub fn def_path(&self, index: DefIndex) -> DefPath {
144 make_def_path(index, |p| self.def_key(p))
147 pub fn opt_def_index(&self, node: ast::NodeId) -> Option<DefIndex> {
148 self.node_map.get(&node).cloned()
151 pub fn opt_local_def_id(&self, node: ast::NodeId) -> Option<DefId> {
152 self.opt_def_index(node).map(DefId::local)
155 pub fn as_local_node_id(&self, def_id: DefId) -> Option<ast::NodeId> {
156 if def_id.krate == LOCAL_CRATE {
157 assert!(def_id.index.as_usize() < self.data.len());
158 Some(self.data[def_id.index.as_usize()].node_id)
164 pub fn create_def_with_parent(&mut self,
165 parent: Option<DefIndex>,
166 node_id: ast::NodeId,
169 assert!(!self.node_map.contains_key(&node_id),
170 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
173 self.data[self.node_map[&node_id].as_usize()]);
175 // Find a unique DefKey. This basically means incrementing the disambiguator
176 // until we get no match.
177 let mut key = DefKey {
179 disambiguated_data: DisambiguatedDefPathData {
185 while self.key_map.contains_key(&key) {
186 key.disambiguated_data.disambiguator += 1;
189 // Create the definition.
190 let index = DefIndex::new(self.data.len());
191 self.data.push(DefData { key: key.clone(), node_id: node_id });
192 self.node_map.insert(node_id, index);
193 self.key_map.insert(key, index);
200 pub fn as_interned_str(&self) -> InternedString {
201 use self::DefPathData::*;
211 DetachedCrate(name) |
217 // note that this does not show up in user printouts
219 InternedString::new("{{root}}")
222 // note that this does not show up in user printouts
224 InternedString::new("{{inlined-root}}")
228 InternedString::new("{{?}}")
232 InternedString::new("{{closure}}")
236 InternedString::new("{{constructor}}")
240 InternedString::new("{{initializer}}")
245 pub fn to_string(&self) -> String {
246 self.as_interned_str().to_string()
250 pub fn make_def_path<FN>(start_index: DefIndex, mut get_key: FN) -> DefPath
251 where FN: FnMut(DefIndex) -> DefKey
253 let mut result = vec![];
254 let mut index = Some(start_index);
255 while let Some(p) = index {
256 let key = get_key(p);
257 match key.disambiguated_data.data {
258 DefPathData::CrateRoot => {
259 assert!(key.parent.is_none());
262 DefPathData::InlinedRoot(ref p) => {
263 assert!(key.parent.is_none());
264 result.extend(p.iter().cloned().rev());
268 result.push(key.disambiguated_data);