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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use quote::quote;
use regex::Regex;
use std::io::{BufRead, BufReader, Cursor};
use syn::parse::{Parse, ParseStream};
use syn::{parse_macro_input, Result};
struct Args {
model: syn::Ident,
header: syn::LitStr,
}
impl Parse for Args {
fn parse(input: ParseStream) -> Result<Self> {
let model = input.parse()?;
input.parse::<syn::Token![,]>()?;
let header = input.parse()?;
Ok(Self { model, header })
}
}
#[derive(Debug)]
struct IO {
pub name: String,
pub ident: Ident,
pub size: usize,
}
impl IO {
fn new(name: &str, size: &str) -> Self {
Self {
name: name.to_string(),
ident: Ident::new(name, Span::call_site()),
size: size.parse().unwrap(),
}
}
fn variant(&self) -> Ident {
Ident::new(&self.name.replace("_", ""), Span::call_site())
}
fn var(&self) -> Ident {
Ident::new(&self.name.to_lowercase(), Span::call_site())
}
}
fn parse_io(lines: &mut std::io::Lines<BufReader<Cursor<String>>>, io: &str) -> Option<Vec<IO>> {
let re_with_size = Regex::new(r"_T (?P<name>\w+)\[(?P<size>\d+)\]").unwrap();
let re_without_size = Regex::new(r"_T (?P<name>\w+)").unwrap();
match lines.next() {
Some(Ok(line)) if line.starts_with("typedef struct") => {
println!("| {}:", io);
let mut io_data = vec![];
while let Some(Ok(line)) = lines.next() {
if line.contains(io) {
break;
} else {
if let Some(caps) = re_with_size.captures(&line) {
let rs_type_name = &caps["name"].replace("_", "");
let rs_var_name = &caps["name"].to_lowercase();
println!(
"| - {:<10}: {:>6} => ({:>10} : {:<8})",
&caps["name"], &caps["size"], rs_var_name, rs_type_name
);
io_data.push(IO::new(&caps["name"], &caps["size"]))
} else {
if let Some(caps) = re_without_size.captures(&line) {
let rs_type_name = &caps["name"].replace("_", "");
let rs_var_name = &caps["name"].to_lowercase();
println!(
"| - {:<10}: {:>6} => ({:>10} : {:<8})",
&caps["name"], "1", rs_var_name, rs_type_name
);
io_data.push(IO::new(&caps["name"], "1"))
}
}
}
}
Some(io_data)
}
_ => None,
}
}
#[proc_macro]
pub fn import(input: TokenStream) -> TokenStream {
let Args { model, header } = parse_macro_input!(input);
println!("Parsing Simulink model {}:", model);
let file = Cursor::new(header.value());
let reader = BufReader::new(file);
let mut lines = reader.lines();
let mut model_inputs = vec![];
let mut model_outputs = vec![];
while let Some(Ok(line)) = lines.next() {
if line.contains("External inputs") {
if let Some(ref mut io) = parse_io(&mut lines, "ExtU") {
model_inputs.append(io);
}
}
if line.contains("External outputs") {
if let Some(ref mut io) = parse_io(&mut lines, "ExtY") {
model_outputs.append(io);
}
}
}
let sim_u: Vec<_> = model_inputs.iter().map(|i| i.ident.clone()).collect();
let size_u: Vec<_> = model_inputs.iter().map(|i| i.size).collect();
let enum_u: Vec<_> = model_inputs.iter().map(|i| i.variant()).collect();
let var_u: Vec<_> = model_inputs.iter().map(|i| i.var()).collect();
let sim_y: Vec<_> = model_outputs.iter().map(|o| o.ident.clone()).collect();
let size_y: Vec<_> = model_outputs.iter().map(|o| o.size).collect();
let enum_y: Vec<_> = model_outputs.iter().map(|i| i.variant()).collect();
let var_y: Vec<_> = model_outputs.iter().map(|i| i.var()).collect();
let code = quote! {
pub trait Simulink {
fn initialize(&mut self);
fn __step__(&self);
fn terminate(&self);
}
paste::paste!{
#[repr(C)]
#[allow(non_snake_case)]
#[derive(Debug)]
struct [<ExtU_ #model _T>] {
#(#sim_u: [f64;#size_u]),*
}}
paste::paste!{
#[repr(C)]
#[allow(non_snake_case)]
#[derive(Debug)]
struct [<ExtY_ #model _T>] {
#(#sim_y: [f64;#size_y]),*
}}
paste::paste!{
extern "C" {
fn [<#model _initialize>]();
fn [<#model _step>]();
fn [<#model _terminate>]();
static mut [<#model _U>]: [<ExtU_ #model _T>];
static mut [<#model _Y>]: [<ExtY_ #model _T>];
}}
#[derive(Debug)]
pub enum U<'a> {
#(#enum_u(&'a mut [f64; #size_u])),*
}
impl<'a> std::ops::Index<usize> for U<'a> {
type Output = f64;
fn index(&self, index: usize) -> &Self::Output {
match self {
#(U::#enum_u(data) => &data[index]),*
}
}
}
impl<'a> std::ops::IndexMut<usize> for U<'a> {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
match self {
#(U::#enum_u(data) => &mut data[index]),*
}
}
}
#[derive(Debug)]
pub enum Y<'a> {
#(#enum_y(&'a mut [f64; #size_y])),*
}
impl<'a> std::ops::Index<usize> for Y<'a> {
type Output = f64;
fn index(&self, index: usize) -> &Self::Output {
match self {
#(Y::#enum_y(data) => &data[index]),*
}
}
}
impl<'a> From<&Y<'a>> for Vec<f64> {
fn from(y: &Y<'a>) -> Vec<f64> {
match y {
#(Y::#enum_y(data) => data.to_vec()),*
}
}
}
pub struct Controller<'a> {
#(pub #var_u: U<'a>,)*
#(pub #var_y: Y<'a>,)*
}
paste::paste!{
impl<'a> Controller<'a> {
pub fn new() -> Self {
let mut this = unsafe {
Self {
#(#var_u: U::#enum_u(&mut [<#model _U>].#sim_u),)*
#(#var_y: Y::#enum_y(&mut [<#model _Y>].#sim_y),)*
}
};
this.initialize();
this
}
}}
paste::paste! {
impl<'a> Simulink for Controller<'a> {
fn initialize(&mut self) {
unsafe {
[<#model _initialize>]();
}
}
fn __step__(&self) {
unsafe {
[<#model _step>]();
}
}
fn terminate(&self) {
unsafe {
[<#model _terminate>]();
}
}
}
}
impl<'a> Drop for Controller<'a> {
fn drop(&mut self) {
self.terminate()
}
}
impl<'a> Iterator for &Controller<'a> {
type Item = ();
fn next(&mut self) -> Option<Self::Item> {
self.__step__();
Some(())
}
}
impl<'a> Iterator for Controller<'a> {
type Item = ();
fn next(&mut self) -> Option<Self::Item> {
self.__step__();
Some(())
}
}
impl<'a> Controller<'a> {
pub fn dispatch(pipe: &mut U<'a>, data: &[f64]) {
data.iter().enumerate().for_each(|(k, &v)| {
pipe[k] = v;
});
}
}
};
code.into()
}