miden-base-macros 0.13.0

Provides proc macro support for Miden rollup SDK
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
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
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
//! Foreign procedure invocation support for generated SDK bindings.

use std::{
    collections::{HashMap, HashSet},
    env, fs,
    path::{Path, PathBuf},
};

use heck::{ToKebabCase, ToSnakeCase};
use miden_assembly_syntax::ast::{Path as MasmPath, PathComponent};
use miden_mast_package::{Package, PackageExport};
use miden_protocol::utils::serde::Deserializable;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{ToTokens, quote};
use syn::{
    Attribute, Error, File, ImplItem, ImplItemFn, Item, ItemFn, ItemImpl, ItemStruct, ReturnType,
    parse_quote,
};
use wit_bindgen_core::wit_parser::{
    Docs, Function, FunctionKind, InterfaceId, Param, Resolve, Span as WitSpan, Type as WitType,
    WorldId, WorldItem,
};

#[cfg(test)]
use crate::wit_world::DependencyInterface;
use crate::{
    generate::{
        collect_arg_idents, format_module_path, qualify_signature_types, should_generate_struct,
    },
    wit_world::SelectedDependency,
};

/// WIT function prefix reserved for generated foreign procedure imports.
pub(crate) const WIT_FUNCTION_PREFIX: &str = "fpi-";

/// Rust identifier prefix generated by wit-bindgen for FPI WIT functions.
pub(crate) const RUST_FUNCTION_PREFIX: &str = "fpi_";

const NEW_METHOD: &str = "new";

/// Method names of the `ActiveAccount` trait (`sdk/base-sys/src/bindings/active_account.rs`).
///
/// Dependency functions mapping to these names are rejected: the generated inherent method would
/// shadow the built-in trait method during Rust method resolution, silently changing what e.g.
/// `account.get_id()` means and bypassing the foreign-binding guard. Keep in sync with the trait.
const ACTIVE_ACCOUNT_METHODS: &[&str] = &[
    "get_id",
    "get_nonce",
    "get_initial_commitment",
    "compute_commitment",
    "get_code_commitment",
    "get_initial_storage_commitment",
    "compute_storage_commitment",
    "get_asset",
    "get_initial_asset",
    "get_balance",
    "get_initial_balance",
    "has_non_fungible_asset",
    "get_initial_vault_root",
    "get_vault_root",
    "get_num_procedures",
    "get_procedure_root",
    "has_procedure",
];

/// Adds `fpi-` functions to imported Miden dependency interfaces in the selected world.
pub(crate) fn inject_imports(
    resolve: &mut Resolve,
    world_id: WorldId,
    dependency_imports: &[String],
) -> syn::Result<()> {
    if dependency_imports.is_empty() {
        return Ok(());
    }

    let dependency_imports = dependency_imports.iter().map(String::as_str).collect::<HashSet<_>>();
    let imported_interfaces = resolve.worlds[world_id]
        .imports
        .values()
        .filter_map(|item| match item {
            WorldItem::Interface { id, .. } => Some(*id),
            _ => None,
        })
        .filter(|id| {
            interface_import_path(resolve, *id)
                .as_ref()
                .is_some_and(|path| dependency_imports.contains(path.as_str()))
        })
        .collect::<Vec<_>>();

    if imported_interfaces.is_empty() {
        return Ok(());
    }

    for interface_id in &imported_interfaces {
        let import = interface_import_path(resolve, *interface_id)
            .unwrap_or_else(|| "<unknown interface>".to_string());
        validate_reserved_fpi_namespace(
            &import,
            resolve.interfaces[*interface_id].functions.values(),
        )?;
    }

    let core_types = resolve_core_types(resolve)?;
    for interface_id in imported_interfaces {
        inject_functions_into_interface(resolve, interface_id, core_types);
    }

    Ok(())
}

/// Determines whether a generated free function represents an FPI WIT import.
pub(crate) fn is_function(func: &ItemFn) -> bool {
    matches!(func.vis, syn::Visibility::Public(_))
        && func.sig.unsafety.is_none()
        && func.sig.ident.to_string().starts_with(RUST_FUNCTION_PREFIX)
}

/// Determines whether a generated free function represents a plain (non-FPI) WIT import.
///
/// Unlike [`is_function`], which keys on the synthesized `fpi_` prefix, this is a negative filter:
/// it accepts any safe, public free function in a generated leaf import module that is not an FPI
/// import. That relies on wit-bindgen emitting exactly the interface's functions as plain public
/// free functions in those modules — it does not emit auxiliary public free functions there. If a
/// future wit-bindgen version changes that, such functions would be picked up as sibling methods
/// and this predicate would need to narrow (e.g. by the interface's declared function set).
pub(crate) fn is_plain_import_function(func: &ItemFn) -> bool {
    matches!(func.vis, syn::Visibility::Public(_))
        && func.sig.unsafety.is_none()
        && !func.sig.ident.to_string().starts_with(RUST_FUNCTION_PREFIX)
}

/// Core WIT types needed to synthesize caller-only FPI imports.
#[derive(Clone, Copy)]
struct CoreTypes {
    felt: WitType,
    word: WitType,
}

/// Generated import module with the free functions selected by a walk filter.
pub(crate) struct Module {
    /// Rust module path where the selected generated free functions live.
    pub(crate) module_path: Vec<syn::Ident>,
    /// String form of `module_path` used for dependency lookup.
    pub(crate) path_string: String,
    /// Selected generated free functions from this import module.
    pub(crate) functions: Vec<ItemFn>,
}

