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.
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 metadata::cstore::LOCAL_CRATE;
13 use syntax::ast::CrateNum;
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);
25 pub fn new(x: usize) -> DefIndex {
26 assert!(x < (u32::MAX as usize));
30 pub fn from_u32(x: u32) -> DefIndex {
34 pub fn as_usize(&self) -> usize {
38 pub fn as_u32(&self) -> u32 {
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);
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)]
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));
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 try!(ty::tls::with_opt(|opt_tcx| {
65 if let Some(tcx) = opt_tcx {
66 try!(write!(f, " => {}", tcx.item_path_str(*self)));
77 pub fn local(index: DefIndex) -> DefId {
78 DefId { krate: LOCAL_CRATE, index: index }
81 pub fn is_local(&self) -> bool {
82 self.krate == LOCAL_CRATE