rustfront 0.4.0

Evaluate MFront material behaviours (constitutive laws) at a material point, in pure Rust, without MGIS or any C++ build dependency
Documentation
//! Reading the symbols a library generated by MFront exports, with the types
//! MFront gives them: what the behaviours, models and material properties
//! share.

use core::ffi::{c_char, c_int, CStr};
use std::ffi::CString;

use libloading::Library;

use crate::{ffi, Error, Parameter, ParameterValue, VariableType};

/// The symbols of a behaviour, model or material property `name`:
/// `<name>_<hypothesis>_<suffix>`, or else `<name>_<suffix>`, MFront exporting
/// a symbol per hypothesis only for the values that depend on it. The methods
/// read each symbol with the type MFront gives it, which the caller of the
/// loaders guarantees.
pub(crate) struct Symbols<'a> {
    pub(crate) library: &'a Library,
    pub(crate) name: &'a str,
    /// The hypothesis of a behaviour; material properties have none.
    pub(crate) hypothesis: Option<&'a str>,
}

impl Symbols<'_> {
    /// The symbol `suffix` as a `T`: a pointer to the variable, or the
    /// function, the symbol names.
    ///
    /// # Safety
    ///
    /// `T` must be the type of the symbol.
    pub(crate) unsafe fn get<T: Copy>(&self, suffix: &str) -> Result<T, Error> {
        let name = self.name;
        let generic = format!("{name}_{suffix}");
        let specific = self.hypothesis.map(|h| format!("{name}_{h}_{suffix}"));
        let found = specific.iter().chain([&generic]).find_map(|symbol| {
            // SAFETY: the caller guarantees the type.
            unsafe { self.library.get::<T>(symbol.as_str()) }
                .ok()
                .map(|s| *s)
        });
        found.ok_or(Error::MissingSymbol { symbol: generic })
    }

    /// The `unsigned short` symbol `suffix`: a count, a flag, a code.
    pub(crate) fn u16(&self, suffix: &str) -> Result<u16, Error> {
        // SAFETY: MFront exports these symbols as `unsigned short`.
        Ok(unsafe { *self.get::<*const u16>(suffix)? })
    }

    /// The `n` strings of the array `suffix`. A single string, exported as a
    /// `const char*` variable, is an array of one.
    pub(crate) fn strings(&self, suffix: &str, n: usize) -> Result<Vec<String>, Error> {
        // SAFETY: MFront exports these symbols as arrays of `n` NUL-terminated
        // strings.
        let array =
            unsafe { core::slice::from_raw_parts(self.get::<*const *const c_char>(suffix)?, n) };
        array
            .iter()
            .map(|&s| {
                // SAFETY: as above.
                unsafe { CStr::from_ptr(s) }
                    .to_str()
                    .map(str::to_owned)
                    .map_err(|_| Error::InvalidString {
                        symbol: format!("{}_{suffix}", self.name),
                    })
            })
            .collect()
    }

    /// The `n` integers of the array `suffix`.
    pub(crate) fn ints(&self, suffix: &str, n: usize) -> Result<Vec<c_int>, Error> {
        // SAFETY: MFront exports these symbols as arrays of `n` `int`.
        Ok(unsafe { core::slice::from_raw_parts(self.get::<*const c_int>(suffix)?, n) }.to_vec())
    }

    /// Checks what every loader needs: the `generic` interface, the kind of
    /// material knowledge (`_mfront_mkt`: 0 for a material property, 1 for a
    /// behaviour or a model), and TFEL 5.1.0 or later. Returns the TFEL version.
    pub(crate) fn check(&self, knowledge: u16) -> Result<String, Error> {
        let name = self.name.to_owned();
        let interface = self.strings("mfront_interface", 1)?.remove(0);
        if interface != "Generic" {
            return Err(Error::NotGeneric { name, interface });
        }
        if self.u16("mfront_mkt")? != knowledge {
            let expected = match knowledge {
                0 => "material property",
                _ => "behaviour or model",
            };
            return Err(Error::UnexpectedKind { name, expected });
        }
        let version = self.strings("tfel_version", 1)?.remove(0);
        // `5.1.0`, `5.2-dev`, …: the leading numbers, compared in order.
        let numbers: Vec<u32> = version
            .split(['.', '-'])
            .map_while(|s| s.parse().ok())
            .collect();
        if numbers.as_slice() < [5, 1, 0].as_slice() {
            return Err(Error::UnsupportedTfelVersion { name, version });
        }
        Ok(version)
    }

    /// The names and types of the variables `suffix`: their number is
    /// `n<suffix>`, their types `<suffix>Types` unless `typed` is false
    /// (material properties are always scalars and have no such symbol).
    pub(crate) fn variables(
        &self,
        suffix: &str,
        typed: bool,
    ) -> Result<Vec<(String, VariableType)>, Error> {
        let n = usize::from(self.u16(&format!("n{suffix}"))?);
        if n == 0 {
            return Ok(Vec::new());
        }
        let codes = if typed {
            self.ints(&format!("{suffix}Types"), n)?
        } else {
            vec![0; n]
        };
        self.strings(suffix, n)?
            .into_iter()
            .zip(codes)
            .map(|(variable, code)| match code {
                0 => Ok((variable, VariableType::Scalar)),
                1 => Ok((variable, VariableType::Stensor)),
                2 => Ok((variable, VariableType::Vector)),
                3 => Ok((variable, VariableType::Tensor)),
                _ => Err(Error::UnsupportedVariableType { variable, code }),
            })
            .collect()
    }

    /// The parameters and their default values. Those of an array are listed
    /// one by one, `b[0]`, `b[1]`, whose default values are named
    /// `b_mfront_index_0`, `b_mfront_index_1`.
    pub(crate) fn parameters(&self) -> Result<Vec<Parameter>, Error> {
        let n = usize::from(self.u16("nParameters")?);
        if n == 0 {
            return Ok(Vec::new());
        }
        let names = self.strings("Parameters", n)?;
        let codes = self.ints("ParametersTypes", n)?;
        names
            .into_iter()
            .zip(codes)
            .map(|(name, code)| {
                let symbol = match name.strip_suffix(']').and_then(|p| p.split_once('[')) {
                    Some((base, index)) => {
                        format!("{base}_mfront_index_{index}_ParameterDefaultValue")
                    }
                    None => format!("{name}_ParameterDefaultValue"),
                };
                // SAFETY: MFront exports the default value of a parameter as a
                // `double`, an `int` or an `unsigned short`, as its type code
                // says: 0, 1 or 2.
                let default = unsafe {
                    match code {
                        0 => ParameterValue::Real(*self.get::<*const f64>(&symbol)?),
                        1 => ParameterValue::Integer(*self.get::<*const c_int>(&symbol)?),
                        2 => ParameterValue::UnsignedShort(*self.get::<*const u16>(&symbol)?),
                        _ => {
                            return Err(Error::UnsupportedVariableType {
                                variable: name,
                                code,
                            })
                        }
                    }
                };
                Ok(Parameter { name, default })
            })
            .collect()
    }

    /// Sets the `values` of parameters among the `declared` ones, in the
    /// static variables of the library.
    ///
    /// # Safety
    ///
    /// No integration or evaluation of this behaviour, model or material
    /// property may run meanwhile.
    pub(crate) unsafe fn set_parameters(
        &self,
        declared: &[Parameter],
        values: &[(&str, ParameterValue)],
    ) -> Result<(), Error> {
        for &(parameter, value) in values {
            let declared = declared
                .iter()
                .find(|p| p.name == parameter)
                .ok_or_else(|| Error::UnknownParameter {
                    name: self.name.to_owned(),
                    parameter: parameter.to_owned(),
                })?;
            // It equals a declared name, read from a C string: it has no NUL.
            let key = CString::new(parameter).expect("a parameter name has no NUL");
            // SAFETY: MFront exports these functions with the signatures of
            // `ffi`; the caller guarantees that nothing runs meanwhile.
            let accepted = unsafe {
                match (declared.default, value) {
                    (ParameterValue::Real(_), ParameterValue::Real(v)) => {
                        self.get::<ffi::SetParameterFn>("setParameter")?(key.as_ptr(), v)
                    }
                    (ParameterValue::Integer(_), ParameterValue::Integer(v)) => {
                        self.get::<ffi::SetIntegerParameterFn>("setIntegerParameter")?(
                            key.as_ptr(),
                            v,
                        )
                    }
                    (ParameterValue::UnsignedShort(_), ParameterValue::UnsignedShort(v)) => {
                        self.get::<ffi::SetUnsignedShortParameterFn>("setUnsignedShortParameter")?(
                            key.as_ptr(),
                            v,
                        )
                    }
                    (expected, _) => {
                        return Err(Error::WrongParameterType {
                            parameter: parameter.to_owned(),
                            expected,
                        });
                    }
                }
            };
            if accepted == 0 {
                return Err(Error::ParameterRejected {
                    parameter: parameter.to_owned(),
                });
            }
        }
        Ok(())
    }
}