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
use proc_macro_error2::emit_error;
use proc_macro2::TokenStream as TokenStream2;
use quote::{ToTokens, format_ident, quote};
use std::collections::HashMap;

use crate::Model;
use crate::model::{AliasAttribute, Field, FieldAttributeOuter};

pub struct BuildMetadataGen<'a> {
    model: &'a Model,
}

impl<'a> BuildMetadataGen<'a> {
    pub fn new(model: &'a Model) -> Self {
        Self { model }
    }

    fn is_clock_type(&self, ty: &syn::Type) -> bool {
        match ty {
            syn::Type::Path(type_path) => type_path
                .path
                .segments
                .last()
                .map(|segment| segment.ident == "Clock")
                .unwrap_or(false),
            _ => false,
        }
    }

    fn is_float_type(&self, ty: &syn::Type) -> bool {
        match ty {
            syn::Type::Path(type_path) => {
                let last = type_path.path.segments.last();
                match last.map(|segment| segment.ident.to_string()) {
                    Some(ident) if ident == "f32" || ident == "f64" => true,
                    Some(ident) if ident == "Vec" => segment_has_float_arg(last),
                    Some(ident) if ident == "Option" => segment_has_float_arg(last),
                    Some(ident) if ident == "Box" => segment_has_float_arg(last),
                    _ => false,
                }
            }
            syn::Type::Array(array) => self.is_float_type(&array.elem),
            syn::Type::Reference(reference) => self.is_float_type(&reference.elem),
            _ => false,
        }
    }
}

fn segment_has_float_arg(segment: Option<&syn::PathSegment>) -> bool {
    let Some(segment) = segment else {
        return false;
    };
    let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
        return false;
    };
    args.args.iter().any(|arg| match arg {
        syn::GenericArgument::Type(ty) => matches_float_type(ty),
        _ => false,
    })
}

fn matches_float_type(ty: &syn::Type) -> bool {
    match ty {
        syn::Type::Path(type_path) => type_path
            .path
            .segments
            .last()
            .map(|segment| matches!(segment.ident.to_string().as_str(), "f32" | "f64"))
            .unwrap_or(false),
        syn::Type::Array(array) => matches_float_type(&array.elem),
        syn::Type::Reference(reference) => matches_float_type(&reference.elem),
        _ => false,
    }
}

