simics 0.2.3

Intel® Simics® Simulator bindings in high level, idiomatic Rust
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
// Copyright (C) 2024 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

use anyhow::{anyhow, Result};
use prettyplease::unparse;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote, ToTokens};
use simics_build_utils::{emit_cfg_directives, emit_link_info};
use std::{collections::HashMap, env::var, fs::write, path::PathBuf};
use syn::{
    parse_file, parse_quote, punctuated::Punctuated, token::Plus, Attribute, BareFnArg, Expr,
    Field, GenericArgument, Ident, Item, ItemConst, ItemStruct, ItemType, Lit, Meta, PathArguments,
    ReturnType, Type, TypeParamBound, Visibility,
};

/// The name of the environment variable set by cargo containing the path to the out directory
/// for intermediate build results
const OUT_DIR_ENV: &str = "OUT_DIR";
/// The name of the environment variable containing the path to the simics base directory e.g.
/// `/path/to/simics/simics-7.0.1`
const SIMICS_BASE_ENV: &str = "SIMICS_BASE";

use simics_api_sys::SIMICS_API_BINDINGS;

const INTERFACES_FILE: &str = "interfaces.rs";
const HAPS_FILE: &str = "haps.rs";

/// Extension trait to convert snake_case to CamelCase.
trait SnakeToCamel {
    fn snake_to_camel(&self) -> String;
}

impl<S> SnakeToCamel for S
where
    S: AsRef<str>,
{
    fn snake_to_camel(&self) -> String {
        let mut s = String::new();
        let mut upper = false;
        for c in self.as_ref().chars() {
            if upper || s.is_empty() {
                s.push(c.to_ascii_uppercase());
                upper = false;
            } else if c == '_' {
                upper = true;
            } else {
                s.push(c.to_ascii_lowercase());
            }
        }
        s
    }
}

struct HapStruct {
    name: Ident,
    callback_ty: Vec<TypeParamBound>,
    handler_name: Ident,
    supports_index_callbacks: Option<String>,
    callback_attrs: Vec<Attribute>,
    struct_name: Ident,
    closure_param_names: Vec<Ident>,
    inputs: Vec<BareFnArg>,
    output: Type,
    userdata_name: Ident,
}

impl TryFrom<(&ItemConst, &ItemType)> for HapStruct {
    type Error = darling::Error;

