Path: blob/main/crates/wiggle/generate/src/codegen_settings.rs
1693 views
use crate::config::{AsyncConf, ErrorConf, ErrorConfField, TracingConf};1use anyhow::{Error, anyhow};2use proc_macro2::{Ident, TokenStream};3use quote::quote;4use std::collections::HashMap;5use std::rc::Rc;6use witx::{Document, Id, InterfaceFunc, Module, NamedType, TypeRef};78pub use crate::config::Asyncness;910pub struct CodegenSettings {11pub errors: ErrorTransform,12pub async_: AsyncConf,13pub wasmtime: bool,14/// Disabling this feature makes it possible to remove all of the tracing15/// code emitted in the Wiggle-generated code; this can be helpful while16/// inspecting the code (e.g., with `cargo expand`).17pub tracing: TracingConf,18/// Determine whether the context structure will use `&mut self` (true) or19/// simply `&self`.20pub mutable: bool,21}22impl CodegenSettings {23pub fn new(24error_conf: &ErrorConf,25async_: &AsyncConf,26doc: &Document,27wasmtime: bool,28tracing: &TracingConf,29mutable: bool,30) -> Result<Self, Error> {31let errors = ErrorTransform::new(error_conf, doc)?;32Ok(Self {33errors,34async_: async_.clone(),35wasmtime,36tracing: tracing.clone(),37mutable,38})39}40pub fn get_async(&self, module: &Module, func: &InterfaceFunc) -> Asyncness {41self.async_.get(module.name.as_str(), func.name.as_str())42}43}4445pub struct ErrorTransform {46m: Vec<ErrorType>,47}4849impl ErrorTransform {50pub fn empty() -> Self {51Self { m: Vec::new() }52}53pub fn new(conf: &ErrorConf, doc: &Document) -> Result<Self, Error> {54let mut richtype_identifiers = HashMap::new();55let m = conf.iter().map(|(ident, field)|56match field {57ErrorConfField::Trappable(field) => if let Some(abi_type) = doc.typename(&Id::new(ident.to_string())) {58Ok(ErrorType::Generated(TrappableErrorType { abi_type, rich_type: field.rich_error.clone() }))59} else {60Err(anyhow!("No witx typename \"{}\" found", ident.to_string()))61},62ErrorConfField::User(field) => if let Some(abi_type) = doc.typename(&Id::new(ident.to_string())) {63if let Some(ident) = field.rich_error.get_ident() {64if let Some(prior_def) = richtype_identifiers.insert(ident.clone(), field.err_loc)65{66return Err(anyhow!(67"duplicate rich type identifier of {:?} not allowed. prior definition at {:?}",68ident, prior_def69));70}71Ok(ErrorType::User(UserErrorType {72abi_type,73rich_type: field.rich_error.clone(),74method_fragment: ident.to_string()75}))76} else {77return Err(anyhow!(78"rich error type must be identifier for now - TODO add ability to provide a corresponding identifier: {:?}",79field.err_loc80))81}82}83else { Err(anyhow!("No witx typename \"{}\" found", ident.to_string())) }84}85).collect::<Result<Vec<_>, Error>>()?;86Ok(Self { m })87}8889pub fn iter(&self) -> impl Iterator<Item = &ErrorType> {90self.m.iter()91}9293pub fn for_abi_error(&self, tref: &TypeRef) -> Option<&ErrorType> {94match tref {95TypeRef::Name(nt) => self.for_name(nt),96TypeRef::Value { .. } => None,97}98}99100pub fn for_name(&self, nt: &NamedType) -> Option<&ErrorType> {101self.m.iter().find(|e| e.abi_type().name == nt.name)102}103}104105pub enum ErrorType {106User(UserErrorType),107Generated(TrappableErrorType),108}109impl ErrorType {110pub fn abi_type(&self) -> &NamedType {111match self {112Self::User(u) => &u.abi_type,113Self::Generated(r) => &r.abi_type,114}115}116}117118pub struct TrappableErrorType {119abi_type: Rc<NamedType>,120rich_type: Ident,121}122123impl TrappableErrorType {124pub fn abi_type(&self) -> TypeRef {125TypeRef::Name(self.abi_type.clone())126}127pub fn typename(&self) -> TokenStream {128let richtype = &self.rich_type;129quote!(#richtype)130}131}132133pub struct UserErrorType {134abi_type: Rc<NamedType>,135rich_type: syn::Path,136method_fragment: String,137}138139impl UserErrorType {140pub fn abi_type(&self) -> TypeRef {141TypeRef::Name(self.abi_type.clone())142}143pub fn typename(&self) -> TokenStream {144let t = &self.rich_type;145quote!(#t)146}147pub fn method_fragment(&self) -> &str {148&self.method_fragment149}150}151152153