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    /// An untyped record (`@{}`). Like a map, only that it is a record is
87    /// checked; a struct assigned to it is coerced into a record by field name.
88    Record,
89    /// The metatype: accepts values that are themselves types.
90    Type,
91}
92
93impl PrimTy {
94    pub const ALL: [PrimTy; 18] = [
95        Self::Bool,
96        Self::Str,
97        Self::Bytes,
98        Self::U8,
99        Self::U16,
100        Self::U32,
101        Self::U64,
102        Self::Usize,
103        Self::I8,
104        Self::I16,
105        Self::I32,
106        Self::I64,
107        Self::Isize,
108        Self::F32,
109        Self::F64,
110        Self::Map,
111        Self::Record,
112        Self::Type,
113    ];
114
115    pub fn name(self) -> &'static str {
116        match self {
117            Self::Bool => "bool",
118            Self::Str => "str",
119            Self::Bytes => "bytes",
120            Self::U8 => "u8",
121            Self::U16 => "u16",
122            Self::U32 => "u32",
123            Self::U64 => "u64",
124            Self::Usize => "usize",
125            Self::I8 => "i8",
126            Self::I16 => "i16",
127            Self::I32 => "i32",
128            Self::I64 => "i64",
129            Self::Isize => "isize",
130            Self::F32 => "f32",
131            Self::F64 => "f64",
132            Self::Map => "map",
133            Self::Record => "record",
134            Self::Type => "type",
135        }
136    }
137
138    pub fn from_name(name: Symbol) -> Option<Self> {
139        Self::ALL.into_iter().find(|ty| ty.name() == name.as_str())
140    }
141}
142
143/// What a name resolved to.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub enum Res {
146    Def(DefKind, DefId),
147    /// A local variable, identified by the pattern that binds it.
148    Local(NodeId),
149    PrimTy(PrimTy),
150    /// `T::name` where `T` is a type parameter: resolved at runtime.
151    TyParamAssoc(DefId, Symbol),
152    /// Resolution failed; the error has been reported.
153    Err,
154}
155
156impl Res {
157    pub fn descr(self) -> &'static str {
158        match self {
159            Self::Def(kind, _) => kind.descr(),
160            Self::Local(_) => "local variable",
161            Self::PrimTy(_) => "builtin type",
162            Self::TyParamAssoc(..) => "type parameter associated function",
163            Self::Err => "unresolved item",
164        }
165    }
166
167    /// The definition to look further names up in, for `a::b` paths.
168    pub fn scope(self) -> Option<DefId> {
169        match self {
170            Self::Def(kind, id) if kind.has_scope() => Some(id),
171            _ => None,
172        }
173    }
174}
175
176/// The two namespaces of names (rustc also has one for macros). A type and
177/// a value may share a name; a tuple struct or variant is in both.
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
179pub enum Namespace {
180    Type,
181    Value,
182}
183
184impl Namespace {
185    pub const TYPE: &[Namespace] = &[Namespace::Type];
186    pub const VALUE: &[Namespace] = &[Namespace::Value];
187    /// For names that are both a type and a value, like tuple structs.
188    pub const BOTH: &[Namespace] = &[Namespace::Type, Namespace::Value];
189
190    pub fn descr(self) -> &'static str {
191        match self {
192            Self::Type => "type",
193            Self::Value => "value",
194        }
195    }
196}
197
198#[derive(Debug, Clone)]
199pub struct DefData {
200    pub kind: DefKind,
201    pub name: Symbol,
202    /// The module or enum the definition is in. `None` for file modules
203    /// and the `std` root.
204    pub parent: Option<DefId>,
205    /// Where the definition's name was written; `None` for built-ins.
206    pub span: Option<Span>,
207}
208
209/// Every definition in the program.
210#[derive(Debug, Default)]
211pub struct Definitions {
212    defs: Vec<DefData>,
213}
214
215impl Definitions {
216    pub fn create(&mut self, data: DefData) -> DefId {
217        let id = DefId(u32::try_from(self.defs.len()).expect("too many definitions"));
218        self.defs.push(data);
219        id
220    }
221
222    pub fn get(&self, id: DefId) -> &DefData {
223        &self.defs[id.0 as usize]
224    }
225
226    pub fn iter(&self) -> impl Iterator<Item = (DefId, &DefData)> {
227        self.defs
228            .iter()
229            .enumerate()
230            .map(|(i, d)| (DefId(i as u32), d))
231    }
232
233    /// `id` and its parents, outermost first: for `std::io::println`, the
234    /// definitions of `std`, `io` and `println`.
235    pub fn lineage(&self, id: DefId) -> Vec<DefId> {
236        let mut lineage = Vec::new();
237        let mut current = Some(id);
238        while let Some(id) = current {
239            lineage.push(id);
240            current = self.get(id).parent;
241        }
242        lineage.reverse();
243        lineage
244    }
245}