Skip to main content

rustc_public/
crate_def.rs

1//! Module that define a common trait for things that represent a crate definition,
2//! such as, a function, a trait, an enum, and any other definitions.
3
4use crate::ty::{GenericArgs, Span, Ty, index_impl};
5use crate::{Crate, Symbol, ThreadLocalIndex, with};
6
7/// A unique identification number for each item accessible for the current compilation unit.
8#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DefId {
}
#[automatically_derived]impl ::core::clone::Clone for DefId {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<usize>;
        let _: ::core::clone::AssertParamIsClone<ThreadLocalIndex>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for DefId { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for DefId { }
#[automatically_derived]impl ::core::cmp::PartialEq for DefId {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0 && self.1 == other.1
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for DefId {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<usize>;
        let _: ::core::cmp::AssertParamIsEq<ThreadLocalIndex>;
    }
}Eq, #[automatically_derived]impl ::core::hash::Hash for DefId {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state);
        ::core::hash::Hash::hash(&self.1, state)
    }
}Hash)]
9pub struct DefId(pub(crate) usize, ThreadLocalIndex);
10impl crate::IndexedVal for DefId {
    fn to_val(index: usize) -> Self { DefId(index, crate::ThreadLocalIndex) }
    fn to_index(&self) -> usize { self.0 }
}
impl ::serde::Serialize for DefId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where
        S: ::serde::Serializer {
        let n: usize = self.0;
        ::serde::Serialize::serialize(&n, serializer)
    }
}index_impl!(DefId);
11
12impl DefId {
13    /// Return fully qualified name of this definition
14    pub fn name(&self) -> Symbol {
15        with(|cx| cx.def_name(*self, false))
16    }
17
18    /// Return a trimmed name of this definition.
19    ///
20    /// This can be used to print more user friendly diagnostic messages.
21    ///
22    /// If a symbol name can only be imported from one place for a type, and as
23    /// long as it was not glob-imported anywhere in the current crate, we trim its
24    /// path and print only the name.
25    ///
26    /// For example, this function may shorten `std::vec::Vec` to just `Vec`,
27    /// as long as there is no other `Vec` importable anywhere.
28    pub fn trimmed_name(&self) -> Symbol {
29        with(|cx| cx.def_name(*self, true))
30    }
31
32    /// Return the parent of this definition, or `None` if this is the root of a
33    /// crate.
34    pub fn parent(&self) -> Option<DefId> {
35        with(|cx| cx.def_parent(*self))
36    }
37
38    pub fn span(&self) -> Span {
39        with(|cx| cx.span_of_a_def(*self))
40    }
41}
42
43/// A trait for retrieving information about a particular definition.
44///
45/// Implementors must provide the implementation of `def_id` which will be used to retrieve
46/// information about a crate's definition.
47pub trait CrateDef {
48    /// Retrieve the unique identifier for the current definition.
49    fn def_id(&self) -> DefId;
50
51    /// Return the fully qualified name of the current definition.
52    ///
53    /// See [`DefId::name`] for more details
54    fn name(&self) -> Symbol {
55        self.def_id().name()
56    }
57
58    /// Return a trimmed name of this definition.
59    ///
60    /// See [`DefId::trimmed_name`] for more details
61    fn trimmed_name(&self) -> Symbol {
62        self.def_id().trimmed_name()
63    }
64
65    /// Return information about the crate where this definition is declared.
66    ///
67    /// This will return the crate number and its name.
68    fn krate(&self) -> Crate {
69        let def_id = self.def_id();
70        with(|cx| cx.krate(def_id))
71    }
72
73    /// Return the span of this definition.
74    fn span(&self) -> Span {
75        self.def_id().span()
76    }
77
78    /// Return registered tool attributes with the given attribute name.
79    ///
80    /// For example, `#![rustfmt::skip]` can be specified as
81    /// `&["rustfmt".to_string(), "skip".to_string()]`.
82    fn tool_attrs(&self, attr: &[Symbol]) -> Vec<Attribute> {
83        let def_id = self.def_id();
84        with(|cx| cx.tool_attrs(def_id, attr))
85    }
86
87    /// Return all tool attributes of this definition.
88    fn all_tool_attrs(&self) -> Vec<Attribute> {
89        let def_id = self.def_id();
90        with(|cx| cx.all_tool_attrs(def_id))
91    }
92}
93
94/// A trait that can be used to retrieve a definition's type.
95///
96/// Note that not every CrateDef has a type `Ty`. They should not implement this trait.
97pub trait CrateDefType: CrateDef {
98    /// Returns the type of this crate item.
99    fn ty(&self) -> Ty {
100        with(|cx| cx.def_ty(self.def_id()))
101    }
102
103    /// Retrieve the type of this definition by instantiating and normalizing it with `args`.
104    ///
105    /// This will panic if instantiation fails.
106    fn ty_with_args(&self, args: &GenericArgs) -> Ty {
107        with(|cx| cx.def_ty_with_args(self.def_id(), args))
108    }
109}
110
111#[derive(#[automatically_derived]impl ::core::clone::Clone for Attribute {
    #[inline]
    fn clone(&self) -> Self {
        Attribute {
            value: ::core::clone::Clone::clone(&self.value),
            span: ::core::clone::Clone::clone(&self.span),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Attribute {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "Attribute value span", &self.value, &&self.span)
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Attribute
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Attribute {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value && self.span == other.span
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Attribute {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<String>;
        let _: ::core::cmp::AssertParamIsEq<Span>;
    }
}Eq)]
112pub struct Attribute {
113    value: String,
114    span: Span,
115}
116
117impl Attribute {
118    pub fn new(value: String, span: Span) -> Attribute {
119        Attribute { value, span }
120    }
121
122    /// Get the span of this attribute.
123    pub fn span(&self) -> Span {
124        self.span
125    }
126
127    /// Get the string representation of this attribute.
128    pub fn as_str(&self) -> &str {
129        &self.value
130    }
131}
132
133macro_rules! crate_def {
134    ($(
135        $(#[$attr:meta])*
136        $vis:vis $name:ident;
137    )*) => {
138        $(
139            $(#[$attr])*
140            #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
141            $vis struct $name(pub DefId);
142
143            impl CrateDef for $name {
144                fn def_id(&self) -> DefId {
145                    self.0
146                }
147            }
148        )*
149    };
150}
151
152macro_rules! crate_def_with_ty {
153    () => {};
154    (
155        $(#[$attr:meta])*
156        $vis:vis $name:ident;
157        $($rest:tt)*
158    ) => {
159        $(#[$attr])*
160        #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
161        $vis struct $name(pub DefId);
162
163        impl CrateDef for $name {
164            fn def_id(&self) -> DefId {
165                self.0
166            }
167        }
168
169        impl CrateDefType for $name {}
170
171        crate_def_with_ty!($($rest)*);
172    };
173    (
174        $(#[$attr:meta])*
175        $vis:vis $name:ident {
176            $(
177                $(#[$f_attr:meta])*
178                $f_vis:vis $f_name:ident: $f_ty:ty,
179            )*
180        }
181        $($rest:tt)*
182    ) => {
183        $(#[$attr])*
184        #[derive(Clone, PartialEq, Eq, Debug)]
185        $vis struct $name {
186            pub(crate) def: DefId,
187            $(
188                $(#[$f_attr])*
189                $f_vis $f_name: $f_ty,
190            )*
191        }
192
193        impl CrateDef for $name {
194            fn def_id(&self) -> DefId {
195                self.def
196            }
197        }
198
199        impl CrateDefType for $name {}
200
201        crate_def_with_ty!($($rest)*);
202    };
203}