/// Resolved package data needed to generate FPI caller wrappers.
struct Dependency {
    /// Rust module path generated by wit-bindgen for the dependency import.
    module_path: String,
    /// Miden package artifact read for procedure roots.
    package_path: PathBuf,
    /// Fully-qualified WIT import path.
    import: String,
    /// Procedure roots keyed by full WIT interface path and function name.
    roots: HashMap<ProcedureRootKey, ProcedureRoot>,
}

/// Identifies a WIT procedure export in a dependency package.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct ProcedureRootKey {
    /// Fully-qualified WIT interface path, including package version.
    interface: String,
    /// WIT function name.
    function: String,
}

/// Four field elements that make up a foreign procedure root.
#[derive(Clone, Copy)]
struct ProcedureRoot {
    felts: [u64; 4],
}

impl ProcedureRootKey {
    /// Creates a root key for one WIT interface function.
    fn new(interface: impl Into<String>, function: impl Into<String>) -> Self {
        Self {
            interface: interface.into(),
            function: function.into(),
        }
    }
}

/// Returns the fully-qualified import path used for a resolved interface.
fn interface_import_path(resolve: &Resolve, interface_id: InterfaceId) -> Option<String> {
    let interface = &resolve.interfaces[interface_id];
    let interface_name = interface.name.as_deref()?;
    let package_id = interface.package?;
    Some(resolve.packages[package_id].name.interface_id(interface_name))
}

/// Resolves `felt` and `word` from `miden:base/core-types`.
fn resolve_core_types(resolve: &Resolve) -> syn::Result<CoreTypes> {
    let core_types = resolve
        .packages
        .iter()
        .find_map(|(_, package)| {
            if package.name.namespace != "miden" || package.name.name != "base" {
                return None;
            }

            package.interfaces.get("core-types").map(|interface_id| {
                let interface = &resolve.interfaces[*interface_id];
                (interface.types.get("felt").copied(), interface.types.get("word").copied())
            })
        })
        .ok_or_else(|| {
            Error::new(
                Span::call_site(),
                "failed to resolve miden:base/core-types package for FPI imports",
            )
        })?;

    let (Some(felt), Some(word)) = core_types else {
        return Err(Error::new(
            Span::call_site(),
            "miden:base/core-types is missing felt or word type definitions",
        ));
    };

    Ok(CoreTypes {
        felt: WitType::Id(felt),
        word: WitType::Id(word),
    })
}

/// Injects FPI variants of every freestanding function in an imported interface.
fn inject_functions_into_interface(
    resolve: &mut Resolve,
    interface_id: InterfaceId,
    core_types: CoreTypes,
) {
    let interface = &mut resolve.interfaces[interface_id];
    let functions = interface
        .functions
        .values()
        .filter(|function| {
            matches!(function.kind, FunctionKind::Freestanding)
                && !function.name.starts_with(WIT_FUNCTION_PREFIX)
        })
        .cloned()
        .collect::<Vec<_>>();

    for function in functions {
        let fpi_name = format!("{WIT_FUNCTION_PREFIX}{}", function.name);
        if interface.functions.contains_key(&fpi_name) {
            continue;
        }

        interface
            .functions
            .insert(fpi_name.clone(), build_import_function(function, fpi_name, core_types));
    }
}

/// Rejects dependency functions that use the namespace reserved for generated FPI imports.
fn validate_reserved_fpi_namespace<'a>(
    import: &str,
    functions: impl IntoIterator<Item = &'a Function>,
) -> syn::Result<()> {
    if let Some(function) = functions
        .into_iter()
        .find(|function| function.name.starts_with(WIT_FUNCTION_PREFIX))
    {
        return Err(Error::new(
            Span::call_site(),
            format!(
                "dependency interface `{import}` defines function `{}` with reserved FPI prefix \
                 `{}`; generated FPI imports use WIT names starting with `{}` and Rust names \
                 starting with `{}`, so dependency functions must use a different name",
                function.name, WIT_FUNCTION_PREFIX, WIT_FUNCTION_PREFIX, RUST_FUNCTION_PREFIX
            ),
        ));
    }

    Ok(())
}

/// Builds the caller-side WIT import that forwards through `execute_foreign_procedure`.
fn build_import_function(function: Function, fpi_name: String, core_types: CoreTypes) -> Function {
    let mut params = Vec::with_capacity(function.params.len() + 3);
    params.push(Param {
        name: "account-id-prefix".to_string(),
        ty: core_types.felt,
        span: WitSpan::default(),
    });
    params.push(Param {
        name: "account-id-suffix".to_string(),
        ty: core_types.felt,
        span: WitSpan::default(),
    });
    params.push(Param {
        name: "foreign-proc-root".to_string(),
        ty: core_types.word,
        span: WitSpan::default(),
    });
    params.extend(function.params);

    Function {
        name: fpi_name,
        kind: FunctionKind::Freestanding,
        params,
        result: function.result,
        docs: Docs::default(),
        stability: function.stability,
        span: WitSpan::default(),
    }
}

/// Walks generated bindings and collects the import-module functions selected by `filter`.
pub(crate) fn collect_import_modules(
    items: &[Item],
    filter: &dyn Fn(&ItemFn) -> bool,
) -> syn::Result<Vec<Module>> {
    let mut modules = Vec::new();
    collect_modules(items, &mut Vec::new(), &mut modules, filter)?;
    Ok(modules)
}

