fmi-export-derive 0.3.0

Proc-macro support for fmi-export
Documentation
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
use attribute_derive::FromAttr;
use proc_macro_error2::emit_error;

mod field_attr;
pub use field_attr::{
    AliasAttribute, ChildAttribute, FieldAttribute, FieldAttributeOuter, TerminalAttribute,
};

/// Helper function to extract docstring from a syn::Attribute
/// Follows DRY principles by centralizing doc attribute parsing logic
fn parse_doc_attribute(attr: &syn::Attribute) -> Option<String> {
    if attr.meta.path().is_ident("doc") {
        attr.meta.require_name_value().ok().and_then(|name_value| {
            if let syn::Expr::Lit(syn::ExprLit {
                lit: syn::Lit::Str(lit_str),
                ..
            }) = &name_value.value
            {
                let doc_line = lit_str.value();
                Some(doc_line.strip_prefix(' ').unwrap_or(&doc_line).to_string())
            } else {
                None
            }
        })
    } else {
        None
    }
}

/// StructAttribute represents the attributes that can be applied to the model struct
#[derive(Debug, attribute_derive::FromAttr, PartialEq, Clone, Default)]
#[attribute(ident = model)]
pub struct StructAttr {
    /// Optional model description (defaults to the struct docstring)
    #[attribute(optional)]
    pub description: Option<String>,

    /// Enable Model Exchange interface
    #[attribute(optional)]
    pub model_exchange: Option<bool>,

    /// Enable Co-Simulation interface
    #[attribute(optional)]
    pub co_simulation: Option<bool>,

    /// Enable Scheduled Execution interface
    #[attribute(optional)]
    pub scheduled_execution: Option<bool>,

    /// Whether to auto-generate a UserModel impl (default: true)
    #[attribute(optional)]
    pub user_model: Option<bool>,
}

#[derive(Debug, PartialEq, Clone)]
pub enum StructAttrOuter {
    Docstring(String),
    Model(StructAttr),
    Terminal(TerminalStructAttr),
}

/// Struct-level attributes for terminal generation
#[derive(Debug, attribute_derive::FromAttr, PartialEq, Clone, Default)]
#[attribute(ident = terminal)]
pub struct TerminalStructAttr {
    /// Optional terminal name override (defaults to struct name)
    #[attribute(optional)]
    pub name: Option<String>,
    /// Optional matching rule override (defaults to "bus")
    #[attribute(optional)]
    pub matching_rule: Option<String>,
    /// Optional terminal kind override
    #[attribute(optional)]
    pub terminal_kind: Option<String>,
}

/// Representation of an FmuModel field with it's parsed attributes
#[derive(Debug, PartialEq, Clone)]
pub struct Field {
    pub ident: syn::Ident,
    pub rust_type: syn::Type,
    pub attrs: Vec<FieldAttributeOuter>,
}

#[derive(Debug, PartialEq, Clone)]
pub struct Model {
    pub ident: syn::Ident,
    pub attrs: Vec<StructAttrOuter>,
    pub fields: Vec<Field>,
}

impl Field {
    /// Extract the description from field docstrings
    pub fn fold_description(&self) -> String {
        self.attrs
            .iter()
            .find_map(|attr| {
                if let FieldAttributeOuter::Docstring(doc) = attr {
                    Some(doc.clone())
                } else {
                    None
                }
            })
            .unwrap_or_else(|| "".to_string())
    }
}

impl Model {
    /// Returns an iterator over all continuous state fields.
    /// A field is considered a continuous state if another field has it as a derivative.
    pub fn iter_continuous_states(&self) -> impl Iterator<Item = &Field> {
        self.fields.iter().filter(move |field| {
            let field_name = field.ident.to_string();
            self.is_continuous_state(&field_name)
        })
    }

