Skip to main content

xur_resolve/
def.rs

1//! What names resolve to, after `rustc_hir::def`.
2
3use std::fmt;
4
5use xur_ast::NodeId;
6
7use crate::native::{NativeFnId, NativeTypeId};
8use xur_span::{Span, Symbol};
9
10/// Identifies a definition: a module, item, enum variant, type parameter
11/// or built-in.
12#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
13pub struct DefId(u32);
14
15impl fmt::Debug for DefId {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        write!(f, "DefId({})", self.0)
18    }
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum DefKind {
23    Mod,
24    Fn,
25    Const,
26    Struct,
27    Enum,
28    Variant,
29    TyParam,
30    /// A function implemented in Rust.
31    NativeFn(NativeFnId),
32    /// A type implemented in Rust; its functions are in its scope.
33    NativeType(NativeTypeId),
34    /// A variant of an enum registered from Rust, of the native type.
35    NativeVariant(NativeTypeId),
36}
37
38impl DefKind {
39    /// How the kind is named in messages, e.g. "function".
40    pub fn descr(self) -> &'static str {
41        match self {
42            Self::Mod => "module",
43            Self::Fn => "function",
44            Self::Const => "constant",
45            Self::Struct => "struct",
46            Self::Enum => "enum",
47            Self::Variant => "variant",
48            Self::TyParam => "type parameter",
49            Self::NativeFn(_) => "native function",
50            Self::NativeType(_) => "native type",
51            Self::NativeVariant(_) => "variant",
52        }
53    }
54
55    /// Whether names can be looked up inside a definition of this kind, as
56    /// in `math::div`, `Shape::Rect` or `Point::new`.
57    pub fn has_scope(self) -> bool {
58        matches!(
59            self,
60            Self::Mod | Self::Enum | Self::Struct | Self::NativeType(_)
61        )
62    }
63}
64
65/// The built-in primitive types.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum PrimTy {
68    Bool,
69    Str,
70    Bytes,
71    U8,
72    U16,
73    U32,
74    U64,
75    Usize,
76    I8,
77    I16,
78    I32,
79    I64,
80    Isize,
81    F32,
82    F64,
83    /// A map (`#{}`), backed by a shared DashMap. Like a list, only the
84    /// container is type-checked; keys and values are dynamic.
85    Map,
86    /// The metatype: accepts values that are themselves types.
87    Type,
88}
89
90impl PrimTy {
91    pub const ALL: [PrimTy; 17] = [
92        Self::Bool,
93        Self::Str,
94        Self::Bytes,
95        Self::U8,
96        Self::U16,
97        Self::U32,
98        Self::U64,
99        Self::Usize,
100        Self::I8,
101        Self::I16,
102        Self::I32,
103        Self::I64,
104        Self::Isize,
105        Self::F32,
106        Self::F64,
107        Self::Map,
108        Self::Type,
109    ];
110
111    pub fn name(self) -> &'static str {
112        match self {
113            Self::Bool => "bool",
114            Self::Str => "str",
115            Self::Bytes => "bytes",
116            Self::U8 => "u8",
117            Self::U16 => "u16",
118            Self::U32 => "u32",
119            Self::U64 => "u64",
120            Self::Usize => "usize",
121            Self::I8 => "i8",
122            Self::I16 => "i16",
123            Self::I32 => "i32",
124            Self::I64 => "i64",
125            Self::Isize => "isize",
126            Self::F32 => "f32",
127            Self::F64 => "f64",
128            Self::Map => "map",
129            Self::Type => "type",
130        }
131    }
132
133    pub fn from_name(name: Symbol) -> Option<Self> {
134        Self::ALL.into_iter().find(|ty| ty.name() == name.as_str())
135    }
136}
137
138/// What a name resolved to.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum Res {
141    Def(DefKind, DefId),
142    /// A local variable, identified by the pattern that binds it.
143    Local(NodeId),
144    PrimTy(PrimTy),
145    /// `T::name` where `T` is a type parameter: resolved at runtime.
146    TyParamAssoc(DefId, Symbol),
147    /// Resolution failed; the error has been reported.
148    Err,
149}
150
151impl Res {
152    pub fn descr(self) -> &'static str {
153        match self {
154            Self::Def(kind, _) => kind.descr(),
155            Self::Local(_) => "local variable",
156            Self::PrimTy(_) => "builtin type",
157            Self::TyParamAssoc(..) => "type parameter associated function",
158            Self::Err => "unresolved item",
159        }
160    }
161
162    /// The definition to look further names up in, for `a::b` paths.
163    pub fn scope(self) -> Option<DefId> {
164        match self {
165            Self::Def(kind, id) if kind.has_scope() => Some(id),
166            _ => None,
167        }
168    }
169}
170
171/// The two namespaces of names (rustc also has one for macros). A type and
172/// a value may share a name; a tuple struct or variant is in both.
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
174pub enum Namespace {
175    Type,
176    Value,
177}
178
179impl Namespace {
180    pub const TYPE: &[Namespace] = &[Namespace::Type];
181    pub const VALUE: &[Namespace] = &[Namespace::Value];
182    /// For names that are both a type and a value, like tuple structs.
183    pub const BOTH: &[Namespace] = &[Namespace::Type, Namespace::Value];
184
185    pub fn descr(self) -> &'static str {
186        match self {
187            Self::Type => "type",
188            Self::Value => "value",
189        }
190    }
191}
192
193#[derive(Debug, Clone)]
194pub struct DefData {
195    pub kind: DefKind,
196    pub name: Symbol,
197    /// The module or enum the definition is in. `None` for file modules
198    /// and the `std` root.
199    pub parent: Option<DefId>,
200    /// Where the definition's name was written; `None` for built-ins.
201    pub span: Option<Span>,
202}
203
204/// Every definition in the program.
205#[derive(Debug, Default)]
206pub struct Definitions {
207    defs: Vec<DefData>,
208}
209
210impl Definitions {
211    pub fn create(&mut self, data: DefData) -> DefId {
212        let id = DefId(u32::try_from(self.defs.len()).expect("too many definitions"));
213        self.defs.push(data);
214        id
215    }
216
217    pub fn get(&self, id: DefId) -> &DefData {
218        &self.defs[id.0 as usize]
219    }
220
221    pub fn iter(&self) -> impl Iterator<Item = (DefId, &DefData)> {
222        self.defs
223            .iter()
224            .enumerate()
225            .map(|(i, d)| (DefId(i as u32), d))
226    }
227
228    /// `id` and its parents, outermost first: for `std::io::println`, the
229    /// definitions of `std`, `io` and `println`.
230    pub fn lineage(&self, id: DefId) -> Vec<DefId> {
231        let mut lineage = Vec::new();
232        let mut current = Some(id);
233        while let Some(id) = current {
234            lineage.push(id);
235            current = self.get(id).parent;
236        }
237        lineage.reverse();
238        lineage
239    }
240}