1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
//! 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. MFront writes them from
/// its UTF-8 sources.
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) };
// SAFETY: as above.
Ok(array
.iter()
.map(|&s| unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned())
.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(())
}
}