Skip to main content

xur_bytecode/
signature.rs

1//! A function's complete written signature, for hosts that call script
2//! functions with arguments they build (such as a form in a web page).
3//!
4//! Unlike [`RtType`](crate::RtType), which keeps only what a runtime check
5//! needs, a [`TypeSig`] keeps everything written: list element types, the
6//! fields of structs (recursively), the variants of enums, and the type
7//! arguments of native types (`web::Slider<u8>`). Attributes on fields are the
8//! registry's: read them with `resolutions.attribute(AttrTarget::Field(..))`.
9
10use xur_ast::{FieldDef, FnRetTy, PatKind, Ty, TyKind};
11use xur_resolve::{DefId, DefKind, Namespace, PrimTy, Program, Res, Resolutions};
12use xur_span::Symbol;
13
14use crate::ItemIndex;
15use crate::ir::RtType;
16use crate::types::prim_rt_type;
17
18/// A function's parameters and return type.
19#[derive(Debug, Clone, PartialEq)]
20pub struct FnSig {
21    pub params: Vec<ParamSig>,
22    pub ret: TypeSig,
23}
24
25#[derive(Debug, Clone, PartialEq)]
26pub struct ParamSig {
27    /// The parameter's name, or `_` for a pattern that isn't a plain name.
28    pub name: String,
29    pub ty: TypeSig,
30}
31
32/// A written type, in full.
33#[derive(Debug, Clone, PartialEq)]
34pub enum TypeSig {
35    Unit,
36    Bool,
37    Str,
38    Bytes,
39    Map,
40    /// An integer type and its range, e.g. `u8` (0 to 255).
41    Int {
42        name: &'static str,
43        min: i128,
44        max: i128,
45    },
46    Float {
47        name: &'static str,
48    },
49    /// `[T]`
50    List(Box<TypeSig>),
51    /// `(A, B)`
52    Tuple(Vec<TypeSig>),
53    /// A user struct and its fields, in declaration order.
54    Struct {
55        def: DefId,
56        name: String,
57        fields: Vec<FieldSig>,
58    },
59    /// A user enum and its variants, in declaration order.
60    Enum {
61        def: DefId,
62        name: String,
63        variants: Vec<VariantSig>,
64    },
65    /// A type a native module registered, with any type arguments written
66    /// after it (`Slider<u8>` has `[u8]`).
67    Native {
68        def: DefId,
69        name: String,
70        args: Vec<TypeSig>,
71    },
72    /// A struct met again inside its own fields; see the outer one for its
73    /// fields.
74    Recursive {
75        def: DefId,
76        name: String,
77    },
78    /// An inferred, generic, pointer, function or record type: anything.
79    Any,
80}
81
82#[derive(Debug, Clone, PartialEq)]
83pub struct FieldSig {
84    /// The field's name, or its position for a tuple struct.
85    pub name: String,
86    pub ty: TypeSig,
87}
88
89#[derive(Debug, Clone, PartialEq)]
90pub struct VariantSig {
91    pub def: DefId,
92    pub name: String,
93    /// Whether it has no fields (`Red`, not `Rgb(u8, u8, u8)`).
94    pub unit: bool,
95}
96
97/// The signature of the top-level function `name` in the program's root
98/// module, or `None` if there is no such function.
99pub fn fn_signature(program: &Program, index: &ItemIndex, name: &str) -> Option<FnSig> {
100    let resolutions = program.resolutions();
101    let root = resolutions.module_defs[program.krate.root.0];
102    let Some(Res::Def(DefKind::Fn, def)) =
103        resolutions.lookup(root, Namespace::Value, Symbol::intern(name))
104    else {
105        return None;
106    };
107    let crate::ItemRef::Fn { item, .. } = index.get(def)? else {
108        return None;
109    };
110    let sigs = Sigs {
111        resolutions,
112        index,
113        seen: Vec::new(),
114    };
115    let mut sigs = sigs;
116    let params = item
117        .decl
118        .inputs
119        .iter()
120        .map(|param| ParamSig {
121            name: match &param.pat.kind {
122                PatKind::Ident(ident) => ident.name.to_string(),
123                _ => "_".to_owned(),
124            },
125            ty: sigs.ty(&param.ty),
126        })
127        .collect();
128    let ret = match &item.decl.output {
129        FnRetTy::Default(_) => TypeSig::Unit,
130        FnRetTy::Ty(ty) => sigs.ty(ty),
131    };
132    Some(FnSig { params, ret })
133}
134
135struct Sigs<'a> {
136    resolutions: &'a Resolutions,
137    index: &'a ItemIndex,
138    /// The structs being expanded, to stop at recursive ones.
139    seen: Vec<DefId>,
140}
141
142impl Sigs<'_> {
143    fn ty(&mut self, ty: &Ty) -> TypeSig {
144        match &ty.kind {
145            TyKind::Path(path) => {
146                let args = || {
147                    path.segments
148                        .last()
149                        .and_then(|segment| segment.args.as_ref())
150                        .map(|args| args.args.as_slice())
151                        .unwrap_or_default()
152                };
153                match self.resolutions.res.get(&path.id) {
154                    Some(Res::PrimTy(prim)) => prim_sig(*prim),
155                    Some(&Res::Def(DefKind::Struct, def)) => self.strukt(def),
156                    Some(&Res::Def(DefKind::Enum, def)) => self.enum_sig(def),
157                    Some(&Res::Def(DefKind::NativeType(_), def)) => TypeSig::Native {
158                        def,
159                        name: self.resolutions.def_path(def),
160                        args: args().iter().map(|ty| self.ty(ty)).collect(),
161                    },
162                    _ => TypeSig::Any,
163                }
164            }
165            TyKind::Tuple(tys) if tys.is_empty() => TypeSig::Unit,
166            TyKind::Tuple(tys) => TypeSig::Tuple(tys.iter().map(|ty| self.ty(ty)).collect()),
167            TyKind::Paren(ty) => self.ty(ty),
168            TyKind::List(ty) => TypeSig::List(Box::new(self.ty(ty))),
169            TyKind::Ptr(_)
170            | TyKind::Fn { .. }
171            | TyKind::Record
172            | TyKind::Infer
173            | TyKind::ImplicitSelf
174            | TyKind::Err => TypeSig::Any,
175        }
176    }
177
178    fn strukt(&mut self, def: DefId) -> TypeSig {
179        let name = self.resolutions.def_path(def);
180        if self.seen.contains(&def) {
181            return TypeSig::Recursive { def, name };
182        }
183        self.seen.push(def);
184        let fields = self
185            .index
186            .fields(def)
187            .unwrap_or_default()
188            .iter()
189            .enumerate()
190            .map(|(i, field)| self.field(i, field))
191            .collect();
192        self.seen.pop();
193        TypeSig::Struct { def, name, fields }
194    }
195
196    fn field(&mut self, i: usize, field: &FieldDef) -> FieldSig {
197        FieldSig {
198            name: field
199                .ident
200                .map(|ident| ident.name.to_string())
201                .unwrap_or_else(|| i.to_string()),
202            ty: self.ty(&field.ty),
203        }
204    }
205
206    fn enum_sig(&self, def: DefId) -> TypeSig {
207        let variants = self
208            .resolutions
209            .defs
210            .iter()
211            .filter(|(_, data)| data.kind == DefKind::Variant && data.parent == Some(def))
212            .map(|(variant, data)| VariantSig {
213                def: variant,
214                name: data.name.to_string(),
215                unit: self.index.fields(variant).is_none_or(<[_]>::is_empty),
216            })
217            .collect();
218        TypeSig::Enum {
219            def,
220            name: self.resolutions.def_path(def),
221            variants,
222        }
223    }
224}
225
226fn prim_sig(prim: PrimTy) -> TypeSig {
227    match prim_rt_type(prim) {
228        RtType::Bool => TypeSig::Bool,
229        RtType::Str => TypeSig::Str,
230        RtType::Bytes => TypeSig::Bytes,
231        RtType::Map => TypeSig::Map,
232        RtType::Int { name, min, max } => TypeSig::Int { name, min, max },
233        RtType::Float { name } => TypeSig::Float { name },
234        _ => TypeSig::Any,
235    }
236}