    /// Checks if a field with the given name is a continuous state variable.
    /// A field is a continuous state if another field has it as a derivative.
    pub fn is_continuous_state(&self, field_name: &str) -> bool {
        self.fields.iter().any(|other_field| {
            other_field.attrs.iter().any(|attr| {
                let derivative_ref = match attr {
                    FieldAttributeOuter::Variable(var_attr) => &var_attr.derivative,
                    _ => return false,
                };

                derivative_ref.as_ref().map(|d| d.to_string()) == Some(field_name.to_string())
            })
        })
    }

    /// Iterator over all fields that are derivatives.
    /// A field is considered a derivative if it has a derivative attribute.
    pub fn iter_derivatives(&self) -> impl Iterator<Item = &Field> {
        self.fields.iter().filter(|field| self.is_derivative(field))
    }

    /// Checks if a field is a derivative variable.
    /// A field is a derivative if it has a derivative attribute.
    pub fn is_derivative(&self, field: &Field) -> bool {
        field.attrs.iter().any(|attr| match attr {
            FieldAttributeOuter::Variable(var_attr) => var_attr.derivative.is_some(),
            _ => false,
        })
    }

    /// Get the parsed model attribute, if present
    pub fn get_model_attr(&self) -> Option<&StructAttr> {
        self.attrs.iter().find_map(|attr| match attr {
            StructAttrOuter::Model(model_attr) => Some(model_attr),
            _ => None,
        })
    }

    /// Get the parsed terminal attribute, if present
    pub fn get_terminal_attr(&self) -> Option<&TerminalStructAttr> {
        self.attrs.iter().find_map(|attr| match attr {
            StructAttrOuter::Terminal(terminal_attr) => Some(terminal_attr),
            _ => None,
        })
    }

    /// Check if Model Exchange is supported
    pub fn supports_model_exchange(&self) -> bool {
        self.get_model_attr()
            .and_then(|attr| attr.model_exchange)
            .unwrap_or(true) // Default to true if not specified
    }

    /// Check if Co-Simulation is supported
    pub fn supports_co_simulation(&self) -> bool {
        self.get_model_attr()
            .and_then(|attr| attr.co_simulation)
            .unwrap_or(false)
    }

    /// Check if Scheduled Execution is supported
    pub fn supports_scheduled_execution(&self) -> bool {
        self.get_model_attr()
            .and_then(|attr| attr.scheduled_execution)
            .unwrap_or(false)
    }

    /// Check if UserModel impl should be auto-generated
    pub fn auto_user_model(&self) -> bool {
        self.get_model_attr()
            .and_then(|attr| attr.user_model)
            .unwrap_or(true)
    }
}

impl TryFrom<syn::Field> for Field {
    type Error = String;
    fn try_from(field: syn::Field) -> Result<Self, String> {
        use attribute_derive::Attribute;
        let attrs = field
            .attrs
            .iter()
            .filter_map(|attr| match attr.meta.path().get_ident() {
                Some(ident) if ident == "doc" => {
                    parse_doc_attribute(attr).map(FieldAttributeOuter::Docstring)
                }

                Some(ident) if ident == "variable" => {
                    match FieldAttribute::from_attribute(attr).map(FieldAttributeOuter::Variable) {
                        Ok(attr) => Some(attr),
                        Err(e) => {
                            emit_error!(attr, format!("{e}"));
                            None
                        }
                    }
                }

                Some(ident) if ident == "alias" => {
                    match AliasAttribute::from_attribute(attr).map(FieldAttributeOuter::Alias) {
                        Ok(attr) => Some(attr),
                        Err(e) => {
                            emit_error!(attr, format!("{e}"));
                            None
                        }
                    }
                }

                Some(ident) if ident == "child" => {
                    match ChildAttribute::from_attribute(attr).map(FieldAttributeOuter::Child) {
                        Ok(attr) => Some(attr),
                        Err(e) => {
                            emit_error!(attr, format!("{e}"));
                            None
                        }
                    }
                }

                Some(ident) if ident == "terminal" => {
                    match TerminalAttribute::from_attribute(attr).map(FieldAttributeOuter::Terminal)
                    {
                        Ok(attr) => Some(attr),
                        Err(e) => {
                            emit_error!(attr, format!("{e}"));
                            None
                        }
                    }
                }

                _ => None,
            })
            .collect();

        Ok(Self {
            ident: field.ident.expect("Expected named field"),
            rust_type: field.ty,
            attrs,
        })
    }
}

