xur-bytecode 0.1.10

The register-based bytecode of the Xur language, and lowering to it
Documentation
//! A function's complete written signature, for hosts that call script
//! functions with arguments they build (such as a form in a web page).
//!
//! Unlike [`RtType`](crate::RtType), which keeps only what a runtime check
//! needs, a [`TypeSig`] keeps everything written: list element types, the
//! fields of structs (recursively), the variants of enums, and the type
//! arguments of native types (`web::Slider<u8>`). Attributes on fields are the
//! registry's: read them with `resolutions.attribute(AttrTarget::Field(..))`.

use xur_ast::{FieldDef, FnRetTy, PatKind, Ty, TyKind};
use xur_resolve::{DefId, DefKind, Namespace, PrimTy, Program, Res, Resolutions};
use xur_span::Symbol;

use crate::ItemIndex;
use crate::ir::RtType;
use crate::types::prim_rt_type;

/// A function's parameters and return type.
#[derive(Debug, Clone, PartialEq)]
pub struct FnSig {
    pub params: Vec<ParamSig>,
    pub ret: TypeSig,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ParamSig {
    /// The parameter's name, or `_` for a pattern that isn't a plain name.
    pub name: String,
    pub ty: TypeSig,
}

/// A written type, in full.
#[derive(Debug, Clone, PartialEq)]
pub enum TypeSig {
    Unit,
    Bool,
    Str,
    Bytes,
    Map,
    /// An integer type and its range, e.g. `u8` (0 to 255).
    Int {
        name: &'static str,
        min: i128,
        max: i128,
    },
    Float {
        name: &'static str,
    },
    /// `[T]`
    List(Box<TypeSig>),
    /// `(A, B)`
    Tuple(Vec<TypeSig>),
    /// A user struct and its fields, in declaration order.
    Struct {
        def: DefId,
        name: String,
        fields: Vec<FieldSig>,
    },
    /// A user enum and its variants, in declaration order.
    Enum {
        def: DefId,
        name: String,
        variants: Vec<VariantSig>,
    },
    /// A type a native module registered, with any type arguments written
    /// after it (`Slider<u8>` has `[u8]`).
    Native {
        def: DefId,
        name: String,
        args: Vec<TypeSig>,
    },
    /// A struct met again inside its own fields; see the outer one for its
    /// fields.
    Recursive {
        def: DefId,
        name: String,
    },
    /// An inferred, generic, pointer, function or record type: anything.
    Any,
}

#[derive(Debug, Clone, PartialEq)]
pub struct FieldSig {
    /// The field's name, or its position for a tuple struct.
    pub name: String,
    pub ty: TypeSig,
}

#[derive(Debug, Clone, PartialEq)]
pub struct VariantSig {
    pub def: DefId,
    pub name: String,
    /// Whether it has no fields (`Red`, not `Rgb(u8, u8, u8)`).
    pub unit: bool,
}

/// The signature of the top-level function `name` in the program's root
/// module, or `None` if there is no such function.
pub fn fn_signature(program: &Program, index: &ItemIndex, name: &str) -> Option<FnSig> {
    let resolutions = program.resolutions();
    let root = resolutions.module_defs[program.krate.root.0];
    let Some(Res::Def(DefKind::Fn, def)) =
        resolutions.lookup(root, Namespace::Value, Symbol::intern(name))
    else {
        return None;
    };
    let crate::ItemRef::Fn { item, .. } = index.get(def)? else {
        return None;
    };
    let sigs = Sigs {
        resolutions,
        index,
        seen: Vec::new(),
    };
    let mut sigs = sigs;
    let params = item
        .decl
        .inputs
        .iter()
        .map(|param| ParamSig {
            name: match &param.pat.kind {
                PatKind::Ident(ident) => ident.name.to_string(),
                _ => "_".to_owned(),
            },
            ty: sigs.ty(&param.ty),
        })
        .collect();
    let ret = match &item.decl.output {
        FnRetTy::Default(_) => TypeSig::Unit,
        FnRetTy::Ty(ty) => sigs.ty(ty),
    };
    Some(FnSig { params, ret })
}

struct Sigs<'a> {
    resolutions: &'a Resolutions,
    index: &'a ItemIndex,
    /// The structs being expanded, to stop at recursive ones.
    seen: Vec<DefId>,
}

impl Sigs<'_> {
    fn ty(&mut self, ty: &Ty) -> TypeSig {
        match &ty.kind {
            TyKind::Path(path) => {
                let args = || {
                    path.segments
                        .last()
                        .and_then(|segment| segment.args.as_ref())
                        .map(|args| args.args.as_slice())
                        .unwrap_or_default()
                };
                match self.resolutions.res.get(&path.id) {
                    Some(Res::PrimTy(prim)) => prim_sig(*prim),
                    Some(&Res::Def(DefKind::Struct, def)) => self.strukt(def),
                    Some(&Res::Def(DefKind::Enum, def)) => self.enum_sig(def),
                    Some(&Res::Def(DefKind::NativeType(_), def)) => TypeSig::Native {
                        def,
                        name: self.resolutions.def_path(def),
                        args: args().iter().map(|ty| self.ty(ty)).collect(),
                    },
                    _ => TypeSig::Any,
                }
            }
            TyKind::Tuple(tys) if tys.is_empty() => TypeSig::Unit,
            TyKind::Tuple(tys) => TypeSig::Tuple(tys.iter().map(|ty| self.ty(ty)).collect()),
            TyKind::Paren(ty) => self.ty(ty),
            TyKind::List(ty) => TypeSig::List(Box::new(self.ty(ty))),
            TyKind::Ptr(_)
            | TyKind::Fn { .. }
            | TyKind::Record
            | TyKind::Infer
            | TyKind::ImplicitSelf
            | TyKind::Err => TypeSig::Any,
        }
    }

    fn strukt(&mut self, def: DefId) -> TypeSig {
        let name = self.resolutions.def_path(def);
        if self.seen.contains(&def) {
            return TypeSig::Recursive { def, name };
        }
        self.seen.push(def);
        let fields = self
            .index
            .fields(def)
            .unwrap_or_default()
            .iter()
            .enumerate()
            .map(|(i, field)| self.field(i, field))
            .collect();
        self.seen.pop();
        TypeSig::Struct { def, name, fields }
    }

    fn field(&mut self, i: usize, field: &FieldDef) -> FieldSig {
        FieldSig {
            name: field
                .ident
                .map(|ident| ident.name.to_string())
                .unwrap_or_else(|| i.to_string()),
            ty: self.ty(&field.ty),
        }
    }

    fn enum_sig(&self, def: DefId) -> TypeSig {
        let variants = self
            .resolutions
            .defs
            .iter()
            .filter(|(_, data)| data.kind == DefKind::Variant && data.parent == Some(def))
            .map(|(variant, data)| VariantSig {
                def: variant,
                name: data.name.to_string(),
                unit: self.index.fields(variant).is_none_or(<[_]>::is_empty),
            })
            .collect();
        TypeSig::Enum {
            def,
            name: self.resolutions.def_path(def),
            variants,
        }
    }
}

fn prim_sig(prim: PrimTy) -> TypeSig {
    match prim_rt_type(prim) {
        RtType::Bool => TypeSig::Bool,
        RtType::Str => TypeSig::Str,
        RtType::Bytes => TypeSig::Bytes,
        RtType::Map => TypeSig::Map,
        RtType::Int { name, min, max } => TypeSig::Int { name, min, max },
        RtType::Float { name } => TypeSig::Float { name },
        _ => TypeSig::Any,
    }
}