    fn try_from(name_ty: (&ItemConst, &ItemType)) -> darling::Result<Self> {
        let name = name_ty.0.ident.clone();
        let callback_type = name_ty.1;
        let callback_attrs = callback_type.attrs.to_vec();

        let supports_index_callbacks = callback_attrs.iter().find_map(|a| {
            let Meta::NameValue(ref meta) = a.meta else {
                return None;
            };

            let Expr::Lit(ref lit) = meta.value else {
                return None;
            };

            let Lit::Str(ref str_lit) = lit.lit else {
                return None;
            };

            if !str_lit.value().contains("Index: Indices not supported") {
                Some(str_lit.value())
            } else {
                None
            }
        });

        let struct_name = format_ident!(
            "{}Hap",
            callback_type
                .ident
                .to_string()
                .trim_end_matches("_hap_callback")
                .to_string()
                .snake_to_camel()
        );

        let handler_name = format_ident!(
            "{}",
            "handle_".to_string()
                + callback_type
                    .ident
                    .to_string()
                    .trim_end_matches("_hap_callback"),
        );

        let Type::Path(ref p) = &*callback_type.ty else {
            return Err(Self::Error::custom(format!(
                "Failed to parse callback type {:?} as path",
                callback_type
            )));
        };

        let last = p.path.segments.last().ok_or_else(|| {
            Self::Error::custom(format!(
                "Failed to get final segment from path type {:?}",
                callback_type
            ))
        })?;

        if last.ident != "Option" {
            return Err(Self::Error::custom(format!(
                "Callback type must be Option to support null-optimization, got {:?}",
                callback_type
            )));
        }

        let PathArguments::AngleBracketed(ref args) = last.arguments else {
            return Err(Self::Error::custom(format!(
                "Failed to get angle bracketed arguments from path type {:?}",
                callback_type
            )));
        };

        let Some(GenericArgument::Type(Type::BareFn(proto))) = args.args.first() else {
            return Err(Self::Error::custom(format!(
                "Failed to get bare function type from path type {:?}",
                callback_type
            )));
        };

        // NOTE: We `use crate::api::sys::*;` at the top of the module, otherwise
        // we would need to rewrite all of the types on `inputs` here.
        let inputs = proto.inputs.iter().cloned().collect::<Vec<_>>();

        let input_names = inputs
            .iter()
            .map(|a| {
                a.name.clone().map(|n| n.0).ok_or_else(|| {
                    Self::Error::custom(format!("Failed to get name from input argument {:?}", a))
                })
            })
            .collect::<darling::Result<Vec<_>>>()?;

        let userdata_name = input_names
            .first()
            .ok_or_else(|| {
                Self::Error::custom(format!(
                    "Failed to get userdata name from input arguments {:?}",
                    inputs
                ))
            })?
            .clone();

        let output = match &proto.output {
            ReturnType::Default => parse_quote!(()),
            ReturnType::Type(_, t) => parse_quote!(#t),
        };

        let closure_params = inputs
            .iter()
            .skip(1)
            .cloned()
            .map(|a| a.ty)
            .collect::<Vec<_>>();
        let closure_param_names = input_names.iter().skip(1).cloned().collect::<Vec<_>>();
        let callback_ty: Punctuated<TypeParamBound, Plus> =
            parse_quote!(FnMut(#(#closure_params),*) -> #output + 'static);
        let callback_ty = callback_ty.iter().cloned().collect::<Vec<_>>();

        Ok(Self {
            name,
            callback_ty,
            handler_name,
            supports_index_callbacks,
            callback_attrs,
            struct_name,
            closure_param_names,
            inputs,
            output,
            userdata_name,
        })
    }
}

impl ToTokens for HapStruct {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        let callback_ty = &self.callback_ty;
        let handler_name = &self.handler_name;
        let add_callback_methods = quote! {
            /// Add a callback to be called on each occurrence of this HAP. The callback may capture its environment.
            ///
            /// # Arguments
            ///
            /// * `callback` - The closure to fire as a callback. The closure will be doubly boxed. Any program state accessed inside
            ///   the closure must have the static lifetime. This is not enforced by the compiler, it is up to the programmer to ensure
            ///   the soundness of their callback code.
            pub fn add_callback<F>(callback: F) -> crate::Result<crate::api::simulator::hap_consumer::HapHandle>
            where
                F: #(#callback_ty)+*,
            {
                let callback = Box::new(callback);
                let callback_box = Box::new(callback);
                let callback_raw = Box::into_raw(callback_box);
                let handler: unsafe extern "C" fn() = unsafe { std::mem::transmute(#handler_name::<F> as usize) };
                Ok(unsafe {
                    crate::api::sys::SIM_hap_add_callback(
                        Self::NAME.as_raw_cstr()?,
                        Some(handler),
                        callback_raw as *mut std::ffi::c_void,
                    )
                })
            }

            /// Add a callback to be called on each occurrence of this HAP for a specific object. The callback may capture its environment.
            ///
            /// # Arguments
            ///
            /// * `callback` - The closure to fire as a callback. The closure will be doubly boxed. Any program state accessed inside
            ///   the closure must have the static lifetime. This is not enforced by the compiler, it is up to the programmer to ensure
            ///   the soundness of their callback code.
            /// * `obj` - The object to fire this callback for. This HAP will not trigger the callback when firing on any object other than
            ///   this one.
            pub fn add_callback_object<F>(callback: F, obj: *mut crate::api::ConfObject) -> crate::Result<crate::api::simulator::hap_consumer::HapHandle>
            where
                F: #(#callback_ty)+*,
            {
                let callback = Box::new(callback);
                let callback_box = Box::new(callback);
                let callback_raw = Box::into_raw(callback_box);
                let handler: unsafe extern "C" fn() = unsafe { std::mem::transmute(#handler_name::<F> as usize) };
                Ok(unsafe {
                    crate::api::sys::SIM_hap_add_callback_obj(
                        Self::NAME.as_raw_cstr()?,
                        obj,
                        0,
                        Some(handler),
                        callback_raw as *mut std::ffi::c_void,
                    )
                })
            }
        };

        let maybe_index_callback_methods = if let Some(ref index) = self.supports_index_callbacks {
            let index_doc = format!("* `index` - The index value for this HAP: {}", index);
            let range_start_doc = format!(
                "* `start` - The start of the range of index values for this HAP: {}",
                index
            );
            let range_end_doc = format!(
                "* `end` - The start of the range of index values for this HAP: {}",
                index
            );

            quote! {
                /// Add a callback to be called on each occurrence of this HAP for a specific index value. The callback may capture its environment.
                ///
                /// Only HAPs which support an index may add a callback in this manner, and the index varies for each HAP. For example, the
                /// [`CoreMagicInstructionHap`] supports an index equal to the magic value.
                ///
                /// # Arguments
                ///
                /// * `callback` - The closure to fire as a callback. The closure will be doubly boxed. Any program state accessed inside
                ///   the closure must have the static lifetime. This is not enforced by the compiler, it is up to the programmer to ensure
                ///   the soundness of their callback code.
                #[doc = #index_doc]
                pub fn add_callback_index<F>(callback: F, index: i64) -> crate::Result<crate::api::simulator::hap_consumer::HapHandle>
                where
                    F: #(#callback_ty)+*,
                {
                    let callback = Box::new(callback);
                    let callback_box = Box::new(callback);
                    let callback_raw = Box::into_raw(callback_box);
                    let handler: unsafe extern "C" fn() = unsafe { std::mem::transmute(#handler_name::<F> as usize) };
                    Ok(unsafe {
                        crate::api::sys::SIM_hap_add_callback_index(
                            Self::NAME.as_raw_cstr()?,
                            Some(handler),
                            callback_raw as *mut std::ffi::c_void,
                            index
                        )
                    })
                }

                /// Add a callback to be called on each occurrence of this HAP for a specific index value range. The callback may capture its environment.
                ///
                /// Only HAPs which support an index may add a callback in this manner, and the index varies for each HAP. For example, the
                /// [`CoreMagicInstructionHap`] supports an index equal to the magic value.
                ///
                /// # Arguments
                ///
                /// * `callback` - The closure to fire as a callback. The closure will be doubly boxed. Any program state accessed inside
                ///   the closure must have the static lifetime. This is not enforced by the compiler, it is up to the programmer to ensure
                ///   the soundness of their callback code.
                #[doc = #range_start_doc]
                #[doc = #range_end_doc]
                pub fn add_callback_range<F>(callback: F, start: i64, end: i64) -> crate::Result<crate::api::simulator::hap_consumer::HapHandle>
                where
                    F: #(#callback_ty)+*,
                {
                    let callback = Box::new(callback);
                    let callback_box = Box::new(callback);
                    let callback_raw = Box::into_raw(callback_box);
                    let handler: unsafe extern "C" fn() = unsafe { std::mem::transmute(#handler_name::<F> as usize) };
                    Ok(unsafe {
                        crate::api::sys::SIM_hap_add_callback_range(
                            Self::NAME.as_raw_cstr()?,
                            Some(handler),
                            callback_raw as *mut std::ffi::c_void,
                            start,
                            end,
                        )
                    })
                }

                /// Add a callback to be called on each occurrence of this HAP on a specific object for a specific index value. The callback may capture its environment.
                ///
                /// Only HAPs which support an index may add a callback in this manner, and the index varies for each HAP. For example, the
                /// [`CoreMagicInstructionHap`] supports an index equal to the magic value.
                ///
                /// # Arguments
                ///
                /// * `callback` - The closure to fire as a callback. The closure will be doubly boxed. Any program state accessed inside
                ///   the closure must have the static lifetime. This is not enforced by the compiler, it is up to the programmer to ensure
                ///   the soundness of their callback code.
                /// * `obj` - The object to fire this callback for. This HAP will not trigger the callback when firing on any object other than
                ///   this one.
                #[doc = #index_doc]
                pub fn add_callback_object_index<F>(callback: F, obj: *mut crate::api::ConfObject, index: i64) -> crate::Result<crate::api::simulator::hap_consumer::HapHandle>
                where
                    F: #(#callback_ty)+*,
                {
                    let callback = Box::new(callback);
                    let callback_box = Box::new(callback);
                    let callback_raw = Box::into_raw(callback_box);
                    let handler: unsafe extern "C" fn() = unsafe { std::mem::transmute(#handler_name::<F> as usize) };
                    Ok(unsafe {
                        crate::api::sys::SIM_hap_add_callback_obj_index(
                            Self::NAME.as_raw_cstr()?,
                            obj,
                            0,
                            Some(handler),
                            callback_raw as *mut std::ffi::c_void,
                            index
                        )
                    })
                }

                /// Add a callback to be called on each occurrence of this HAP on a specific object for a specific index value range. The callback may capture its environment.
                ///
                /// Only HAPs which support an index may add a callback in this manner, and the index varies for each HAP. For example, the
                /// [`CoreMagicInstructionHap`] supports an index equal to the magic value.
                ///
                /// # Arguments
                ///
                /// * `callback` - The closure to fire as a callback. The closure will be doubly boxed. Any program state accessed inside
                ///   the closure must have the static lifetime. This is not enforced by the compiler, it is up to the programmer to ensure
                ///   the soundness of their callback code.
                /// * `obj` - The object to fire this callback for. This HAP will not trigger the callback when firing on any object other than
                ///   this one.
                #[doc = #range_start_doc]
                #[doc = #range_end_doc]
                pub fn add_callback_object_range<F>(callback: F, obj: *mut crate::api::ConfObject, start: i64, end: i64) -> crate::Result<crate::api::simulator::hap_consumer::HapHandle>
                where
                    F: #(#callback_ty)+*,
                {
                    let callback = Box::new(callback);
                    let callback_box = Box::new(callback);
                    let callback_raw = Box::into_raw(callback_box);
                    let handler: unsafe extern "C" fn() = unsafe { std::mem::transmute(#handler_name::<F> as usize) };
                    Ok(unsafe {
                        crate::api::sys::SIM_hap_add_callback_obj_range(
                            Self::NAME.as_raw_cstr()?,
                            obj,
                            0,
                            Some(handler),
                            callback_raw as *mut std::ffi::c_void,
                            start,
                            end,
                        )
                    })
                }
            }
        } else {
            quote! {}
        };

        let name = &self.name;
        let callback_attrs = &self.callback_attrs;
        let struct_name = &self.struct_name;
        let closure_param_names = &self.closure_param_names;
        let inputs = &self.inputs;
        let output = &self.output;
        let userdata_name = &self.userdata_name;

        tokens.extend(quote! {
            #(#callback_attrs)*
            /// Automatically generated struct for the HAP
            pub struct #struct_name {}

            impl crate::api::traits::hap::Hap for #struct_name {
                type Name =  &'static [u8];
                const NAME: Self::Name = crate::api::sys::#name;
            }

            impl #struct_name {
                #add_callback_methods
                #maybe_index_callback_methods
            }

            /// The handler for HAPs of a specific type. Unboxes a boxed
            /// closure and calls it with the correct HAP callback arguments
            extern "C" fn #handler_name<F>(#(#inputs),*) -> #output
            where
                F: #(#callback_ty)+*,
            {
                // NOTE: This box must be leaked, because we may call this closure again, we cannot drop it
                let closure = Box::leak(unsafe { Box::from_raw(#userdata_name as *mut Box<F>) });
                closure(#(#closure_param_names),*)
            }
        });
    }
}

struct Haps {
    hap_structs: Vec<HapStruct>,
}

impl Haps {
    fn generate<S>(bindings: S) -> darling::Result<Self>
    where
        S: AsRef<str>,
    {
        let parsed = parse_file(bindings.as_ref())?;
        let hap_name_items = parsed
            .items
            .iter()
            .filter_map(|i| match i {
                Item::Const(c) if c.ident.to_string().ends_with("_HAP_NAME") => {
                    Some((c.ident.to_string(), c))
                }
                _ => None,
            })
            .collect::<HashMap<_, _>>();
        let hap_callbacks = parsed
            .items
            .iter()
            .filter_map(|i| match i {
                Item::Type(ty) if ty.ident.to_string().ends_with("_hap_callback") => {
                    let type_name = ty.ident.to_string();
                    // Skip generic callback type definitions that are not actual HAPs
                    // These are used as type aliases in Simics 7.38+ but don't correspond to actual HAPs
                    if type_name.starts_with("callback_type")
                        || type_name.starts_with("description")
                        || type_name.starts_with("index")
                    {
                        return None;
                    }
                    Some(
                        hap_name_items
                            .get(
                                &(type_name
                                    .trim_end_matches("_hap_callback")
                                    .to_ascii_uppercase()
                                    + "_HAP_NAME"),
                            )
                            .map(|hap_name_item| ((*hap_name_item).clone(), ty.clone()))
                            .ok_or_else(|| {
                                darling::Error::custom(format!(
                                    "Failed to find HAP name for {:?}",
                                    ty
                                ))
                            }),
                    )
                }
                _ => None,
            })
            .collect::<darling::Result<HashMap<_, _>>>()?;
        let hap_structs = hap_callbacks
            .iter()
            .map(HapStruct::try_from)
            .collect::<darling::Result<Vec<_>>>()?;

        Ok(Self { hap_structs })
    }
}

impl ToTokens for Haps {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        let hap_structs = &self.hap_structs;
        tokens.extend(quote! {
            #[allow(dead_code, non_snake_case)]
            /// Automatically generated HAP implementations
            pub mod haps {
                use crate::api::sys::*;
                use crate::api::traits::hap::Hap;
                use raw_cstr::AsRawCstr;

                #(#hap_structs)*
            }
        });
    }
}

pub struct InterfaceMethod {
    vis: Visibility,
    wrapper_inputs: Vec<BareFnArg>,
    output: Type,
    some_name: Ident,
    name_ident: Ident,
    ok_value: Expr,
    name: Ident,
}

impl TryFrom<&Field> for InterfaceMethod {
    type Error = darling::Error;

    fn try_from(value: &Field) -> darling::Result<Self> {
        let vis = value.vis.clone();

        let Type::Path(ref p) = value.ty else {
            return Err(darling::Error::custom(format!(
                "Expected a path type for field, got {:?}",
                value.ty
            )));
        };

        let last = p.path.segments.last().ok_or_else(|| {
            darling::Error::custom(format!(
                "Missing final segment for path type {:?}",
                value.ty
            ))
        })?;

        if last.ident != "Option" {
            return Err(darling::Error::custom(format!(
                "Expected Option type for field, got {:?}",
                value.ty
            )));
        }

        let name = (value.ident.clone())
            .ok_or_else(|| darling::Error::custom("Missing field name".to_string()))?;

        let PathArguments::AngleBracketed(ref args) = last.arguments else {
            return Err(darling::Error::custom(format!(
                "Expected angle bracketed arguments for field, got {:?}",
                last.arguments
            )));
        };

        let Some(GenericArgument::Type(Type::BareFn(proto))) = args.args.first() else {
            return Err(darling::Error::custom(format!(
                "Expected bare function type for field, got {:?}",
                args.args.first()
            )));
        };

        let inputs = proto.inputs.iter().cloned().collect::<Vec<_>>();

        let has_obj = inputs
            .first()
            .is_some_and(|f| quote!(#f).to_string().ends_with("conf_object_t"));

        let input_names = inputs
            .iter()
            .skip(if has_obj { 1 } else { 0 })
            .map(|a| {
                a.name.clone().map(|n| n.0).ok_or_else(|| {
                    darling::Error::custom(format!("Missing input name for {:?}", a))
                })
            })
            .collect::<darling::Result<Vec<_>>>()?;

        let wrapper_inputs = inputs
            .iter()
            .skip(if has_obj { 1 } else { 0 })
            .cloned()
            .collect::<Vec<_>>();

        let (is_attr_value, output) = match &proto.output {
            ReturnType::Default => (false, parse_quote!(())),
            ReturnType::Type(_, t) => {
                if let Type::Path(p) = &**t {
                    p.path
                        .get_ident()
                        .map(|i| i.to_string())
                        .filter(|i| i == "attr_value_t")
                        .map(|_| (true, parse_quote!(crate::api::AttrValue)))
                        .unwrap_or((false, parse_quote!(#t)))
                } else {
                    (false, parse_quote!(#t))
                }
            }
        };

        // NOTE: We need to make a new name because in some cases the fn ptr name is the same as one of the parameter
        // names
        let some_name = format_ident!("{}_fn", name);
        let name_ident = format_ident!("{}", name);
        let maybe_self_obj = has_obj.then_some(quote!(self.obj,)).unwrap_or_default();

        let ok_value = if is_attr_value {
            parse_quote!(Ok(unsafe { #some_name(#maybe_self_obj #(#input_names),*) }.into()))
        } else {
            parse_quote!(Ok(unsafe { #some_name(#maybe_self_obj #(#input_names),*) }))
        };

        Ok(Self {
            vis,
            wrapper_inputs,
            output,
            some_name,
            name_ident,
            ok_value,
            name,
        })
    }
}

impl ToTokens for InterfaceMethod {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        let vis = &self.vis;
        let wrapper_inputs = &self.wrapper_inputs;
        let output = &self.output;
        let some_name = &self.some_name;
        let name_ident = &self.name_ident;
        let ok_value = &self.ok_value;
        let name = self.name.to_string();

        tokens.extend(quote! {
            /// Automatically generated method for the interface
            #vis fn #name_ident(&mut self, #(#wrapper_inputs),*) -> crate::Result<#output> {
                if let Some(#some_name) = unsafe { *self.interface}.#name_ident {
                    #ok_value
                } else {
                    Err(crate::Error::NoInterfaceMethod { method: #name.to_string() })
                }
            }
        });
    }
}

pub struct InterfaceStruct {
    struct_name: Ident,
    interface_ident: Ident,
    interface_methods: Vec<InterfaceMethod>,
    name_ident: Ident,
}

impl TryFrom<(&ItemConst, &ItemStruct)> for InterfaceStruct {
    type Error = darling::Error;

    fn try_from(value: (&ItemConst, &ItemStruct)) -> darling::Result<Self> {
        let name = value.0;
        let interface = value.1;
        let interface_methods = interface
            .fields
            .iter()
            .filter_map(|f| match InterfaceMethod::try_from(f) {
                Ok(m) => Some(m),
                Err(e) => {
                    eprintln!("cargo:warning=Failed to generate method for field {f:?}: {e}");
                    None
                }
            })
            .collect::<Vec<_>>();
        let camel_name = name.ident.to_string().snake_to_camel();
        let struct_name = format_ident!("{camel_name}");
        let interface_ident = interface.ident.clone();
        let name_ident = name.ident.clone();
        Ok(Self {
            struct_name,
            interface_ident,
            interface_methods,
            name_ident,
        })
    }
}

impl ToTokens for InterfaceStruct {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        let struct_name = &self.struct_name;
        let interface_ident = &self.interface_ident;
        let interface_methods = &self.interface_methods;
        let name_ident = &self.name_ident;

        tokens.extend(quote! {
            /// Automatically generated structure for the interface
            pub struct #struct_name {
                obj: *mut crate::api::ConfObject,
                interface: *mut crate::api::sys::#interface_ident,
            }

            impl #struct_name {
                #(#interface_methods)*
            }

            impl crate::api::traits::Interface for #struct_name {
                type InternalInterface = crate::api::sys::#interface_ident;
                type Name = &'static [u8];

                const NAME: &'static [u8] = crate::api::sys::#name_ident;

                fn new(obj: *mut crate::api::ConfObject, interface: *mut Self::InternalInterface) -> Self {
                    Self { obj, interface }
                }
            }
        });
    }
}

pub struct Interfaces {
    interface_structs: Vec<InterfaceStruct>,
}

impl Interfaces {
    pub fn generate<S>(bindings: S) -> darling::Result<Self>
    where
        S: AsRef<str>,
    {
        let parsed = parse_file(bindings.as_ref())?;

        let interface_name_items = parsed
            .items
            .iter()
            .filter_map(|i| match i {
                Item::Const(c) if c.ident.to_string().ends_with("_INTERFACE") => {
                    Some((c.ident.to_string(), c))
                }
                _ => None,
            })
            .collect::<HashMap<_, _>>();

        let interfaces = parsed
            .items
            .iter()
            .filter_map(|i| {
                if let Item::Struct(s) = i {
                    interface_name_items
                        .get(&s.ident.to_string().to_ascii_uppercase())
                        .map(|interface_name_item| ((*interface_name_item).clone(), s.clone()))
                } else {
                    None
                }
            })
            .collect::<HashMap<_, _>>();

        let interface_structs = interfaces
            .iter()
            .map(InterfaceStruct::try_from)
            .collect::<darling::Result<Vec<_>>>()?;

        Ok(Self { interface_structs })
    }
}

impl ToTokens for Interfaces {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        let interface_structs = &self.interface_structs;
        tokens.extend(quote! {
            #[allow(dead_code, non_snake_case)]
            /// Automatically generated interfaces from the base package
            pub mod interfaces {
                use crate::api::sys::*;

                #(#interface_structs)*
            }
        })
    }
}

fn main() -> Result<()> {
    println!("cargo:rerun-if-env-changed={SIMICS_BASE_ENV}");
    let out_dir = PathBuf::from(
        var(OUT_DIR_ENV)
            .map_err(|e| anyhow!("No environment variable {OUT_DIR_ENV} found: {e}"))?,
    );

    // Write intermediate auto-generated high level bindings for interfaces and haps

    let interfaces_out_file = out_dir.join(INTERFACES_FILE);
    let haps_out_file = out_dir.join(HAPS_FILE);

    let interfaces_tokens = Interfaces::generate(SIMICS_API_BINDINGS)
        .map(|i| i.to_token_stream())
        .unwrap_or_else(|e| e.write_errors());

    let haps_tokens = Haps::generate(SIMICS_API_BINDINGS)
        .map(|h| h.to_token_stream())
        .unwrap_or_else(|e| e.write_errors());

    eprintln!("cargo:warning=Writing interfaces to {interfaces_out_file:?}");

    write(
        interfaces_out_file,
        unparse(&parse_file(&interfaces_tokens.to_string()).map_err(|e| {
            eprintln!("Failed to parse interfaces file: {e}\n{interfaces_tokens}");
            e
        })?),
    )?;

    eprintln!("cargo:warning=Writing haps to {haps_out_file:?}");

    write(
        haps_out_file,
        unparse(&parse_file(&haps_tokens.to_string()).map_err(|e| {
            eprintln!("Failed to parse interfaces file: {e}\n{haps_tokens}");
            e
        })?),
    )?;

    eprintln!("cargo:warning=Emitting cfg directives");
    emit_cfg_directives()?;
    eprintln!("cargo:warning=Emitting link info");
    emit_link_info()?;

    Ok(())
}