/// Check for variable name conflicts with the built-in "time" variable
/// and for alias/variable name uniqueness.
fn check_time_variable_conflicts(fields: &[Field]) {
    let mut seen_names = std::collections::HashSet::new();

    for field in fields {
        let field_name = field.ident.to_string();

        // Check variable names (including custom name overrides)
        for attr in &field.attrs {
            if let FieldAttributeOuter::Variable(var_attr) = attr {
                let var_name = var_attr.name.as_deref().unwrap_or(&field_name);
                if var_name.to_lowercase() == "time" {
                    emit_error!(field.ident, "'time' is a reserved name.");
                }
                if !seen_names.insert(var_name.to_string()) {
                    emit_error!(
                        field.ident,
                        format!("Duplicate variable or alias name '{var_name}'.")
                    );
                }
            }
        }

        // Check alias names too
        for attr in &field.attrs {
            if let FieldAttributeOuter::Alias(alias_attr) = attr {
                let alias_name = alias_attr.name.as_str();
                if alias_name.to_lowercase() == "time" {
                    emit_error!(field.ident, "'time' is a reserved name.");
                }
                if !seen_names.insert(alias_name.to_string()) {
                    emit_error!(
                        field.ident,
                        format!("Duplicate variable or alias name '{alias_name}'.")
                    );
                }
            }
        }
    }
}

impl From<syn::DeriveInput> for Model {
    fn from(item: syn::DeriveInput) -> Self {
        if let syn::Data::Struct(struct_data) = item.data {
            let attrs = build_attrs(item.attrs);
            let fields = build_fields(struct_data.fields);

            // Check for time variable name conflicts
            check_time_variable_conflicts(&fields);

            Self {
                ident: item.ident,
                attrs,
                fields,
            }
        } else {
            emit_error!(item, "FmuModel can only be derived for structs");
            Self {
                ident: item.ident,
                attrs: vec![],
                fields: vec![],
            }
        }
    }
}

/// Parse struct-level attributes, accepting explicit boolean values
pub fn build_attrs(attrs: Vec<syn::Attribute>) -> Vec<StructAttrOuter> {
    attrs
        .into_iter()
        .filter_map(|attr| match attr.meta.path().get_ident() {
            Some(ident) if ident == "doc" => {
                parse_doc_attribute(&attr).map(StructAttrOuter::Docstring)
            }

            Some(ident) if ident == "model" => {
                // Prefer the derived parser; fall back to a manual tolerant parser for bool flags
                match StructAttr::from_attribute(attr.clone())
                    .or_else(|_e| parse_model_attr_bool(attr.clone()))
                {
                    Ok(attr) => Some(StructAttrOuter::Model(attr)),
                    Err(e) => {
                        emit_error!(attr, format!("{e}"));
                        None
                    }
                }
            }

            Some(ident) if ident == "terminal" => {
                match TerminalStructAttr::from_attribute(attr.clone()) {
                    Ok(attr) => Some(StructAttrOuter::Terminal(attr)),
                    Err(e) => {
                        emit_error!(attr, format!("{e}"));
                        None
                    }
                }
            }

            _ => None,
        })
        .collect()
}

