]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/def_id.rs
Auto merge of #27273 - tshepang:claim-not-accurate, r=steveklabnik
[rust.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::ty;
12 use syntax::ast::{CrateNum, NodeId};
13 use std::fmt;
14
15 #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
16            RustcDecodable, Hash, Copy)]
17 pub struct DefId {
18     pub krate: CrateNum,
19     pub node: NodeId,
20 }
21
22 impl fmt::Debug for DefId {
23     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
24         try!(write!(f, "DefId {{ krate: {}, node: {}",
25                     self.krate, self.node));
26
27         // Unfortunately, there seems to be no way to attempt to print
28         // a path for a def-id, so I'll just make a best effort for now
29         // and otherwise fallback to just printing the crate/node pair
30         try!(ty::tls::with_opt(|opt_tcx| {
31             if let Some(tcx) = opt_tcx {
32                 try!(write!(f, " => {}", tcx.item_path_str(*self)));
33             }
34             Ok(())
35         }));
36
37         write!(f, " }}")
38     }
39 }
40
41
42 impl DefId {
43     pub fn local(id: NodeId) -> DefId {
44         DefId { krate: LOCAL_CRATE, node: id }
45     }
46
47     /// Read the node id, asserting that this def-id is krate-local.
48     pub fn local_id(&self) -> NodeId {
49         assert_eq!(self.krate, LOCAL_CRATE);
50         self.node
51     }
52
53     pub fn is_local(&self) -> bool {
54         self.krate == LOCAL_CRATE
55     }
56 }
57
58
59 /// Item definitions in the currently-compiled crate would have the CrateNum
60 /// LOCAL_CRATE in their DefId.
61 pub const LOCAL_CRATE: CrateNum = 0;
62