fp-macros 0.8.0

Procedural macros for generating and working with Higher-Kinded Type (HKT) traits in the fp-library crate.
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
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
use {
	crate::{
		analysis::{
			dispatch::DispatchTraitInfo,
			get_all_parameters,
		},
		core::{
			config::Config,
			constants::attributes::{
				ALLOW_NAMED_GENERICS,
				DOCUMENT_SIGNATURE,
				DOCUMENT_TYPE_PARAMETERS,
				DOCUMENT_USE,
			},
			error_handling::{
				CollectErrors,
				ErrorCollector,
			},
		},
		documentation::document_signature::generate_signature,
		resolution::{
			ImplKey,
			resolver::{
				SelfSubstitutor,
				get_concrete_type_name,
				get_self_type_info,
				merge_generics,
			},
		},
		support::{
			attributes::{
				AttributeExt,
				count_attributes,
				find_attribute,
			},
			documentation_parameters::{
				DocumentationParameter,
				DocumentationParameters,
			},
			generate_documentation::format_parameter_doc,
			parsing::{
				self,
				parse_parameter_documentation_pairs,
			},
		},
	},
	quote::quote,
	syn::{
		FnArg,
		ImplItem,
		Item,
		Result,
		TraitItem,
		Type,
		TypeParamBound,
		parse_quote,
		spanned::Spanned,
		visit_mut::VisitMut,
	},
};