/// Fallback parser that accepts boolean flags for co_simulation/model_exchange/scheduled_execution
fn parse_model_attr_bool(attr: syn::Attribute) -> Result<StructAttr, String> {
    let mut model_attr = StructAttr::default();

    let list = attr
        .meta
        .require_list()
        .map_err(|_| "expected a model attribute list like #[model(...)]".to_string())?;

    for nested in list
        .parse_args_with(syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated)
        .map_err(|_| "failed to parse #[model(...)] arguments".to_string())?
    {
        match nested {
            syn::Meta::NameValue(nv) if nv.path.is_ident("model_exchange") => {
                if let syn::Expr::Lit(syn::ExprLit {
                    lit: syn::Lit::Bool(lit_bool),
                    ..
                }) = nv.value
                {
                    model_attr.model_exchange = Some(lit_bool.value);
                } else {
                    return Err("model_exchange expects a boolean".into());
                }
            }
            syn::Meta::Path(path) if path.is_ident("model_exchange") => {
                return Err(
                    "model_exchange expects a boolean value, e.g. model_exchange = true".into(),
                );
            }
            syn::Meta::List(list) if list.path.is_ident("model_exchange") => {
                let _ = list;
                return Err(
                    "model_exchange expects a boolean value, e.g. model_exchange = true".into(),
                );
            }
            syn::Meta::NameValue(nv) if nv.path.is_ident("co_simulation") => {
                if let syn::Expr::Lit(syn::ExprLit {
                    lit: syn::Lit::Bool(lit_bool),
                    ..
                }) = nv.value
                {
                    model_attr.co_simulation = Some(lit_bool.value);
                } else {
                    return Err("co_simulation expects a boolean".into());
                }
            }
            syn::Meta::Path(path) if path.is_ident("co_simulation") => {
                return Err(
                    "co_simulation expects a boolean value, e.g. co_simulation = true".into(),
                );
            }
            syn::Meta::List(list) if list.path.is_ident("co_simulation") => {
                let _ = list;
                return Err(
                    "co_simulation expects a boolean value, e.g. co_simulation = true".into(),
                );
            }
            syn::Meta::NameValue(nv) if nv.path.is_ident("scheduled_execution") => {
                if let syn::Expr::Lit(syn::ExprLit {
                    lit: syn::Lit::Bool(lit_bool),
                    ..
                }) = nv.value
                {
                    model_attr.scheduled_execution = Some(lit_bool.value);
                } else {
                    return Err("scheduled_execution expects a boolean".into());
                }
            }
            syn::Meta::Path(path) if path.is_ident("scheduled_execution") => {
                return Err(
                    "scheduled_execution expects a boolean value, e.g. scheduled_execution = true"
                        .into(),
                );
            }
            syn::Meta::List(list) if list.path.is_ident("scheduled_execution") => {
                let _ = list;
                return Err(
                    "scheduled_execution expects a boolean value, e.g. scheduled_execution = true"
                        .into(),
                );
            }
            syn::Meta::NameValue(nv) if nv.path.is_ident("user_model") => {
                if let syn::Expr::Lit(syn::ExprLit {
                    lit: syn::Lit::Bool(lit_bool),
                    ..
                }) = nv.value
                {
                    model_attr.user_model = Some(lit_bool.value);
                } else {
                    return Err("user_model expects a boolean".into());
                }
            }
            syn::Meta::Path(path) if path.is_ident("user_model") => {
                return Err("user_model expects a boolean value, e.g. user_model = false".into());
            }
            syn::Meta::List(list) if list.path.is_ident("user_model") => {
                let _ = list;
                return Err("user_model expects a boolean value, e.g. user_model = false".into());
            }
            // Ignore unknown entries here and let the main parser report errors elsewhere
            _ => {}
        }
    }

    Ok(model_attr)
}

/// Check if a field has any FMU-relevant attributes (variable or alias)
fn has_fmu_attributes(field: &syn::Field) -> bool {
    field.attrs.iter().any(|attr| {
        attr.meta
            .path()
            .get_ident()
            .map(|ident| {
                ident == "variable" || ident == "alias" || ident == "child" || ident == "terminal"
            })
            .unwrap_or(false)
    })
}