impl ToTokens for BuildMetadataGen<'_> {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        let prefix_binding = quote! { prefix.unwrap_or("") };

        // Build a map of field names to their assigned value references
        let mut field_name_to_vr = HashMap::new();
        let mut current_vr = 0u32; // Start at 0, will be added to vr_offset (1) to get actual VRs starting at 1

        // First pass: assign VRs to all fields with variable attributes (excluding skipped ones)
        for field in &self.model.fields {
            if self.has_skip_attribute(field) {
                // Skip fields with skip=true
                continue;
            }

            for attr in &field.attrs {
                match attr {
                    FieldAttributeOuter::Variable(_) => {
                        field_name_to_vr.insert(field.ident.to_string(), current_vr);
                        current_vr += 1;
                    }
                    FieldAttributeOuter::Alias(_) => {
                        // Ignore Alias attributes for now
                    }
                    FieldAttributeOuter::Child(_) => {
                        // Child fields are flattened in a later pass; VRs are assigned then
                    }
                    FieldAttributeOuter::Terminal(_) => {
                        // Terminals are handled separately
                    }
                    FieldAttributeOuter::Docstring(_) => {
                        // Skip docstrings
                    }
                }
            }
        }

        let mut variable_tokens = Vec::new();
        let mut model_structure_tokens = Vec::new();
        let vr_offset_tracking = quote! { let mut current_vr_offset = vr_offset; };

        // Second pass: generate the actual variable definitions
        for field in &self.model.fields {
            if self.has_skip_attribute(field) {
                // For fields with skip=true, don't generate anything
                continue;
            } else if self.is_child_field(field) {
                // For child fields, recursively call build_metadata and prefix variable names
                let field_type = &field.rust_type;
                let field_name = field.ident.to_string();
                let child_prefix_lit = self.child_prefix_literal(field, &field_name);
                variable_tokens.push(quote! {
                    let child_prefix = format!("{}{}.", #prefix_binding, #child_prefix_lit);
                    let field_count = <#field_type as ::fmi_export::fmi3::Model>::build_metadata(
                        variables,
                        model_structure,
                        current_vr_offset,
                        Some(child_prefix.as_str())
                    );

                    current_vr_offset += field_count;
                });
            } else if self.has_no_variable_attributes(field) {
                // For fields with no attributes, recursively call build_metadata
                let field_type = &field.rust_type;
                variable_tokens.push(quote! {
                    let field_count = <#field_type as ::fmi_export::fmi3::Model>::build_metadata(variables, model_structure, current_vr_offset, Some(#prefix_binding));
                    current_vr_offset += field_count;
                });
            } else {
                // Generate variables for this field
                for attr in &field.attrs {
                    match attr {
                        FieldAttributeOuter::Variable(var_attr) => {
                            let alias_attrs: Vec<&AliasAttribute> = field
                                .attrs
                                .iter()
                                .filter_map(|attr| match attr {
                                    FieldAttributeOuter::Alias(alias_attr) => Some(alias_attr),
                                    _ => None,
                                })
                                .collect();
                            let mut added_initial_unknown = false;
                            let var_token = self.generate_variable_definition(
                                field,
                                var_attr,
                                &field.ident.to_string(),
                                &field_name_to_vr,
                                &prefix_binding,
                                &alias_attrs,
                            );
                            variable_tokens.push(var_token);

                            // Generate model structure entries for derivatives
                            if let Some(derivative_ref) = &var_attr.derivative {
                                let derivative_name = derivative_ref.to_string();
                                if field_name_to_vr.contains_key(&derivative_name) {
                                    let current_vr = field_name_to_vr[&field.ident.to_string()];

                                    // Add this field (derivative) to continuous_state_derivative
                                    model_structure_tokens.push(quote! {
                                        model_structure.unknowns.push(::fmi::schema::fmi3::VariableDependency::ContinuousStateDerivative(::fmi::schema::fmi3::Fmi3Unknown {
                                            annotations: None,
                                            value_reference: current_vr_offset + #current_vr,
                                            dependencies: None,
                                            dependencies_kind: None,
                                        }));
                                    });

                                    // Add this field to initial_unknown if it has initial = Calculated
                                    if let Some(initial) = &var_attr.initial {
                                        let initial_schema: ::fmi::fmi3::schema::Initial =
                                            (*initial).into();
                                        if matches!(
                                            initial_schema,
                                            ::fmi::fmi3::schema::Initial::Calculated
                                        ) {
                                            model_structure_tokens.push(quote! {
                                                model_structure.unknowns.push(::fmi::schema::fmi3::VariableDependency::InitialUnknown(::fmi::schema::fmi3::Fmi3Unknown {
                                                    annotations: None,
                                                    value_reference: current_vr_offset + #current_vr,
                                                    dependencies: None,
                                                    dependencies_kind: None,
                                                }));
                                            });
                                            added_initial_unknown = true;
                                        }
                                    }
                                }
                            }

                            // Generate outputs for fields with Output causality
                            if let Some(causality) = &var_attr.causality {
                                let causality_schema: ::fmi::fmi3::schema::Causality =
                                    (*causality).into();
                                if matches!(
                                    causality_schema,
                                    ::fmi::fmi3::schema::Causality::Output
                                ) {
                                    let current_vr = field_name_to_vr[&field.ident.to_string()];

                                    // Find if any other field has this field as derivative
                                    let mut derivative_vr = None;
                                    for other_field in &self.model.fields {
                                        for other_attr in &other_field.attrs {
                                            if let FieldAttributeOuter::Variable(other_var_attr) =
                                                other_attr
                                                && let Some(other_derivative_ref) =
                                                    &other_var_attr.derivative
                                                && other_derivative_ref == &field.ident
                                                && let Some(&other_vr) = field_name_to_vr
                                                    .get(&other_field.ident.to_string())
                                            {
                                                derivative_vr = Some(other_vr);
                                                break;
                                            }
                                        }
                                        if derivative_vr.is_some() {
                                            break;
                                        }
                                    }

                                    if let Some(dep_vr) = derivative_vr {
                                        model_structure_tokens.push(quote! {
                                            model_structure.unknowns.push(::fmi::schema::fmi3::VariableDependency::Output(::fmi::schema::fmi3::Fmi3Unknown {
                                                annotations: None,
                                                value_reference: current_vr_offset + #current_vr,
                                                dependencies: Some(::fmi::schema::utils::AttrList(vec![current_vr_offset + #dep_vr])),
                                                dependencies_kind: Some(::fmi::schema::utils::AttrList(vec![::fmi::schema::fmi3::DependenciesKind::Dependent])),
                                            }));
                                        });
                                    } else {
                                        // Output without dependencies
                                        model_structure_tokens.push(quote! {
                                            model_structure.unknowns.push(::fmi::schema::fmi3::VariableDependency::Output(::fmi::schema::fmi3::Fmi3Unknown {
                                                annotations: None,
                                                value_reference: current_vr_offset + #current_vr,
                                                dependencies: None,
                                                dependencies_kind: None,
                                            }));
                                        });
                                    }
                                }
                            }

                            // Output clocks must be listed in InitialUnknowns
                            if let Some(causality) = &var_attr.causality {
                                let causality_schema: ::fmi::fmi3::schema::Causality =
                                    (*causality).into();
                                if matches!(
                                    causality_schema,
                                    ::fmi::fmi3::schema::Causality::Output
                                ) && self.is_clock_type(&field.rust_type)
                                {
                                    let current_vr = field_name_to_vr[&field.ident.to_string()];
                                    model_structure_tokens.push(quote! {
                                        model_structure.unknowns.push(::fmi::schema::fmi3::VariableDependency::InitialUnknown(::fmi::schema::fmi3::Fmi3Unknown {
                                            annotations: None,
                                            value_reference: current_vr_offset + #current_vr,
                                            dependencies: None,
                                            dependencies_kind: None,
                                        }));
                                    });
                                }
                            }

                            // Generate model structure entries for event indicators
                            if matches!(var_attr.event_indicator, Some(true)) {
                                let current_vr = field_name_to_vr[&field.ident.to_string()];
                                model_structure_tokens.push(quote! {
                                    model_structure.unknowns.push(::fmi::schema::fmi3::VariableDependency::EventIndicator(::fmi::schema::fmi3::Fmi3Unknown {
                                        annotations: None,
                                        value_reference: current_vr_offset + #current_vr,
                                        dependencies: None,
                                        dependencies_kind: None,
                                    }));
                                });
                            }

                            // Add any variable with initial=Calculated to InitialUnknowns
                            if !added_initial_unknown && let Some(initial) = &var_attr.initial {
                                let initial_schema: ::fmi::fmi3::schema::Initial =
                                    (*initial).into();
                                if matches!(
                                    initial_schema,
                                    ::fmi::fmi3::schema::Initial::Calculated
                                ) {
                                    // Skip clocked variables; the triggering clock handles initial unknowns.
                                    if var_attr
                                        .clocks
                                        .as_ref()
                                        .is_none_or(|clocks| clocks.is_empty())
                                    {
                                        let current_vr = field_name_to_vr[&field.ident.to_string()];
                                        model_structure_tokens.push(quote! {
                                                model_structure.unknowns.push(::fmi::schema::fmi3::VariableDependency::InitialUnknown(::fmi::schema::fmi3::Fmi3Unknown {
                                                    annotations: None,
                                                    value_reference: current_vr_offset + #current_vr,
                                                    dependencies: None,
                                                    dependencies_kind: None,
                                                }));
                                            });
                                    }
                                }
                            }
                        }
                        FieldAttributeOuter::Alias(_) => {
                            // Ignore Alias attributes for now
                        }
                        FieldAttributeOuter::Child(_) => {
                            // Child fields are handled separately
                        }
                        FieldAttributeOuter::Terminal(_) => {
                            // Terminals are handled separately
                        }
                        FieldAttributeOuter::Docstring(_) => {
                            // Skip docstrings
                        }
                    }
                }
            }
        }

        // Count how many variables this model defines
        let own_variable_count = field_name_to_vr.len() as u32;

        tokens.extend(quote! {
            use ::fmi_export::fmi3::FmiVariableBuilder;
            use ::fmi::schema::fmi3::AppendToModelVariables;
            #vr_offset_tracking
            #(#variable_tokens)*
            #(#model_structure_tokens)*
            current_vr_offset - vr_offset + #own_variable_count
        });
    }
}

impl BuildMetadataGen<'_> {
    /// Check if a field has the skip attribute set to true
    fn has_skip_attribute(&self, field: &Field) -> bool {
        field
            .attrs
            .iter()
            .any(|attr| matches!(attr, FieldAttributeOuter::Variable(var_attr) if var_attr.skip))
    }

    /// Check if a field has no variable attributes (ignoring docstrings and aliases)
    fn has_no_variable_attributes(&self, field: &Field) -> bool {
        !field
            .attrs
            .iter()
            .any(|attr| matches!(attr, FieldAttributeOuter::Variable(_)))
    }

    fn is_child_field(&self, field: &Field) -> bool {
        field
            .attrs
            .iter()
            .any(|attr| matches!(attr, FieldAttributeOuter::Child(_)))
    }

    fn child_prefix_literal(&self, field: &Field, default_name: &str) -> syn::LitStr {
        let prefix = field.attrs.iter().find_map(|attr| {
            if let FieldAttributeOuter::Child(child_attr) = attr {
                child_attr.prefix.as_deref()
            } else {
                None
            }
        });
        let prefix = prefix.unwrap_or(default_name);
        syn::LitStr::new(prefix, field.ident.span())
    }

    /// Generate a variable definition for a field
    fn generate_variable_definition(
        &self,
        field: &Field,
        var_attr: &crate::model::FieldAttribute,
        var_name: &str,
        field_name_to_vr: &HashMap<String, u32>,
        prefix_binding: &TokenStream2,
        alias_attrs: &[&AliasAttribute],
    ) -> TokenStream2 {
        let field_type = &field.rust_type;
        let current_vr = field_name_to_vr[var_name];
        let is_float = self.is_float_type(&field.rust_type);

        // Use the name attribute if specified, otherwise use the field name
        let variable_name = var_attr
            .name
            .clone()
            .unwrap_or_else(|| field.ident.to_string());
        let variable_name_prefixed = quote! { format!("{}{}", #prefix_binding, #variable_name) };

        // Build the variable definition
        let mut builder_calls = Vec::new();

        // Set causality if specified
        if let Some(causality) = &var_attr.causality {
            let causality_schema: fmi::fmi3::schema::Causality = (*causality).into();
            let causality_str = format!("{:?}", causality_schema);
            let causality_variant = format_ident!("{}", causality_str);
            builder_calls.push(quote! {
                .with_causality(::fmi::fmi3::schema::Causality::#causality_variant)
            });
        }

        // Set variability if specified
        if let Some(variability) = &var_attr.variability {
            let variability_schema: fmi::fmi3::schema::Variability = (*variability).into();
            let variability_str = format!("{:?}", variability_schema);
            let variability_variant = format_ident!("{}", variability_str);
            builder_calls.push(quote! {
                .with_variability(::fmi::fmi3::schema::Variability::#variability_variant)
            });
        }

        // Default variability based on FMI3 spec if not provided explicitly.
        if var_attr.variability.is_none()
            && let Some(causality) = &var_attr.causality
        {
            let causality_schema: ::fmi::fmi3::schema::Causality = (*causality).into();
            let default_variability = match causality_schema {
                ::fmi::fmi3::schema::Causality::Parameter
                | ::fmi::fmi3::schema::Causality::CalculatedParameter
                | ::fmi::fmi3::schema::Causality::StructuralParameter => {
                    ::fmi::fmi3::schema::Variability::Fixed
                }
                _ if is_float => ::fmi::fmi3::schema::Variability::Continuous,
                _ => ::fmi::fmi3::schema::Variability::Discrete,
            };
            let variability_str = format!("{:?}", default_variability);
            let variability_variant = format_ident!("{}", variability_str);
            builder_calls.push(quote! {
                .with_variability(::fmi::fmi3::schema::Variability::#variability_variant)
            });
        }

        // Set interval variability if specified (for Clock variables)
        if let Some(interval_variability) = &var_attr.interval_variability {
            let interval_variability_schema: fmi::fmi3::schema::IntervalVariability =
                (*interval_variability).into();
            let interval_variability_str = format!("{:?}", interval_variability_schema);
            let interval_variability_variant = format_ident!("{}", interval_variability_str);
            builder_calls.push(quote! {
                .with_interval_variability(
                    ::fmi::fmi3::schema::IntervalVariability::#interval_variability_variant
                )
            });
        }

        // Set start value if specified
        if let Some(start) = &var_attr.start {
            builder_calls.push(quote! {
                .with_start(#start)
            });
        }

        // Set initial if specified
        if let Some(initial) = &var_attr.initial {
            let initial_schema: fmi::fmi3::schema::Initial = (*initial).into();
            let initial_str = format!("{:?}", initial_schema);
            let initial_variant = format_ident!("{}", initial_str);
            builder_calls.push(quote! {
                .with_initial(::fmi::fmi3::schema::Initial::#initial_variant)
            });
        }

        // Set derivative if specified
        if let Some(derivative_ref) = &var_attr.derivative {
            let derivative_name = derivative_ref.to_string();
            if let Some(&derivative_vr) = field_name_to_vr.get(&derivative_name) {
                builder_calls.push(quote! {
                    .with_derivative(current_vr_offset + #derivative_vr)
                });
            }
        }

        // Set max_size if specified (for Binary variables)
        if let Some(max_size) = var_attr.max_size {
            builder_calls.push(quote! {
                .with_max_size(#max_size)
            });
        }

        // Set mime_type if specified (for Binary variables)
        if let Some(mime_type) = &var_attr.mime_type {
            builder_calls.push(quote! {
                .with_mime_type(#mime_type)
            });
        }

        // Set clocks if specified
        if let Some(clocks) = &var_attr.clocks {
            // Convert Vec<syn::Ident> to Vec<u32> by looking up VRs and adding vr_offset
            let clock_vrs: Vec<u32> = clocks
                .iter()
                .filter_map(|clock_ident| {
                    let clock_name = clock_ident.to_string();
                    field_name_to_vr.get(&clock_name).map(|&vr| vr + 1) // Add 1 for vr_offset
                })
                .collect();

            if !clock_vrs.is_empty() {
                builder_calls.push(quote! {
                    .with_clocks(vec![#(#clock_vrs),*])
                });
            }
        }

        // Set description from field docstring or attribute
        let description = if let Some(attr_desc) = &var_attr.description {
            quote! { .with_description(#attr_desc) }
        } else {
            let field_desc = field.fold_description();
            if !field_desc.is_empty() {
                quote! { .with_description(#field_desc) }
            } else {
                quote! {}
            }
        };

        let alias_tokens: Vec<TokenStream2> = alias_attrs
            .iter()
            .map(|alias_attr| {
                if alias_attr.display_unit.is_some() && !is_float {
                    emit_error!(
                        field.ident,
                        "alias display_unit is only allowed for Float32/Float64 variables"
                    );
                }

                let alias_name_lit = syn::LitStr::new(&alias_attr.name, field.ident.span());
                let alias_name_prefixed =
                    quote! { format!("{}{}", #prefix_binding, #alias_name_lit) };
                let alias_description = alias_attr.description.as_ref().map_or_else(
                    || quote! { None },
                    |desc| {
                        let desc_lit = syn::LitStr::new(desc, field.ident.span());
                        quote! { Some(#desc_lit.to_string()) }
                    },
                );
                let alias_display_unit = alias_attr.display_unit.as_ref().map_or_else(
                    || quote! { None },
                    |display_unit| {
                        let display_unit_lit = syn::LitStr::new(display_unit, field.ident.span());
                        quote! { Some(#display_unit_lit.to_string()) }
                    },
                );

                if is_float {
                    quote! {
                        var.aliases.push(::fmi::schema::fmi3::FloatVariableAlias {
                            name: #alias_name_prefixed,
                            description: #alias_description,
                            display_unit: #alias_display_unit,
                        });
                    }
                } else {
                    quote! {
                        var.aliases.push(::fmi::schema::fmi3::VariableAlias {
                            name: #alias_name_prefixed,
                            description: #alias_description,
                        });
                    }
                }
            })
            .collect();

        quote! {
            let mut var = <#field_type as ::fmi_export::fmi3::FmiVariableBuilder>::variable(#variable_name_prefixed, current_vr_offset + #current_vr)
                #description
                #(#builder_calls)*
                .finish();
            #(#alias_tokens)*
            var.append_to_variables(variables);
        }
    }
}