Skip to main content

xur_runtime/
reflect.rs

1//! What native code can learn about Xur types at runtime, for `std::reflect`.
2
3use xur_ast::Attribute;
4use xur_resolve::{DefId, RtType};
5use xur_span::Symbol;
6
7/// A type as native code sees it: a type argument, as in `layout::<T>()`,
8/// or the written type of a field.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct TypeRef {
11    /// How the type was written, resolved: `u32`, `Point`, `[u8]`, or `_`
12    /// if unknown.
13    pub name: String,
14    /// The struct, enum or native type it names, if any.
15    pub def: Option<DefId>,
16}
17
18impl TypeRef {
19    /// A type with a name only, such as a primitive.
20    pub fn named(name: impl Into<String>) -> Self {
21        Self {
22            name: name.into(),
23            def: None,
24        }
25    }
26
27    /// `@`: record mode — values are coerced to records, and `T::new()`
28    /// creates an empty record.
29    pub fn record() -> Self {
30        Self {
31            name: "@".to_owned(),
32            def: None,
33        }
34    }
35
36    pub fn is_record(&self) -> bool {
37        self.name == "@" && self.def.is_none()
38    }
39}
40
41/// A struct or enum variant defined in Xur.
42#[derive(Debug, Clone)]
43pub struct AdtInfo {
44    /// Its path, e.g. `Point` or `Shape::Circle`.
45    pub name: String,
46    /// The constructor of its values.
47    pub ctor: DefId,
48    /// Whether it is a variant of an enum, rather than a struct.
49    pub is_variant: bool,
50    /// The attributes written on it, such as `#[repr(C)]`.
51    pub attrs: &'static [Attribute],
52    /// Its fields, in declaration order.
53    pub fields: Vec<FieldInfo>,
54}
55
56#[derive(Debug, Clone)]
57pub struct FieldInfo {
58    /// `None` for the fields of tuple structs and variants.
59    pub name: Option<Symbol>,
60    pub ty: TypeRef,
61    pub attrs: &'static [Attribute],
62}
63
64impl AdtInfo {
65    /// The names of the fields, or their numbers for a tuple struct.
66    pub fn field_names(&self) -> Vec<String> {
67        self.fields
68            .iter()
69            .enumerate()
70            .map(|(index, field)| match field.name {
71                Some(name) => name.to_string(),
72                None => index.to_string(),
73            })
74            .collect()
75    }
76}
77
78/// Reflection data for a function, closure, or constructor.
79#[derive(Debug, Clone)]
80pub struct FnInfo {
81    pub name: String,
82    pub param_count: usize,
83    pub param_names: Vec<Option<String>>,
84    pub param_types: Vec<Option<RtType>>,
85    pub return_type: Option<RtType>,
86}