pub fn build_fields(fields: syn::Fields) -> Vec<Field> {
    match fields {
        syn::Fields::Named(syn::FieldsNamed { named, .. }) => named
            .into_iter()
            .filter(has_fmu_attributes) // Only process fields with FMU attributes
            .filter_map(|ref field| match Field::try_from(field.clone()) {
                Ok(field) => Some(field),
                Err(e) => {
                    emit_error!(field, format!("{e}"));
                    None
                }
            })
            .collect(),
        _ => {
            emit_error!(fields, "Expected named fields in the struct");
            vec![]
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use attribute_derive::FromAttr;
    use fmi::fmi3::schema;

    #[test]
    fn test_attribute() {
        let input: syn::Attribute = syn::parse_quote! {
            #[variable(causality = Parameter, variability = Fixed, start = -9.81)]
        };
        let _attr = FieldAttribute::from_attribute(input).unwrap();

        let input: syn::Attribute = syn::parse_quote! {
            #[variable(causality = Output, start = 0.0)]
        };
        let _attr = FieldAttribute::from_attribute(input).unwrap();
    }

    #[test]
    fn test_fields_and_attributes() {
        let input: syn::ItemStruct = syn::parse_quote! {
            struct TestModel {
                /// Test1
                #[variable(causality = Output, start = 1.0)]
                h: f64,

                /// Test2
                #[variable(causality = Output, start = 0.0)]
                #[alias(name="alias_h", description = "Alias of h")]
                v: f64,
            }
        };
        let fields = build_fields(input.fields);

        assert_eq!(fields.len(), 2, "There should be 2 fields");
        assert_eq!(
            fields[0].attrs,
            vec![
                FieldAttributeOuter::Docstring("Test1".to_string()),
                FieldAttributeOuter::Variable(FieldAttribute {
                    causality: Some(schema::Causality::Output.into()),
                    start: Some(syn::parse_quote!(1.0)),
                    ..Default::default()
                })
            ],
            "First field should have 2 attributes: docstring and variable"
        );
        assert_eq!(
            fields[1].attrs,
            vec![
                FieldAttributeOuter::Docstring("Test2".to_string()),
                FieldAttributeOuter::Variable(FieldAttribute {
                    causality: Some(schema::Causality::Output.into()),
                    start: Some(syn::parse_quote!(0.0)),
                    ..Default::default()
                }),
                FieldAttributeOuter::Alias(AliasAttribute {
                    name: "alias_h".to_string(),
                    description: Some("Alias of h".to_string()),
                    display_unit: None,
                })
            ],
            "Second field should have 3 attributes: docstring, variable, and alias"
        );
    }

    #[test]
    fn test_field_description() {
        let input: syn::Field = syn::parse_quote! {
            /// This is a field description
            #[variable(causality = Output, start = 1.0)]
            height: f64
        };
        let field = Field::try_from(input).unwrap();
        assert_eq!(
            field.fold_description(),
            "This is a field description".to_string(),
            "Field description should match the docstring"
        );

        let input: syn::Field = syn::parse_quote! {
            #[variable(causality = Output, start = 1.0)]
            height: f64
        };
        let field = Field::try_from(input).unwrap();
        assert_eq!(
            field.fold_description(),
            "".to_string(),
            "Field description should be empty when no docstring"
        );
    }

    #[test]
    fn test_fields_without_fmu_attributes_are_ignored() {
        let input: syn::ItemStruct = syn::parse_quote! {
            struct TestModel {
                /// Height above ground (state output) - has FMU attribute
                #[variable(causality = Output, start = 1.0)]
                h: f64,

                /// User variable without FMU attributes - should be ignored
                internal_state: Vec<bool>,

                /// Another user variable - should be ignored
                helper_data: std::collections::HashMap<String, i32>,

                /// Velocity - has FMU attribute
                #[variable(causality = Output, start = 0.0)]
                v: f64,
            }
        };
        let fields = build_fields(input.fields);

        // Only fields with FMU attributes should be included
        assert_eq!(
            fields.len(),
            2,
            "Only fields with FMU attributes should be processed"
        );
        assert_eq!(fields[0].ident.to_string(), "h");
        assert_eq!(fields[1].ident.to_string(), "v");
    }
}