]> git.proxmox.com Git - rustc.git/blob - src/librustc/middle/def_id.rs
Imported Upstream version 1.8.0+dfsg1
[rustc.git] / src / librustc / middle / def_id.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use middle::cstore::LOCAL_CRATE;
12 use middle::ty;
13 use syntax::ast::CrateNum;
14 use std::fmt;
15 use std::u32;
16
17 /// A DefIndex is an index into the hir-map for a crate, identifying a
18 /// particular definition. It should really be considered an interned
19 /// shorthand for a particular DefPath.
20 #[derive(Clone, Debug, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
21 RustcDecodable, Hash, Copy)]
22 pub struct DefIndex(u32);
23
24 impl DefIndex {
25 pub fn new(x: usize) -> DefIndex {
26 assert!(x < (u32::MAX as usize));
27 DefIndex(x as u32)
28 }
29
30 pub fn from_u32(x: u32) -> DefIndex {
31 DefIndex(x)
32 }
33
34 pub fn as_usize(&self) -> usize {
35 self.0 as usize
36 }
37
38 pub fn as_u32(&self) -> u32 {
39 self.0
40 }
41 }
42
43 /// The crate root is always assigned index 0 by the AST Map code,
44 /// thanks to `NodeCollector::new`.
45 pub const CRATE_DEF_INDEX: DefIndex = DefIndex(0);
46
47 /// A DefId identifies a particular *definition*, by combining a crate
48 /// index and a def index.
49 #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
50 RustcDecodable, Hash, Copy)]
51 pub struct DefId {
52 pub krate: CrateNum,
53 pub index: DefIndex,
54 }
55
56 impl fmt::Debug for DefId {
57 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
58 try!(write!(f, "DefId {{ krate: {:?}, node: {:?}",
59 self.krate, self.index));
60
61 // Unfortunately, there seems to be no way to attempt to print
62 // a path for a def-id, so I'll just make a best effort for now
63 // and otherwise fallback to just printing the crate/node pair
64 if self.is_local() { // (1)
65 // (1) side-step fact that not all external things have paths at
66 // the moment, such as type parameters
67 try!(ty::tls::with_opt(|opt_tcx| {
68 if let Some(tcx) = opt_tcx {
69 try!(write!(f, " => {}", tcx.item_path_str(*self)));
70 }
71 Ok(())
72 }));
73 }
74
75 write!(f, " }}")
76 }
77 }
78
79
80 impl DefId {
81 pub fn local(index: DefIndex) -> DefId {
82 DefId { krate: LOCAL_CRATE, index: index }
83 }
84
85 pub fn is_local(&self) -> bool {
86 self.krate == LOCAL_CRATE
87 }
88 }