/// Recursively walks all modules and collects selected functions from leaf import modules.
fn collect_modules(
    items: &[Item],
    path: &mut Vec<syn::Ident>,
    modules_out: &mut Vec<Module>,
    filter: &dyn Fn(&ItemFn) -> bool,
) -> syn::Result<()> {
    for item in items.iter() {
        if let Item::Mod(module) = item {
            path.push(module.ident.clone());
            if let Some((_, ref content)) = module.content {
                collect_modules(content, path, modules_out, filter)?;
                collect_functions_from_module(content, path, modules_out, filter);
            }
            path.pop();
        }
    }

    Ok(())
}

/// Collects selected generated free functions from a leaf import module.
fn collect_functions_from_module(
    items: &[Item],
    path: &[syn::Ident],
    modules_out: &mut Vec<Module>,
    filter: &dyn Fn(&ItemFn) -> bool,
) {
    if !should_generate_struct(path, items) {
        return;
    }

    let functions = items
        .iter()
        .filter_map(|item| match item {
            Item::Fn(func) if filter(func) => Some(func.clone()),
            _ => None,
        })
        .collect::<Vec<_>>();

    if functions.is_empty() {
        return;
    }

    modules_out.push(Module {
        module_path: path.to_vec(),
        path_string: format_module_path(path),
        functions,
    });
}