/// Generate a Hindley-Milner type signature and insert it as doc comments.
///
/// This is the shared core used by both impl method and trait method signature processing.
fn insert_signature_docs(
	attrs: &mut Vec<syn::Attribute>,
	attr_pos: usize,
	sig: &syn::Signature,
	config: &Config,
) {
	let signature_data = generate_signature(sig, config);

	let doc_comment = format!("`{signature_data}`");
	let doc_attr: syn::Attribute = parse_quote!(#[doc = #doc_comment]);
	attrs.insert(attr_pos, doc_attr);

	// Add section header
	let header_attr: syn::Attribute = parse_quote!(#[doc = r#"### Type Signature
"#]);
	attrs.insert(attr_pos, header_attr);
}

/// Process the `#[document_signature]` attribute on an impl method.
///
/// Performs Self-type substitution and generics merging before delegating
/// to [`insert_signature_docs`] for the shared doc comment insertion.
#[expect(clippy::too_many_arguments, reason = "Documentation generation requires many parameters")]
pub(super) fn process_document_signature(
	method: &mut syn::ImplItemFn,
	attr_pos: usize,
	self_ty: &syn::Type,
	self_ty_path: &str,
	_trait_name: Option<&str>,
	trait_path_str: Option<&str>,
	document_use: Option<&str>,
	item_impl_generics: &syn::Generics,
	config: &Config,
	errors: &mut ErrorCollector,
) {
	method.attrs.remove(attr_pos);

	let mut synthetic_sig = method.sig.clone();

	// Extract base type name and generic parameters from impl
	let (base_type_name, impl_generic_params) = get_self_type_info(self_ty, item_impl_generics);

	// Resolve Self
	let mut substitutor = SelfSubstitutor::new(
		self_ty,
		self_ty_path,
		trait_path_str,
		document_use,
		config,
		base_type_name.clone(),
		impl_generic_params.clone(),
	);
	substitutor.visit_signature_mut(&mut synthetic_sig);

	// Collect any resolution errors
	errors.extend(substitutor.errors);

	// Merge generics
	merge_generics(&mut synthetic_sig, item_impl_generics);

	// Create a modified config with concrete type information
	let mut sig_config = config.clone();

	// Extract and add the concrete type name
	if let Some(concrete_type_name) = get_concrete_type_name(self_ty, config) {
		sig_config.concrete_types.insert(concrete_type_name.clone());
		sig_config.self_type_name = Some(concrete_type_name);
	}

	insert_signature_docs(&mut method.attrs, attr_pos, &synthetic_sig, &sig_config);
}

/// Process the `#[document_type_parameters]` attribute, shared core.
///
/// Works with any item that has `attrs` and generic parameters - methods (impl or trait),
/// trait definitions, or any other generic item.
fn process_type_parameters_core(
	attrs: &mut Vec<syn::Attribute>,
	generics: &syn::Generics,
	item_label: &str,
	attr_pos: usize,
	errors: &mut ErrorCollector,
) {
	let attr = attrs.remove(attr_pos);

	let param_names: Vec<String> = get_all_parameters(generics);

	// Error if item has no type parameters - use collect_our_result
	if errors
		.collect_our_result(|| {
			parsing::parse_has_documentable_items(
				param_names.len(),
				attr.span(),
				DOCUMENT_TYPE_PARAMETERS,
				&format!("{item_label} with no type parameters"),
			)
		})
		.is_none()
	{
		// Error occurred, return early
		return;
	}

	// Try to parse the arguments from the attribute
	if let Some(args) = errors.collect(|| attr.parse_args::<DocumentationParameters>()) {
		let entries: Vec<_> = args.entries.into_iter().collect();

		if let Some(pairs) = errors.collect_our_result(|| {
			parse_parameter_documentation_pairs(param_names, entries, attr.span())
		}) {
			let mut docs = Vec::new();
			docs.push((
				String::new(),
				r#"### Type Parameters
"#
				.to_string(),
			));

			for (name_from_target, entry) in pairs {
				let (name, desc) = match entry {
					DocumentationParameter::Override(n, d) => (n.value(), d.value()),
					DocumentationParameter::Description(d) => (name_from_target, d.value()),
				};
				docs.push((name, desc));
			}

			for (i, (name, desc)) in docs.into_iter().enumerate() {
				let doc_comment = format_parameter_doc(&name, &desc);
				let doc_attr: syn::Attribute = parse_quote!(#[doc = #doc_comment]);
				attrs.insert(attr_pos + i, doc_attr);
			}
		}
	} else {
		// Parse failed - add a custom error message with context
		errors.push(syn::Error::new(
			attr.span(),
			format!("Failed to parse {DOCUMENT_TYPE_PARAMETERS} arguments"),
		));
	}
}

/// Process the `#[document_type_parameters]` attribute on an impl method.
pub(super) fn process_document_type_parameters(
	method: &mut syn::ImplItemFn,
	attr_pos: usize,
	errors: &mut ErrorCollector,
) {
	process_type_parameters_core(
		&mut method.attrs,
		&method.sig.generics,
		&format!("method '{}'", method.sig.ident),
		attr_pos,
		errors,
	);
}

/// Process method-level documentation (signatures and type parameters).
#[expect(clippy::too_many_arguments, reason = "Documentation generation requires many parameters")]
fn process_method_documentation(
	method: &mut syn::ImplItemFn,
	self_ty: &syn::Type,
	self_ty_path: &str,
	trait_name: Option<&str>,
	trait_path_str: Option<&str>,
	impl_document_use: Option<&str>,
	item_impl_generics: &syn::Generics,
	config: &Config,
	errors: &mut ErrorCollector,
) {
	// Strip #[allow_named_generics] - consumed during lint pass, must not remain in output
	method.attrs.retain(|attr| !attr.path().is_ident(ALLOW_NAMED_GENERICS));

	let method_document_use = method.attrs.find_value_or_collect(DOCUMENT_USE, errors);
	let document_use = method_document_use.or_else(|| impl_document_use.map(String::from));

	// 1. Handle HM Signature
	if let Some(attr_pos) = find_attribute(&method.attrs, DOCUMENT_SIGNATURE) {
		if count_attributes(&method.attrs, DOCUMENT_SIGNATURE) > 1 {
			errors.push(syn::Error::new(
				method.sig.ident.span(),
				format!(
					"#[{DOCUMENT_SIGNATURE}] can only be used once per item. Remove the duplicate attribute on method `{}`",
					method.sig.ident
				),
			));
		} else {
			process_document_signature(
				method,
				attr_pos,
				self_ty,
				self_ty_path,
				trait_name,
				trait_path_str,
				document_use.as_deref(),
				item_impl_generics,
				config,
				errors,
			);
		}
	}

	// 2. Handle Doc Type Params
	if let Some(attr_pos) = find_attribute(&method.attrs, DOCUMENT_TYPE_PARAMETERS) {
		if count_attributes(&method.attrs, DOCUMENT_TYPE_PARAMETERS) > 1 {
			errors.push(syn::Error::new(
				method.sig.ident.span(),
				format!(
					"#[{DOCUMENT_TYPE_PARAMETERS}] can only be used once per item. Remove the duplicate attribute on method `{}`",
					method.sig.ident
				),
			));
		} else {
			process_document_type_parameters(method, attr_pos, errors);
		}
	}

	// 3. Document parameters is now handled directly in document_parameters.rs
	// No processing needed in document_module
}

/// Process a single impl block for documentation generation.
fn process_impl_block(
	item_impl: &mut syn::ItemImpl,
	config: &Config,
	errors: &mut ErrorCollector,
) {
	let self_ty = &*item_impl.self_ty;
	let self_ty_path = quote!(#self_ty).to_string();
	let trait_path = item_impl.trait_.as_ref().map(|(_, path, _)| path);
	let trait_name = trait_path.and_then(|p| p.segments.last().map(|s| s.ident.to_string()));
	let trait_path_str = trait_path.map(|p| quote!(#p).to_string());

	// Generate impl-level documentation for type parameters if attribute is present
	if count_attributes(&item_impl.attrs, DOCUMENT_TYPE_PARAMETERS) > 1 {
		errors.push(syn::Error::new(
			item_impl.self_ty.span(),
			format!(
				"#[{DOCUMENT_TYPE_PARAMETERS}] can only be used once per item. Remove the duplicate attribute on impl block for `{self_ty_path}`",
			),
		));
	} else if let Some(attr_pos) = find_attribute(&item_impl.attrs, DOCUMENT_TYPE_PARAMETERS) {
		// Create impl key and process in one go to avoid borrow conflicts
		let impl_key = ImplKey::from_paths(&self_ty_path, trait_path_str.as_deref());

		// Get the stored impl-level docs from config
		if let Some(impl_docs) = config.impl_type_param_docs.get(&impl_key) {
			// Remove the attribute
			item_impl.attrs.remove(attr_pos);

			// Generate documentation comments for each impl-level type parameter
			let mut docs = Vec::new();
			docs.push((
				String::new(),
				r#"### Type Parameters
"#
				.to_string(),
			));
			for (param_name, desc) in impl_docs.iter() {
				docs.push((param_name.clone(), desc.clone()));
			}

			for (i, (name, desc)) in docs.into_iter().enumerate() {
				let doc_comment = format_parameter_doc(&name, &desc);
				let doc_attr: syn::Attribute = parse_quote!(#[doc = #doc_comment]);
				item_impl.attrs.insert(attr_pos + i, doc_attr);
			}
		} else {
			// This shouldn't happen as context extraction should have caught this
			// But remove the attribute anyway to prevent downstream issues
			item_impl.attrs.remove(attr_pos);
		}
	}

	// Parse impl-level document_use attribute
	let impl_document_use = item_impl.attrs.find_value_or_collect(DOCUMENT_USE, errors);

	// Process each method in the impl block
	for impl_item in &mut item_impl.items {
		if let ImplItem::Fn(method) = impl_item {
			process_method_documentation(
				method,
				self_ty,
				&self_ty_path,
				trait_name.as_deref(),
				trait_path_str.as_deref(),
				impl_document_use.as_deref(),
				&item_impl.generics,
				config,
				errors,
			);
		}
	}
}

/// Process a trait method's documentation (signatures and type parameters).
///
/// Unlike impl methods, trait methods have no Self-type context, so signature
/// generation uses the method signature directly without substitution.
fn process_trait_method_documentation(
	method: &mut syn::TraitItemFn,
	config: &Config,
	errors: &mut ErrorCollector,
) {
	// 1. Handle HM Signature - no Self substitution needed
	if let Some(attr_pos) = find_attribute(&method.attrs, DOCUMENT_SIGNATURE) {
		if count_attributes(&method.attrs, DOCUMENT_SIGNATURE) > 1 {
			errors.push(syn::Error::new(
				method.sig.ident.span(),
				format!(
					"#[{DOCUMENT_SIGNATURE}] can only be used once per item. Remove the duplicate attribute on method `{}`",
					method.sig.ident
				),
			));
		} else {
			method.attrs.remove(attr_pos);
			insert_signature_docs(&mut method.attrs, attr_pos, &method.sig, config);
		}
	}

	// 2. Handle Doc Type Params
	if let Some(attr_pos) = find_attribute(&method.attrs, DOCUMENT_TYPE_PARAMETERS) {
		if count_attributes(&method.attrs, DOCUMENT_TYPE_PARAMETERS) > 1 {
			errors.push(syn::Error::new(
				method.sig.ident.span(),
				format!(
					"#[{DOCUMENT_TYPE_PARAMETERS}] can only be used once per item. Remove the duplicate attribute on method `{}`",
					method.sig.ident
				),
			));
		} else {
			process_type_parameters_core(
				&mut method.attrs,
				&method.sig.generics,
				&format!("method '{}'", method.sig.ident),
				attr_pos,
				errors,
			);
		}
	}
}

/// Process a trait definition for documentation generation.
fn process_trait_block(
	item_trait: &mut syn::ItemTrait,
	config: &Config,
	errors: &mut ErrorCollector,
) {
	// Handle trait-level #[document_type_parameters]
	if let Some(attr_pos) = find_attribute(&item_trait.attrs, DOCUMENT_TYPE_PARAMETERS) {
		if count_attributes(&item_trait.attrs, DOCUMENT_TYPE_PARAMETERS) > 1 {
			errors.push(syn::Error::new(
				item_trait.ident.span(),
				format!(
					"#[{DOCUMENT_TYPE_PARAMETERS}] can only be used once per item. Remove the duplicate attribute on trait `{}`",
					item_trait.ident
				),
			));
		} else {
			process_type_parameters_core(
				&mut item_trait.attrs,
				&item_trait.generics,
				&format!("trait '{}'", item_trait.ident),
				attr_pos,
				errors,
			);
		}
	}

	// Process each method in the trait
	for item in &mut item_trait.items {
		if let TraitItem::Fn(method) = item {
			process_trait_method_documentation(method, config, errors);
		}
	}
}

/// Generate documentation for all items.
///
/// This is the main entry point for documentation generation. It processes impl blocks
/// and trait definitions in the provided items, generating documentation for type
/// parameters, method signatures, and other attributes.
pub(super) fn generate_documentation(
	items: &mut [Item],
	config: &Config,
) -> Result<()> {
	let mut errors = ErrorCollector::new();

	for item in items {
		match item {
			Item::Impl(item_impl) => process_impl_block(item_impl, config, &mut errors),
			Item::Trait(item_trait) => process_trait_block(item_trait, config, &mut errors),
			Item::Fn(item_fn) => {
				// Strip #[allow_named_generics] - consumed during lint pass, must not remain
				// in output
				item_fn.attrs.retain(|attr| !attr.path().is_ident(ALLOW_NAMED_GENERICS));

				// If this function has #[document_signature] and references a dispatch trait,
				// generate a dispatch-aware HM signature and remove the attribute so the
				// standalone macro does not also process it.
				process_fn_dispatch_signature(item_fn, config);
			}
			_ => {}
		}
	}

	errors.finish()
}

// -- Dispatch-aware free function signature generation --

/// Process `#[document_signature]` on a free function if it references a dispatch trait.
///
/// If the function has `#[document_signature]` and an `impl *Dispatch<...>` parameter,
/// removes the attribute and inserts a dispatch-aware HM signature as doc comments.
/// If no dispatch trait is found, the attribute is left for the standalone macro.
fn process_fn_dispatch_signature(
	item_fn: &mut syn::ItemFn,
	config: &Config,
) {
	let Some(attr_pos) = find_attribute(&item_fn.attrs, DOCUMENT_SIGNATURE) else {
		return;
	};

	// If the attribute has a string argument (manual override), use it directly
	if let Some(attr) = item_fn.attrs.get(attr_pos)
		&& let Some(manual_sig) = extract_manual_signature(attr)
	{
		item_fn.attrs.remove(attr_pos);
		let doc_comment = format!("`{manual_sig}`");
		let doc_attr: syn::Attribute = parse_quote!(#[doc = #doc_comment]);
		item_fn.attrs.insert(attr_pos, doc_attr);
		let header_attr: syn::Attribute = parse_quote!(#[doc = r#"### Type Signature
"#]);
		item_fn.attrs.insert(attr_pos, header_attr);
		return;
	}

	let Some(dispatch_info) = find_dispatch_trait_in_sig(&item_fn.sig, config) else {
		// No dispatch trait found; leave #[document_signature] for the standalone macro
		return;
	};

	// Build synthetic signature; if it fails (e.g., missing Kind hash), leave
	// the attribute for the standalone macro
	let Some(synthetic_sig) = build_synthetic_signature(&item_fn.sig, &dispatch_info) else {
		return;
	};

	// Remove the attribute so the standalone macro does not also process it
	item_fn.attrs.remove(attr_pos);

	// Generate HM signature from the synthetic signature via the existing pipeline
	let sig_data = generate_signature(&synthetic_sig, config);

	let doc_comment = format!("`{sig_data}`");
	let doc_attr: syn::Attribute = parse_quote!(#[doc = #doc_comment]);
	item_fn.attrs.insert(attr_pos, doc_attr);

	let header_attr: syn::Attribute = parse_quote!(#[doc = r#"### Type Signature
"#]);
	item_fn.attrs.insert(attr_pos, header_attr);
}

/// Extract a manual signature override from a `#[document_signature("...")]` attribute.
///
/// Returns `Some(String)` if the attribute has a string literal argument.
/// Returns `None` if the attribute has no arguments.
fn extract_manual_signature(attr: &syn::Attribute) -> Option<String> {
	let syn::Meta::List(meta_list) = &attr.meta else {
		return None;
	};
	let lit: syn::LitStr = syn::parse2(meta_list.tokens.clone()).ok()?;
	let value = lit.value();
	if value.is_empty() { None } else { Some(value) }
}

/// Find a dispatch trait referenced in a function's parameters via `impl *Dispatch<...>`.
fn find_dispatch_trait_in_sig(
	sig: &syn::Signature,
	config: &Config,
) -> Option<DispatchTraitInfo> {
	for input in &sig.inputs {
		let FnArg::Typed(pat_type) = input else {
			continue;
		};
		let Type::ImplTrait(impl_trait) = &*pat_type.ty else {
			continue;
		};
		for bound in &impl_trait.bounds {
			let TypeParamBound::Trait(trait_bound) = bound else {
				continue;
			};
			let Some(segment) = trait_bound.path.segments.last() else {
				continue;
			};
			let name = segment.ident.to_string();
			if let Some(info) = config.dispatch_traits.get(&name) {
				return Some(info.clone());
			}
		}
	}

	// Also check where-clause bounds for closureless dispatch
	// (the container type itself has a *Dispatch bound)
	if let Some(where_clause) = &sig.generics.where_clause {
		for predicate in &where_clause.predicates {
			if let syn::WherePredicate::Type(pred_type) = predicate {
				for bound in &pred_type.bounds {
					if let TypeParamBound::Trait(trait_bound) = bound {
						let Some(segment) = trait_bound.path.segments.last() else {
							continue;
						};
						let name = segment.ident.to_string();
						if let Some(info) = config.dispatch_traits.get(&name) {
							return Some(info.clone());
						}
					}
				}
			}
		}
	}

	None
}

/// Information about a type parameter bounded by `InferableFnBrand<_, A, B, _>`.
///
/// When `WrappedFn: InferableFnBrand<FnBrand, A, B, Mode>`, the type parameter
/// `WrappedFn` is semantically `(A -> B)` and should be hidden from the forall
/// clause, with occurrences replaced by an arrow type.
struct FnBrandResolution {
	/// The input type ident (second type arg of InferableFnBrand).
	input: syn::Ident,
	/// The output type ident (third type arg of InferableFnBrand).
	output: syn::Ident,
}

/// Scan the signature's where clause for `InferableFnBrand` bounds and return
/// a map from bounded type parameter name to its arrow components.
///
/// For example, `WrappedFn: InferableFnBrand<FnBrand, A, B, Mode>` produces
/// `{ "WrappedFn" -> FnBrandResolution { input: A, output: B } }`.
fn extract_fn_brand_resolutions(
	sig: &syn::Signature
) -> std::collections::HashMap<String, FnBrandResolution> {
	use crate::analysis::generics::{
		trait_bound_name,
		where_clause_type_predicates,
	};

	let mut result = std::collections::HashMap::new();
	for (ident, bounds) in where_clause_type_predicates(&sig.generics) {
		for bound in bounds {
			let TypeParamBound::Trait(trait_bound) = bound else {
				continue;
			};
			if trait_bound_name(trait_bound)
				.is_none_or(|n| n != crate::core::constants::markers::INFERABLE_FN_BRAND)
			{
				continue;
			}
			let Some(segment) = trait_bound.path.segments.last() else {
				continue;
			};
			let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
				continue;
			};
			// InferableFnBrand<FnBrand, A, B, Mode> - extract A (index 1) and B (index 2)
			let type_args: Vec<&syn::Ident> = args
				.args
				.iter()
				.filter_map(|arg| {
					if let syn::GenericArgument::Type(Type::Path(tp)) = arg {
						tp.path.get_ident()
					} else {
						None
					}
				})
				.collect();
			// type_args[0] = FnBrand, [1] = A, [2] = B, [3] = Mode (optional)
			if let [_, input, output, ..] = type_args.as_slice() {
				result.insert(
					ident.to_string(),
					FnBrandResolution {
						input: (*input).clone(),
						output: (*output).clone(),
					},
				);
			}
		}
	}
	result
}

/// Build a synthetic `syn::Signature` that replaces dispatch machinery with
/// semantic equivalents. The result is fed to `generate_signature()` which
/// already handles Apply! simplification, qualified paths, and brand name
/// formatting.
///
/// Returns `None` if the Kind hash is not available (fallback to standalone macro).
fn build_synthetic_signature(
	_original_sig: &syn::Signature,
	dispatch_info: &DispatchTraitInfo,
) -> Option<syn::Signature> {
	let kind_trait_name = dispatch_info.kind_trait_name.as_ref()?;
	let brand_param = &dispatch_info.brand_param;
	let kind_ident: syn::Ident = syn::parse_str(kind_trait_name).ok()?;
	let brand_ident: syn::Ident = syn::parse_str(brand_param).ok()?;

	// Resolve InferableFnBrand bounds: type params like WrappedFn that are
	// bounded by InferableFnBrand<FnBrand, A, B, _> are semantically (A -> B)
	// and should be hidden from forall with their occurrences substituted.
	let fn_brand_resolutions = extract_fn_brand_resolutions(_original_sig);

	// Build generic params
	let mut generic_params: Vec<syn::GenericParam> = Vec::new();

	// Lifetime 'a
	generic_params.push(parse_quote!('a));

	// Brand: SemanticConstraint + Kind_hash
	if let Some(ref constraint_name) = dispatch_info.semantic_constraint {
		let constraint_ident: syn::Ident = syn::parse_str(constraint_name).ok()?;
		generic_params.push(parse_quote!(#brand_ident: #constraint_ident + #kind_ident));
	} else {
		generic_params.push(parse_quote!(#brand_ident: #kind_ident));
	}

	// Add type params in the order they appear in the dispatch trait definition.
	// This preserves the trait author's intended ordering for the forall clause.
	// Brand is already added above; skip it and add the remaining params.
	// Params resolved via InferableFnBrand are also skipped (they appear as
	// arrow types in container element positions instead).
	let mut all_element_types: Vec<String> = Vec::new();
	let secondary_map: std::collections::HashMap<&str, &str> =
		dispatch_info.secondary_constraints.iter().map(|(p, c)| (p.as_str(), c.as_str())).collect();

	for param_name in &dispatch_info.type_param_order {
		// Brand is already added as the first generic param
		if param_name == brand_param {
			continue;
		}

		// Skip params resolved via InferableFnBrand (e.g., WrappedFn)
		if fn_brand_resolutions.contains_key(param_name) {
			continue;
		}

		// Secondary constraint params (e.g., F: Applicative, M: Applicative)
		if let Some(constraint_name) = secondary_map.get(param_name.as_str()) {
			let param_ident: syn::Ident = syn::parse_str(param_name).ok()?;
			let constraint_ident: syn::Ident = syn::parse_str(constraint_name).ok()?;
			generic_params.push(parse_quote!(#param_ident: #constraint_ident + #kind_ident));
			continue;
		}

		// Element type params
		if let Ok(param_ident) = syn::parse_str::<syn::Ident>(param_name) {
			generic_params.push(parse_quote!(#param_ident: 'a));
			all_element_types.push(param_name.clone());
		}
	}

	// Build function parameters by transforming the original signature's params.
	// - impl *Dispatch<...> -> impl Fn(inputs) -> output (from arrow type)
	// - Container types (FA, FB) -> <Brand as Kind_hash>::Of<'a, ElementType>
	// - Other params -> keep as-is
	//
	// The container_map maps FUNCTION type param names to element types.
	// This is built by matching the function's dispatch trait type args
	// (which use the function's param names like FA) against the
	// dispatch_info.container_params (which use the trait's param names like FTA).
	let mut container_map = build_container_map(_original_sig, dispatch_info);

	// Resolve InferableFnBrand element types in the container map: if a
	// container's element type is a param resolved via InferableFnBrand
	// (e.g., WrappedFn), replace it with a bare fn type so it renders as
	// (A -> B) in the HM signature.
	if !fn_brand_resolutions.is_empty() {
		for elements in container_map.values_mut() {
			resolve_fn_brand_elements(elements, &fn_brand_resolutions);
		}
	}

	let mut fn_params: Vec<syn::FnArg> = Vec::new();

	for input in &_original_sig.inputs {
		let FnArg::Typed(pat_type) = input else {
			continue;
		};

		// Check if this is the impl Dispatch parameter -> replace with Fn closure
		if matches!(&*pat_type.ty, Type::ImplTrait(_))
			&& let Some(ref arrow) = dispatch_info.arrow_type
			&& let Some(closure_param) =
				build_closure_param(arrow, dispatch_info.tuple_closure, &brand_ident, &kind_ident)
		{
			fn_params.push(closure_param);
			continue;
		}
		// For closureless dispatch with impl *Dispatch param (e.g., explicit join),
		// treat the param as a container. Falls through to the container/InferableBrand
		// logic below by extracting the param name from the impl trait bound.
		if let Type::ImplTrait(impl_trait) = &*pat_type.ty {
			// Check if this is an impl *Dispatch bound (closureless container param)
			let is_dispatch_bound = impl_trait.bounds.iter().any(|b| {
				if let TypeParamBound::Trait(t) = b {
					t.path
						.segments
						.last()
						.map(|s| {
							s.ident
								.to_string()
								.ends_with(crate::core::constants::markers::DISPATCH_SUFFIX)
						})
						.unwrap_or(false)
				} else {
					false
				}
			});
			if is_dispatch_bound && dispatch_info.arrow_type.is_none() {
				// Closureless dispatch with impl Dispatch param: treat as container.
				// Use the same fallback chain as InferableBrand-bounded params.
				use crate::analysis::dispatch::ReturnStructure;
				let element_types: Option<Vec<Type>> = dispatch_info
					.self_type_elements
					.clone()
					.or_else(|| {
						let elems: Vec<Type> = dispatch_info
							.type_param_order
							.iter()
							.filter(|p| {
								*p != brand_param
									&& p.len() == 1 && !dispatch_info
									.secondary_constraints
									.iter()
									.any(|(sc, _)| sc == *p)
							})
							.filter_map(|p| syn::parse_str::<Type>(p).ok())
							.collect();
						if elems.is_empty() { None } else { Some(elems) }
					})
					.or_else(|| match &dispatch_info.return_structure {
						ReturnStructure::Applied(args) => Some(args.clone()),
						_ => None,
					});
				if let Some(mut elements) = element_types {
					resolve_fn_brand_elements(&mut elements, &fn_brand_resolutions);
					let pat = &pat_type.pat;
					let container_type = build_applied_type(&brand_ident, &kind_ident, &elements)?;
					fn_params.push(parse_quote!(#pat: #container_type));
					continue;
				}
			}
			// Skip other impl Trait params that didn't produce a closure or container
			continue;
		}

		// For tuple closure dispatch via where-clause (e.g., compose_kleisli
		// where (F, G): ComposeKleisliDispatch), detect tuple params of type vars
		// and replace with the closure tuple.
		//
		// If the function's tuple param order differs from the where clause's
		// dispatch-bounded tuple (e.g., param is (F, G) but where clause has
		// (G, F): Dispatch), reverse the arrow inputs to match the function's
		// parameter order.
		if dispatch_info.tuple_closure
			&& let Type::Tuple(param_tuple) = &*pat_type.ty
			&& param_tuple.elems.len() >= 2
			&& let Some(ref arrow) = dispatch_info.arrow_type
		{
			let effective_arrow = if is_tuple_order_reversed(param_tuple, _original_sig) {
				let mut reversed = arrow.clone();
				reversed.inputs.reverse();
				reversed
			} else {
				arrow.clone()
			};
			if let Some(closure_param) =
				build_closure_param(&effective_arrow, true, &brand_ident, &kind_ident)
			{
				fn_params.push(closure_param);
				continue;
			}
		}

		// Check if this is a container type param -> replace with <Brand as Kind>::Of<...>
		let ty = &pat_type.ty;
		let type_ident_str = match &**ty {
			Type::Path(tp) => tp.path.get_ident().map(|id| id.to_string()),
			_ => None,
		};
		if let Some(ref ident_str) = type_ident_str
			&& let Some(elements) = container_map.get(ident_str.as_str())
		{
			let pat = &pat_type.pat;
			let container_type = build_applied_type(&brand_ident, &kind_ident, elements)?;
			fn_params.push(parse_quote!(#pat: #container_type));
			continue;
		}

		// Check if this is a dispatch trait associated type projection
		// (e.g., <FA as ApplyFirstDispatch<...>>::FB -> Brand B)
		if let Type::Path(type_path) = &*pat_type.ty
			&& type_path.qself.is_some()
			&& let Some(last_seg) = type_path.path.segments.last()
		{
			let assoc_name = last_seg.ident.to_string();
			if let Some((_, elements)) =
				dispatch_info.associated_types.iter().find(|(name, _)| name == &assoc_name)
			{
				let pat = &pat_type.pat;
				let container_type = build_applied_type(&brand_ident, &kind_ident, elements)?;
				fn_params.push(parse_quote!(#pat: #container_type));
				continue;
			}
		}

		// For closureless dispatch or unrecognized container params:
		// if the type is a InferableBrand-bounded or Dispatch-bounded param, it's a container.
		// Fallback chain (most direct source first):
		// 1. self_type_elements: from the Val impl's self type (e.g., separate, compact)
		// 2. type_param_order: single-letter element types from the trait definition (e.g., alt)
		// 3. return structure: from the dispatch method's return type (last resort)
		if is_dispatch_container_param(ty, _original_sig) {
			use crate::analysis::dispatch::ReturnStructure;

			let element_types: Option<Vec<Type>> = dispatch_info
				.self_type_elements
				.clone()
				.or_else(|| {
					// Extract single-letter element types from trait definition params,
					// excluding Brand and secondary constraint params.
					let elems: Vec<Type> = dispatch_info
						.type_param_order
						.iter()
						.filter(|p| {
							*p != brand_param
								&& p.len() == 1 && !dispatch_info
								.secondary_constraints
								.iter()
								.any(|(sc, _)| sc == *p)
						})
						.filter_map(|p| syn::parse_str::<Type>(p).ok())
						.collect();
					if elems.is_empty() { None } else { Some(elems) }
				})
				.or_else(|| match &dispatch_info.return_structure {
					ReturnStructure::Applied(args) => Some(args.clone()),
					ReturnStructure::Nested {
						inner_args, ..
					} => Some(inner_args.clone()),
					ReturnStructure::Tuple(elements) => elements.first().cloned(),
					ReturnStructure::NestedTuple {
						inner_elements, ..
					} => inner_elements.first().cloned(),
					ReturnStructure::Plain(_) => None,
				});
			if let Some(mut elems) = element_types {
				resolve_fn_brand_elements(&mut elems, &fn_brand_resolutions);
				let pat = &pat_type.pat;
				let container_type = build_applied_type(&brand_ident, &kind_ident, &elems)?;
				fn_params.push(parse_quote!(#pat: #container_type));
				continue;
			}
		}

		// Keep other params as-is
		fn_params.push(input.clone());
	}

	// Build return type
	let return_type =
		build_return_type(&dispatch_info.return_structure, &brand_ident, &kind_ident)?;

	// Assemble the signature
	let generics = syn::Generics {
		lt_token: Some(Default::default()),
		params: generic_params.into_iter().collect(),
		gt_token: Some(Default::default()),
		where_clause: None,
	};

	Some(syn::Signature {
		constness: None,
		asyncness: None,
		unsafety: None,
		abi: None,
		fn_token: Default::default(),
		ident: syn::parse_str("synthetic").ok()?,
		generics,
		paren_token: Default::default(),
		inputs: fn_params.into_iter().collect(),
		variadic: None,
		output: syn::ReturnType::Type(Default::default(), Box::new(return_type)),
	})
}

/// Build a container map from the function's dispatch trait type args.
///
/// Uses the container_params' stored position indices to do a direct positional
/// lookup into the function's dispatch trait type args, avoiding heuristic scanning.
/// Keys are type parameter names extracted as idents from the dispatch trait's
/// angle-bracketed arguments.
fn build_container_map(
	sig: &syn::Signature,
	dispatch_info: &DispatchTraitInfo,
) -> std::collections::HashMap<String, Vec<Type>> {
	if dispatch_info.container_params.is_empty() {
		return std::collections::HashMap::new();
	}

	// Extract dispatch trait type arg idents from whichever location has them:
	// either `impl *Dispatch<...>` parameter or where-clause bound.
	let fn_type_arg_idents = extract_dispatch_type_arg_idents(sig);
	if fn_type_arg_idents.is_empty() {
		return std::collections::HashMap::new();
	}

	// Use each container param's stored position to directly look up the
	// corresponding function type arg ident.
	let mut result = std::collections::HashMap::new();
	for cp in &dispatch_info.container_params {
		if let Some(Some(fn_arg_ident)) = fn_type_arg_idents.get(cp.position) {
			result.insert(fn_arg_ident.to_string(), cp.element_types.clone());
		}
	}
	result
}

/// Extract the dispatch trait's type arg idents from a function signature.
///
/// Checks both `impl *Dispatch<...>` parameters and where-clause bounds.
/// Returns one entry per type argument (excluding lifetimes), preserving
/// positional alignment. Complex types produce `None`.
fn extract_dispatch_type_arg_idents(sig: &syn::Signature) -> Vec<Option<syn::Ident>> {
	// Check impl Trait parameters
	for input in &sig.inputs {
		let FnArg::Typed(pat_type) = input else { continue };
		let Type::ImplTrait(impl_trait) = &*pat_type.ty else { continue };
		for bound in &impl_trait.bounds {
			if let Some(args) = extract_dispatch_trait_arg_idents(bound) {
				return args;
			}
		}
	}

	// Check where-clause bounds
	if let Some(where_clause) = &sig.generics.where_clause {
		for predicate in &where_clause.predicates {
			if let syn::WherePredicate::Type(pred_type) = predicate {
				for bound in &pred_type.bounds {
					if let Some(args) = extract_dispatch_trait_arg_idents(bound) {
						return args;
					}
				}
			}
		}
	}

	Vec::new()
}

/// If a type param bound is a `*Dispatch<...>` trait, extract its type arg idents.
///
/// Returns one entry per type argument (excluding lifetimes), preserving
/// positional alignment with the trait definition's type parameters.
/// Complex types that are not simple identifiers produce `None`.
fn extract_dispatch_trait_arg_idents(bound: &TypeParamBound) -> Option<Vec<Option<syn::Ident>>> {
	let TypeParamBound::Trait(trait_bound) = bound else {
		return None;
	};
	let segment = trait_bound.path.segments.last()?;
	if !segment.ident.to_string().ends_with(crate::core::constants::markers::DISPATCH_SUFFIX) {
		return None;
	}
	let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
		return None;
	};
	Some(
		args.args
			.iter()
			.filter_map(|arg| match arg {
				syn::GenericArgument::Type(Type::Path(type_path)) =>
					Some(type_path.path.get_ident().cloned()),
				syn::GenericArgument::Type(_) => Some(None),
				_ => None, // Skip lifetimes
			})
			.collect(),
	)
}

/// Check if a type has an InferableBrand or Dispatch bound in the signature's where clause.
///
/// Only matches simple identifier types (single-segment paths). Complex types
/// (references, qualified paths, etc.) are never dispatch container params.
fn is_dispatch_container_param(
	ty: &syn::Type,
	sig: &syn::Signature,
) -> bool {
	use crate::analysis::generics::{
		collect_trait_bounds_for_param,
		trait_bound_name,
	};

	let Type::Path(type_path) = ty else {
		return false;
	};
	let Some(ident) = type_path.path.get_ident() else {
		return false;
	};
	let ident_str = ident.to_string();
	for bound in collect_trait_bounds_for_param(&ident_str, &sig.generics) {
		if let Some(name) = trait_bound_name(bound) {
			let name_str = name.to_string();
			if name_str.starts_with(crate::core::constants::markers::INFERABLE_BRAND_PREFIX)
				|| name_str.ends_with(crate::core::constants::markers::DISPATCH_SUFFIX)
			{
				return true;
			}
		}
	}
	false
}

/// Check if a function's tuple parameter has its elements in reversed order
/// relative to the dispatch-bounded tuple in the where clause.
///
/// For example, if the function param is `(F, G)` but the where clause has
/// `(G, F): ComposeKleisliDispatch`, the order is reversed. This matters
/// for generating correct HM signatures where the arrow inputs must match
/// the function's actual parameter order.
fn is_tuple_order_reversed(
	param_tuple: &syn::TypeTuple,
	sig: &syn::Signature,
) -> bool {
	let Some(where_clause) = &sig.generics.where_clause else {
		return false;
	};

	// Extract ident names from the function's tuple param elements
	let param_idents: Vec<&syn::Ident> = param_tuple
		.elems
		.iter()
		.filter_map(|elem| if let Type::Path(tp) = elem { tp.path.get_ident() } else { None })
		.collect();
	if param_idents.len() < 2 {
		return false;
	}

	// Find the dispatch-bounded tuple in the where clause
	for predicate in &where_clause.predicates {
		let syn::WherePredicate::Type(pred_type) = predicate else {
			continue;
		};
		let Type::Tuple(where_tuple) = &pred_type.bounded_ty else {
			continue;
		};
		// Check if this tuple has a *Dispatch bound
		let has_dispatch = pred_type.bounds.iter().any(|b| {
			if let TypeParamBound::Trait(tb) = b {
				tb.path.segments.last().is_some_and(|s| {
					s.ident.to_string().ends_with(crate::core::constants::markers::DISPATCH_SUFFIX)
				})
			} else {
				false
			}
		});
		if !has_dispatch {
			continue;
		}

		// Extract ident names from the where clause's tuple
		let where_idents: Vec<&syn::Ident> = where_tuple
			.elems
			.iter()
			.filter_map(|elem| if let Type::Path(tp) = elem { tp.path.get_ident() } else { None })
			.collect();

		// Check if the orders differ (same elements, different positions)
		if param_idents.len() == where_idents.len()
			&& param_idents != where_idents
			&& param_idents.iter().all(|id| where_idents.contains(id))
		{
			return true;
		}
	}

	false
}

/// Resolve element type names through InferableFnBrand mappings.
///
/// Any element that names a type parameter resolved via InferableFnBrand
/// (e.g., `WrappedFn`) is replaced with a bare fn type string `fn(A)->B`.
fn resolve_fn_brand_elements(
	elements: &mut [Type],
	fn_brand_resolutions: &std::collections::HashMap<String, FnBrandResolution>,
) {
	for elem in elements.iter_mut() {
		let key = if let Type::Path(tp) = elem {
			tp.path.get_ident().map(|id| id.to_string())
		} else {
			None
		};
		if let Some(key) = key
			&& let Some(resolution) = fn_brand_resolutions.get(key.as_str())
		{
			let input = &resolution.input;
			let output = &resolution.output;
			let fn_str = format!("fn({input})->{output}");
			if let Ok(fn_ty) = syn::parse_str::<Type>(&fn_str) {
				*elem = fn_ty;
			}
		}
	}
}

/// Build a `<Brand as Kind_hash>::Of<'a, A, B, ...>` qualified path type.
fn build_applied_type(
	brand_ident: &syn::Ident,
	kind_ident: &syn::Ident,
	element_types: &[Type],
) -> Option<syn::Type> {
	let mut args = vec![quote!('a)];
	for elem in element_types {
		args.push(quote!(#elem));
	}
	let args_tokens = quote!(#(#args),*);
	Some(parse_quote!(<#brand_ident as #kind_ident>::Of<#args_tokens>))
}

/// Build the closure parameter as `impl Fn(inputs) -> output`.
fn build_closure_param(
	arrow: &crate::analysis::dispatch::DispatchArrow,
	tuple_closure: bool,
	brand_ident: &syn::Ident,
	kind_ident: &syn::Ident,
) -> Option<syn::FnArg> {
	use crate::analysis::dispatch::{
		ArrowOutput,
		DispatchArrowParam,
	};

	if tuple_closure {
		// For tuple closures (bimap, etc.), each input is a sub-arrow.
		// Build bare fn pointer types in a tuple. The HM pipeline handles
		// fn(A) -> B via visit_bare_fn.
		let mut fn_types: Vec<syn::Type> = Vec::new();

		for param in &arrow.inputs {
			let sub_arrow = match param {
				DispatchArrowParam::SubArrow(arrow) => arrow,
				DispatchArrowParam::TypeParam(_)
				| DispatchArrowParam::AssociatedType {
					..
				} => {
					continue;
				}
			};

			// Build fn type from structured sub-arrow
			let mut input_types: Vec<syn::Type> = Vec::new();
			for sub_param in &sub_arrow.inputs {
				match sub_param {
					DispatchArrowParam::TypeParam(ident) => {
						input_types.push(parse_quote!(#ident));
					}
					DispatchArrowParam::AssociatedType {
						assoc_name,
					} => {
						input_types.push(parse_quote!(#brand_ident::#assoc_name));
					}
					DispatchArrowParam::SubArrow(_) => continue,
				}
			}

			let output_type: syn::Type = match &sub_arrow.output {
				ArrowOutput::Plain(ty) => *ty.clone(),
				ArrowOutput::BrandApplied(args) =>
					build_applied_type(brand_ident, kind_ident, args)?,
				ArrowOutput::OtherApplied {
					brand,
					args,
				} => build_applied_type(brand, kind_ident, args)?,
			};

			fn_types.push(parse_quote!(fn(#(#input_types),*) -> #output_type));
		}

		if fn_types.is_empty() {
			return None;
		}

		return Some(parse_quote!(fg: (#(#fn_types),*)));
	}

	// Single closure: build impl Fn(A, B, ...) -> R
	let mut input_types: Vec<syn::Type> = Vec::new();
	for param in &arrow.inputs {
		match param {
			DispatchArrowParam::TypeParam(ident) => {
				input_types.push(parse_quote!(#ident));
			}
			DispatchArrowParam::AssociatedType {
				assoc_name,
			} => {
				input_types.push(parse_quote!(#brand_ident::#assoc_name));
			}
			DispatchArrowParam::SubArrow(_) => {
				// SubArrow is only used in tuple closures, not single closures
				continue;
			}
		}
	}

	let output_type: syn::Type = match &arrow.output {
		ArrowOutput::Plain(ty) => *ty.clone(),
		ArrowOutput::BrandApplied(args) => build_applied_type(brand_ident, kind_ident, args)?,
		ArrowOutput::OtherApplied {
			brand,
			args,
		} => build_applied_type(brand, kind_ident, args)?,
	};

	Some(parse_quote!(f: impl Fn(#(#input_types),*) -> #output_type + 'a))
}

/// Build the return type from `ReturnStructure`.
fn build_return_type(
	ret: &crate::analysis::dispatch::ReturnStructure,
	brand_ident: &syn::Ident,
	kind_ident: &syn::Ident,
) -> Option<syn::Type> {
	use crate::analysis::dispatch::ReturnStructure;

	match ret {
		ReturnStructure::Plain(ty) => Some(*ty.clone()),
		ReturnStructure::Applied(args) => build_applied_type(brand_ident, kind_ident, args),
		ReturnStructure::Nested {
			outer_param,
			inner_args,
		} => {
			let inner_type = build_applied_type(brand_ident, kind_ident, inner_args)?;
			Some(parse_quote!(<#outer_param as #kind_ident>::Of<'a, #inner_type>))
		}
		ReturnStructure::Tuple(elements) => {
			let elem_types: Vec<syn::Type> = elements
				.iter()
				.filter_map(|args| build_applied_type(brand_ident, kind_ident, args))
				.collect();
			Some(parse_quote!((#(#elem_types),*)))
		}
		ReturnStructure::NestedTuple {
			outer_param,
			inner_elements,
		} => {
			let tuple_types: Vec<syn::Type> = inner_elements
				.iter()
				.filter_map(|args| build_applied_type(brand_ident, kind_ident, args))
				.collect();
			let tuple_type: syn::Type = parse_quote!((#(#tuple_types),*));
			Some(parse_quote!(<#outer_param as #kind_ident>::Of<'a, #tuple_type>))
		}
	}
}