/// Builds typed FPI methods on the user-provided foreign account wrapper struct.
pub(crate) fn augment_foreign_account_bindings(
    bindings: TokenStream2,
    account_struct: ItemStruct,
    dependencies: Vec<SelectedDependency>,
    binding_module_ident: syn::Ident,
) -> syn::Result<TokenStream2> {
    let file: File = syn::parse2(bindings)?;
    let modules = collect_import_modules(&file.items, &is_function)?;

    if modules.is_empty() {
        return Err(Error::new(
            account_struct.ident.span(),
            "account did not find any callable exports in the selected packages",
        ));
    }

    let dependencies =
        dependencies.into_iter().map(load_dependency).collect::<syn::Result<Vec<_>>>()?;
    let struct_item = foreign_account_struct(&account_struct)?;
    let active_account_item = active_account_impl(&account_struct);
    let mut impl_item = foreign_account_impl(&account_struct);
    let mut seen_methods = HashMap::new();
    let mut include_paths = Vec::new();

    for module in modules {
        let Some(dependency) = dependencies
            .iter()
            .find(|dependency| dependency.module_path == module.path_string)
        else {
            return Err(Error::new(
                Span::call_site(),
                format!(
                    "failed to resolve FPI dependency metadata for generated module `{}`",
                    module.path_string
                ),
            ));
        };

        if !include_paths.iter().any(|path| path == &dependency.package_path) {
            include_paths.push(dependency.package_path.clone());
        }

        let mut signature_module_path = Vec::with_capacity(module.module_path.len() + 1);
        signature_module_path.push(binding_module_ident.clone());
        signature_module_path.extend(module.module_path.iter().cloned());

        for func in &module.functions {
            let wit_name = function_wit_name(func)?;
            let root_key = ProcedureRootKey::new(dependency.import.as_str(), wit_name.as_str());
            let root = dependency.roots.get(&root_key).ok_or_else(|| {
                Error::new(
                    func.sig.ident.span(),
                    format!(
                        "failed to find procedure root for `{}#{wit_name}` in package '{}'",
                        dependency.import,
                        dependency.package_path.display()
                    ),
                )
            })?;
            let method = build_wrapper_method(
                func,
                &signature_module_path,
                quote!(#binding_module_ident),
                &module.module_path,
                *root,
            )?;
            let method_name = method.sig.ident.to_string();
            if let Some(existing_path) = seen_methods.get(&method_name) {
                return Err(Error::new(
                    method.sig.ident.span(),
                    format!(
                        "account method name collision on `{method_name}`: generated from both \
                         `{existing_path}` and `{}`",
                        module.path_string
                    ),
                ));
            }
            seen_methods.insert(method_name, module.path_string.clone());
            impl_item.items.push(ImplItem::Fn(method));
        }
    }

    let bindings = file.into_token_stream();
    let package_includes = include_paths
        .into_iter()
        .map(|path| {
            let utf8_path = path.to_str().ok_or_else(|| {
                Error::new(
                    Span::call_site(),
                    format!("path '{}' contains invalid UTF-8", path.display()),
                )
            })?;
            Ok(quote! {
                const _: &[u8] = include_bytes!(#utf8_path);
            })
        })
        .collect::<syn::Result<Vec<_>>>()?;

    Ok(quote! {
        #[doc(hidden)]
        #[allow(dead_code)]
        pub mod #binding_module_ident {
            #bindings
        }

        #struct_item
        #impl_item
        #active_account_item
        #(#package_includes)*
    })
}

/// Builds a method on an account wrapper that dispatches between a native call and an FPI call.
///
/// The marked struct can stand in for either the transaction's native (active) account or a
/// foreign account. The generated method inspects [`foreign_account_id`] at runtime: when set it
/// forwards through the generated `fpi_*` import (`execute_foreign_procedure`); otherwise it calls
/// the dependency's native import directly.
fn build_wrapper_method(
    func: &ItemFn,
    signature_module_path: &[syn::Ident],
    call_base_path: TokenStream2,
    call_module_path: &[syn::Ident],
    procedure_root: ProcedureRoot,
) -> syn::Result<ImplItemFn> {
    let foreign_fn_ident = func.sig.ident.clone();
    // Stripping the `fpi_` prefix yields both the wrapper method name and the matching native
    // import name generated by wit-bindgen for the same WIT function.
    let native_fn_ident = method_ident(func)?;
    let mut sig = func.sig.clone();
    sig.ident = native_fn_ident.clone();

    if sig.inputs.len() < 3 {
        return Err(Error::new(
            sig.ident.span(),
            "generated FPI function is missing account id and procedure root parameters",
        ));
    }
    let retained_inputs = sig.inputs.iter().skip(3).cloned().collect::<Vec<_>>();

    sig.inputs.clear();
    sig.inputs.push(parse_quote!(&self));
    sig.inputs.extend(retained_inputs);
    qualify_signature_types(&mut sig, signature_module_path);

    let arg_idents = collect_arg_idents(func)?.into_iter().skip(3).collect::<Vec<_>>();
    let root_tokens = procedure_root_tokens(procedure_root);

    let mut path_tokens = call_base_path;
    for ident in call_module_path {
        path_tokens = quote! { #path_tokens :: #ident };
    }

    let foreign_call = quote! {
        #path_tokens :: #foreign_fn_ident(
            __miden_foreign_account_id.prefix,
            __miden_foreign_account_id.suffix,
            #root_tokens,
            #(#arg_idents),*
        )
    };
    let native_call = quote! {
        #path_tokens :: #native_fn_ident(#(#arg_idents),*)
    };
    let dispatch = quote! {
        match self.foreign_account_id {
            ::core::option::Option::Some(__miden_foreign_account_id) => { #foreign_call }
            ::core::option::Option::None => { #native_call }
        }
    };

    let method_doc = format!(
        "Invokes `{}` on the native account, or through `execute_foreign_procedure` when this \
         binding targets a foreign account.",
        native_fn_ident.to_string().to_kebab_case()
    );
    let doc_attr: Attribute = parse_quote!(#[doc = #method_doc]);
    let inline_attr: Attribute = parse_quote!(#[inline(always)]);

    let body_tokens = match &sig.output {
        ReturnType::Default => quote!({ #dispatch; }),
        _ => quote!({ #dispatch }),
    };
    let block = syn::parse2(body_tokens)?;

    Ok(ImplItemFn {
        attrs: vec![doc_attr, inline_attr],
        vis: func.vis.clone(),
        defaultness: None,
        sig,
        block,
    })
}

/// Replaces an empty marker struct with one that optionally stores a foreign account id.
///
/// A `None` id selects the transaction's native (active) account; a `Some` id selects a foreign
/// account reached through FPI.
fn foreign_account_struct(account_struct: &ItemStruct) -> syn::Result<ItemStruct> {
    let attrs = &account_struct.attrs;
    let vis = &account_struct.vis;
    let ident = &account_struct.ident;
    // `Default` is the only trait the macro derives: the note/tx-script entrypoint account is
    // built through `AccountWrapper::active()` (= `Self::default()`), whose `foreign_account_id`
    // is `None` (the active account). Conveniences such as `Clone`/`Copy`/`Debug` are left
    // to the user. The derive is skipped when the user already requests `Default`, because their
    // attributes are re-emitted verbatim and a second `Default` impl would conflict.
    let derive_default =
        (!user_derived_names(attrs).contains("Default")).then(|| quote!(#[derive(Default)]));
    syn::parse2(quote! {
        #(#attrs)*
        #derive_default
        #vis struct #ident {
            /// `Some` when this binding targets a foreign account (FPI); `None` for the
            /// transaction's active account.
            foreign_account_id: ::core::option::Option<::miden::AccountId>,
        }
    })
}

/// Returns the trait names (final path segments) the user already derives on the marker struct.
fn user_derived_names(attrs: &[Attribute]) -> HashSet<String> {
    attrs
        .iter()
        .filter(|attr| attr.path().is_ident("derive"))
        .filter_map(|attr| {
            attr.parse_args_with(
                syn::punctuated::Punctuated::<syn::Path, syn::Token![,]>::parse_terminated,
            )
            .ok()
        })
        .flatten()
        .filter_map(|path| path.segments.last().map(|segment| segment.ident.to_string()))
        .collect()
}

/// Creates the inherent impl block shared by all generated foreign account methods.
fn foreign_account_impl(account_struct: &ItemStruct) -> ItemImpl {
    let ident = &account_struct.ident;
    parse_quote! {
        impl #ident {
            /// Creates an account API wrapper bound to the given foreign account.
            ///
            /// Methods invoked on the returned value are dispatched through
            /// `execute_foreign_procedure` against `account_id`.
            #[inline(always)]
            pub fn new(account_id: ::miden::AccountId) -> Self {
                Self {
                    foreign_account_id: ::core::option::Option::Some(account_id),
                }
            }
        }
    }
}

/// Builds the SDK trait impls for the account wrapper struct.
///
/// Emits the `ActiveAccount` guard impl that rejects active-account ops on a foreign binding,
/// and the `AccountWrapper` marker impl through which the note/tx-script macros instantiate
/// the entrypoint account parameter.
fn active_account_impl(account_struct: &ItemStruct) -> TokenStream2 {
    let ident = &account_struct.ident;
    let message = format!(
        "active-account operation called on `{ident}` while it is bound to a foreign account; \
         active-account methods are only valid for the transaction's active account"
    );
    quote! {
        impl ::miden::active_account::ActiveAccount for #ident {
            #[inline(always)]
            fn __assert_active_account(&self) {
                if self.foreign_account_id.is_some() {
                    ::core::panic!(#message);
                }
            }
        }

        impl ::miden::active_account::AccountWrapper for #ident {}
    }
}

/// Returns the wrapper method name for a generated FPI free function.
fn method_ident(func: &ItemFn) -> syn::Result<syn::Ident> {
    let fn_name = func.sig.ident.to_string();
    let Some(method_name) = fn_name.strip_prefix(RUST_FUNCTION_PREFIX) else {
        return Err(Error::new(
            func.sig.ident.span(),
            format!(
                "expected generated FPI function name to start with `{}`",
                RUST_FUNCTION_PREFIX
            ),
        ));
    };
    if method_name == NEW_METHOD {
        return Err(Error::new(
            func.sig.ident.span(),
            format!(
                "generated FPI function `{fn_name}` maps to reserved wrapper method \
                 `{NEW_METHOD}`; dependency functions must not be named `new`"
            ),
        ));
    }
    if ACTIVE_ACCOUNT_METHODS.contains(&method_name) {
        return Err(Error::new(
            func.sig.ident.span(),
            format!(
                "dependency function `{}` collides with the built-in `ActiveAccount` method \
                 `{method_name}`; the generated wrapper method would shadow it. Rename the \
                 dependency function",
                method_name.to_kebab_case()
            ),
        ));
    }

    Ok(syn::Ident::new(method_name, func.sig.ident.span()))
}

/// Returns the original WIT function name represented by a generated FPI free function.
fn function_wit_name(func: &ItemFn) -> syn::Result<String> {
    Ok(method_ident(func)?.to_string().to_kebab_case())
}

/// Converts a procedure root into SDK `Word` construction tokens.
fn procedure_root_tokens(root: ProcedureRoot) -> TokenStream2 {
    let felts = root.felts.into_iter().map(|value| quote!(::miden::felt!(#value)));
    quote!(::miden::Word::new([#(#felts),*]))
}

/// Loads a single dependency package and extracts exported procedure roots.
fn load_dependency(dependency: SelectedDependency) -> syn::Result<Dependency> {
    let import = dependency.import().to_owned();
    let module_path = import_module_path(&import);
    let package_path = resolve_dependency_package_path(&dependency)?;
    let package_bytes = fs::read(&package_path).map_err(|err| {
        Error::new(
            Span::call_site(),
            format!("failed to read dependency package '{}': {err}", package_path.display()),
        )
    })?;
    let package = Package::read_from_bytes(&package_bytes).map_err(|err| {
        Error::new(
            Span::call_site(),
            format!("failed to deserialize dependency package '{}': {err}", package_path.display()),
        )
    })?;

    let mut roots = HashMap::new();
    for export in package.manifest.exports() {
        let PackageExport::Procedure(proc_export) = export else {
            continue;
        };
        let Some(root_key) = procedure_root_key_from_export_path(proc_export.path.as_ref()) else {
            continue;
        };

        if root_key.interface != import {
            continue;
        }
        roots.insert(root_key, procedure_root_from_digest(&proc_export.digest));
    }

    Ok(Dependency {
        module_path,
        package_path,
        import,
        roots,
    })
}

/// Maps dependency-defined WIT types to the normal bindings module generated by component/note.
pub(crate) fn dependency_type_with_entries(
    dependencies: &[SelectedDependency],
) -> Vec<(String, wit_bindgen_rust::WithOption)> {
    use heck::ToUpperCamelCase;

    dependencies
        .iter()
        .flat_map(|dependency| {
            let import = dependency.import();
            let module_path = import_module_path(import);
            dependency.type_names().iter().map(move |wit_type| {
                (
                    format!("{import}/{wit_type}"),
                    wit_bindgen_rust::WithOption::Path(format!(
                        "crate::bindings::{}::{}",
                        module_path,
                        wit_type.to_upper_camel_case()
                    )),
                )
            })
        })
        .collect()
}

/// Converts a fully-qualified WIT import path into the Rust module path generated by wit-bindgen.
pub(crate) fn import_module_path(import: &str) -> String {
    let without_version = import.split('@').next().unwrap_or(import);
    without_version
        .split([':', '/'])
        .filter(|segment| !segment.is_empty())
        .map(|segment| segment.to_snake_case())
        .collect::<Vec<_>>()
        .join("::")
}

/// Finds the `.masp` package artifact corresponding to a manifest dependency entry.
fn resolve_dependency_package_path(dependency: &SelectedDependency) -> syn::Result<PathBuf> {
    if dependency.root.is_file() {
        return Ok(dependency.root.clone());
    }

    let preferred_profile = env::var("PROFILE").unwrap_or_else(|_| "debug".to_string());
    let mut profiles = vec![preferred_profile.clone()];
    if preferred_profile != "release" {
        profiles.push("release".to_string());
    }
    if preferred_profile != "debug" {
        profiles.push("debug".to_string());
    }

    let package_stems = dependency_package_stems(dependency);
    let output_dirs = dependency_output_dirs(dependency, &profiles);
    for dir in &output_dirs {
        if let Some(package) = find_dependency_package_in_dir(dir, &package_stems)? {
            return Ok(package.clone());
        }
    }

    Err(Error::new(
        Span::call_site(),
        missing_dependency_package_message(dependency, &package_stems, &output_dirs, &profiles),
    ))
}

/// Formats the diagnostic emitted when FPI wrapper generation cannot load a dependency package.
fn missing_dependency_package_message(
    dependency: &SelectedDependency,
    package_stems: &[String],
    output_dirs: &[PathBuf],
    profiles: &[String],
) -> String {
    let searched = output_dirs
        .iter()
        .map(|dir| format!("'{}'", dir.display()))
        .collect::<Vec<_>>()
        .join(", ");
    let expected_files = package_stems
        .iter()
        .flat_map(|stem| profiles.iter().map(move |profile| format!("{stem}.masp in {profile}")))
        .collect::<Vec<_>>()
        .join(", ");
    let build_hint = dependency_build_hint(dependency);

    format!(
        "miden::generate! could not find a built `.masp` package for FPI dependency '{}' (import \
         '{}', root '{}'). FPI wrappers need the dependency package during Rust macro expansion \
         to read procedure roots. Expected one of: {expected_files}. Searched: {searched}. \
         {build_hint}",
        dependency.name,
        dependency.import(),
        dependency.root.display(),
    )
}

/// Returns a command hint for building a dependency package before generating FPI wrappers.
fn dependency_build_hint(dependency: &SelectedDependency) -> String {
    let manifest_path = dependency.root.join("Cargo.toml");
    if manifest_path.is_file() {
        format!(
            "Build the dependency first with `cargo miden build --manifest-path {} --release`, or \
             persist the compiled package to '{}/target/miden/<profile>' before compiling this \
             crate.",
            manifest_path.display(),
            dependency.root.display(),
        )
    } else {
        format!(
            "Build the dependency first with `cargo miden build`, or persist the compiled package \
             to '{}/target/miden/<profile>' before compiling this crate.",
            dependency.root.display(),
        )
    }
}

/// Returns candidate output directories where a dependency `.masp` may have been written.
fn dependency_output_dirs(dependency: &SelectedDependency, profiles: &[String]) -> Vec<PathBuf> {
    let mut dirs = Vec::new();

    // The dependency root is the most precise location for path dependencies. Prefer it over
    // ambient target directories so restored or previously built artifacts cannot shadow the
    // package that belongs to the dependency being wrapped.
    push_profile_dirs(&mut dirs, dependency.root.join("target"), profiles);
    push_manifest_ancestor_target_profile_dirs(&mut dirs, &dependency.root, profiles);
    push_ancestor_target_profile_dirs(&mut dirs, &dependency.root, profiles);

    if let Ok(target_dir) = env::var("CARGO_TARGET_DIR") {
        push_profile_dirs(&mut dirs, PathBuf::from(target_dir), profiles);
    }

    if let Ok(out_dir) = env::var("OUT_DIR") {
        for ancestor in Path::new(&out_dir).ancestors() {
            push_profile_dirs(&mut dirs, ancestor.to_path_buf(), profiles);
        }
    }

    if let Ok(current_dir) = env::current_dir() {
        push_profile_dirs(&mut dirs, current_dir.join("target"), profiles);
        push_manifest_ancestor_target_profile_dirs(&mut dirs, &current_dir, profiles);
        push_ancestor_target_profile_dirs(&mut dirs, &current_dir, profiles);
    }

    dirs
}

/// Adds `target/miden/<profile>` directories while preserving insertion order.
fn push_profile_dirs(dirs: &mut Vec<PathBuf>, target_root: PathBuf, profiles: &[String]) {
    for profile in profiles {
        let dir = target_root.join("miden").join(profile);
        if !dirs.iter().any(|existing| existing == &dir) {
            dirs.push(dir);
        }
    }
}

/// Adds `target/miden/<profile>` directories found in ancestors of `path`.
fn push_ancestor_target_profile_dirs(dirs: &mut Vec<PathBuf>, path: &Path, profiles: &[String]) {
    for ancestor in path.ancestors() {
        if ancestor.file_name().is_some_and(|name| name == "target") {
            push_profile_dirs(dirs, ancestor.to_path_buf(), profiles);
        }
    }
}

/// Adds `target/miden/<profile>` directories for Cargo manifest ancestors.
fn push_manifest_ancestor_target_profile_dirs(
    dirs: &mut Vec<PathBuf>,
    path: &Path,
    profiles: &[String],
) {
    for ancestor in path.ancestors() {
        if ancestor.join("Cargo.toml").is_file() || ancestor.join("Cargo.lock").is_file() {
            push_profile_dirs(dirs, ancestor.join("target"), profiles);
        }
    }
}

/// Finds a dependency package in `dir`, preferring filenames that match the package name.
fn find_dependency_package_in_dir(
    dir: &Path,
    package_stems: &[String],
) -> syn::Result<Option<PathBuf>> {
    if !dir.is_dir() {
        return Ok(None);
    }

    let mut packages = fs::read_dir(dir)
        .map_err(|err| {
            Error::new(
                Span::call_site(),
                format!("failed to read dependency output directory '{}': {err}", dir.display()),
            )
        })?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|err| {
            Error::new(
                Span::call_site(),
                format!("failed to iterate dependency output directory '{}': {err}", dir.display()),
            )
        })?
        .into_iter()
        .map(|entry| entry.path())
        .filter(|path| path.extension().is_some_and(|ext| ext == "masp"))
        .collect::<Vec<_>>();
    packages.sort();

    for stem in package_stems {
        if let Some(package) = packages.iter().find(|path| {
            path.file_stem()
                .and_then(|value| value.to_str())
                .is_some_and(|file_stem| file_stem == stem)
        }) {
            return Ok(Some(package.clone()));
        }
    }

    Ok((packages.len() == 1).then(|| packages[0].clone()))
}

/// Returns likely `.masp` filename stems for a dependency.
fn dependency_package_stems(dependency: &SelectedDependency) -> Vec<String> {
    let mut stems = Vec::new();

    if let Some(package_name) = dependency_manifest_package_name(&dependency.root) {
        push_dependency_stem(&mut stems, &package_name);
    }

    if let Some(name) = dependency.name.split([':', '/']).next_back() {
        push_dependency_stem(&mut stems, name);
    }

    if let Some(name) = dependency.root.file_name().and_then(|name| name.to_str()) {
        push_dependency_stem(&mut stems, name);
    }

    stems
}

/// Reads the Cargo package name for dependency directories.
fn dependency_manifest_package_name(root: &Path) -> Option<String> {
    let manifest_path = root.join("Cargo.toml");
    let manifest = fs::read_to_string(manifest_path).ok()?;
    let manifest = manifest.parse::<toml::Table>().ok()?;
    manifest
        .get("package")
        .and_then(toml::Value::as_table)
        .and_then(|package| package.get("name"))
        .and_then(toml::Value::as_str)
        .map(ToOwned::to_owned)
}

/// Adds Miden package stem candidates if they have not already been added.
fn push_dependency_stem(stems: &mut Vec<String>, name: &str) {
    if !name.is_empty() && !stems.iter().any(|existing| existing == name) {
        stems.push(name.to_owned());
    }

    let normalized = name.replace('-', "_");
    if !normalized.is_empty() && !stems.iter().any(|existing| existing == &normalized) {
        stems.push(normalized);
    }
}

/// Extracts the WIT interface/function key encoded in a package procedure export path.
fn procedure_root_key_from_export_path(path: &MasmPath) -> Option<ProcedureRootKey> {
    let interface = single_non_root_path_component(path.parent()?)?;
    let function = path.last()?;
    Some(ProcedureRootKey::new(interface, function))
}

/// Returns the only non-root path component if `path` has exactly one.
fn single_non_root_path_component(path: &MasmPath) -> Option<&str> {
    let mut component = None;

    for next in path.components() {
        let next = next.ok()?;
        match next {
            PathComponent::Root => continue,
            PathComponent::Normal(_) => {
                if component.replace(next.as_str()).is_some() {
                    return None;
                }
            }
        }
    }

    component
}

/// Converts a MAST digest word into literal field elements.
fn procedure_root_from_digest(digest: &miden_protocol::Word) -> ProcedureRoot {
    let elements = digest.as_elements();
    ProcedureRoot {
        felts: [
            elements[0].as_canonical_u64(),
            elements[1].as_canonical_u64(),
            elements[2].as_canonical_u64(),
            elements[3].as_canonical_u64(),
        ],
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn procedure_root_key_uses_full_wit_interface_component() {
        let path =
            MasmPath::validate(r#"::"miden:no-arg-account/no-arg-account@0.0.1"::"get-count""#)
                .expect("fixture path must be valid");

        let key = procedure_root_key_from_export_path(path)
            .expect("WIT export path must produce a procedure root key");

        assert_eq!(
            key,
            ProcedureRootKey::new("miden:no-arg-account/no-arg-account@0.0.1", "get-count")
        );
    }

    #[test]
    fn dependency_stem_preserves_package_filename_before_legacy_alias() {
        let mut stems = Vec::new();

        push_dependency_stem(&mut stems, "no-arg-account");

        assert_eq!(stems, ["no-arg-account", "no_arg_account"]);
    }

    #[test]
    fn dependency_output_dirs_include_manifest_ancestor_targets() {
        let temp_root = env::temp_dir()
            .join(format!("midenc-fpi-dependency-output-dirs-{}", std::process::id()));
        let workspace_root = temp_root.join("workspace");
        let dependency_root = workspace_root.join("tests/fixtures/dependency");
        std::fs::create_dir_all(&dependency_root).unwrap();
        std::fs::write(workspace_root.join("Cargo.lock"), "").unwrap();
        std::fs::write(dependency_root.join("Cargo.toml"), "").unwrap();

        let mut dirs = Vec::new();
        push_manifest_ancestor_target_profile_dirs(
            &mut dirs,
            &dependency_root,
            &[String::from("release")],
        );

        assert_eq!(dirs[0], dependency_root.join("target/miden/release"));
        assert!(
            dirs.contains(&workspace_root.join("target/miden/release")),
            "expected workspace target in {dirs:?}"
        );

        std::fs::remove_dir_all(temp_root).unwrap();
    }

    #[test]
    fn missing_dependency_package_message_explains_macro_time_requirement() {
        let temp_root =
            env::temp_dir().join(format!("midenc-fpi-missing-package-{}", std::process::id()));
        std::fs::create_dir_all(&temp_root).unwrap();
        std::fs::write(temp_root.join("Cargo.toml"), "[package]\nname = \"counter\"\n").unwrap();

        let dependency = SelectedDependency {
            name: "counter".to_string(),
            root: temp_root.clone(),
            interface: DependencyInterface {
                name: "counter".to_string(),
                import: "miden:counter/counter@0.0.1".to_string(),
                types: Vec::new(),
            },
        };
        let profiles = vec!["release".to_string(), "debug".to_string()];
        let stems = vec!["counter".to_string(), "counter_component".to_string()];
        let output_dirs =
            vec![temp_root.join("target/miden/release"), temp_root.join("target/miden/debug")];

        let message =
            missing_dependency_package_message(&dependency, &stems, &output_dirs, &profiles);

        assert!(message.contains("miden::generate! could not find a built `.masp` package"));
        assert!(message.contains("FPI wrappers need the dependency package during Rust macro"));
        assert!(message.contains("counter.masp in release"));
        assert!(message.contains("counter_component.masp in debug"));
        assert!(message.contains("cargo miden build --manifest-path"));
        assert!(message.contains(&temp_root.display().to_string()));

        std::fs::remove_dir_all(temp_root).unwrap();
    }

    #[test]
    fn procedure_root_key_rejects_nested_non_wit_export_path() {
        let path = MasmPath::validate(
            r#"::"miden:no-arg-note/no-arg-note@0.0.1"::no_arg_note::cabi_realloc"#,
        )
        .expect("fixture path must be valid");

        assert_eq!(procedure_root_key_from_export_path(path), None);
    }

    #[test]
    fn procedure_root_key_separates_same_function_in_different_interfaces() {
        let first = ProcedureRootKey::new("miden:foo/account@0.0.1", "get-count");
        let second = ProcedureRootKey::new("miden:foo/account-admin@0.0.1", "get-count");

        assert_ne!(first, second);
    }

    #[test]
    fn reserved_fpi_namespace_allows_regular_dependency_functions() {
        let functions = [test_function("get-count")];

        validate_reserved_fpi_namespace("miden:counter/counter@0.0.1", functions.iter())
            .expect("regular dependency function names must be allowed");
    }

    #[test]
    fn reserved_fpi_namespace_rejects_real_fpi_prefixed_functions() {
        let functions = [test_function("fpi-get-count")];

        let err = validate_reserved_fpi_namespace("miden:counter/counter@0.0.1", functions.iter())
            .expect_err("real dependency functions must not use the generated FPI prefix");
        let message = err.to_string();

        assert!(message.contains("miden:counter/counter@0.0.1"), "unexpected error: {message}");
        assert!(message.contains("fpi-get-count"), "unexpected error: {message}");
        assert!(message.contains("reserved FPI prefix `fpi-`"), "unexpected error: {message}");
        assert!(message.contains("starting with `fpi_`"), "unexpected error: {message}");
    }

    #[test]
    fn method_ident_rejects_reserved_new() {
        let func: ItemFn = parse_quote! {
            pub fn fpi_new(
                account_id_prefix: ::miden::Felt,
                account_id_suffix: ::miden::Felt,
                foreign_proc_root: ::miden::Word,
            ) {}
        };

        let err = method_ident(&func)
            .expect_err("FPI methods must not collide with the generated constructor");
        let message = err.to_string();

        assert!(message.contains("reserved wrapper method `new`"));
        assert!(message.contains("must not be named `new`"));
    }

    #[test]
    fn foreign_account_struct_derives_only_default() {
        let marker: ItemStruct = parse_quote! {
            #[derive(Clone, PartialEq)]
            struct Wallet;
        };

        let expanded = foreign_account_struct(&marker).unwrap();
        let rendered = expanded.to_token_stream().to_string();

        // User derives are kept verbatim.
        for kept in ["Clone", "PartialEq"] {
            assert_eq!(rendered.matches(kept).count(), 1, "expected `{kept}` kept: {rendered}");
        }
        // `Default` is the only trait the macro adds; conveniences are left to the user.
        assert_eq!(rendered.matches("Default").count(), 1, "expected added `Default`: {rendered}");
        for absent in ["Copy", "Debug"] {
            assert_eq!(
                rendered.matches(absent).count(),
                0,
                "macro must not derive `{absent}`: {rendered}"
            );
        }
    }

    #[test]
    fn foreign_account_struct_skips_duplicate_default_derive() {
        let marker: ItemStruct = parse_quote! {
            #[derive(Default)]
            struct Wallet;
        };

        let expanded = foreign_account_struct(&marker).unwrap();
        let rendered = expanded.to_token_stream().to_string();

        // The user already derives `Default`, so the macro must not add a second one.
        assert_eq!(
            rendered.matches("Default").count(),
            1,
            "expected exactly one `Default` in expansion: {rendered}"
        );
    }

    #[test]
    fn method_ident_rejects_active_account_collision() {
        let func: ItemFn = parse_quote! {
            pub fn fpi_get_id(
                account_id_prefix: ::miden::Felt,
                account_id_suffix: ::miden::Felt,
                foreign_proc_root: ::miden::Word,
            ) {}
        };

        let err =
            method_ident(&func).expect_err("FPI methods must not shadow `ActiveAccount` built-ins");
        let message = err.to_string();

        assert!(message.contains("`get-id`"), "unexpected error: {message}");
        assert!(
            message.contains("`ActiveAccount` method `get_id`"),
            "unexpected error: {message}"
        );
    }

    fn test_function(name: &str) -> Function {
        Function {
            name: name.to_string(),
            kind: FunctionKind::Freestanding,
            params: Vec::new(),
            result: None,
            docs: Docs::default(),
            stability: Default::default(),
            span: WitSpan::default(),
        }
    }
}