fp-macros 0.7.1

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
//! HM type transformation visitor.
//!
//! This module contains the HmAstBuilder, which implements the TypeVisitor trait
//! to transform Rust types into Hindley-Milner representations.

use {
	crate::{
		analysis::{
			get_apply_macro_parameters,
			get_fn_brand_info,
			traits::format_brand_name,
		},
		core::{
			config::Config,
			constants::{
				markers,
				types,
			},
		},
		hm::{
			HmAst,
			converter::{
				get_smart_pointer_inner,
				is_phantom_data_path,
				is_smart_pointer,
				trait_bound_to_hm_type,
			},
		},
		support::{
			TypeVisitor,
			last_path_segment,
		},
	},
	std::collections::{
		HashMap,
		HashSet,
	},
	syn::{
		GenericArgument,
		PathArguments,
		ReturnType,
		TypeParamBound,
	},
};

/// Visitor that builds HM type representations from Rust types.
///
/// This is the main type transformation engine. It implements TypeVisitor
/// to traverse Rust type syntax trees and produce HmAst representations.
pub struct HmAstBuilder<'a> {
	pub fn_bounds: &'a HashMap<String, HmAst>,
	pub generic_names: &'a HashSet<String>,
	pub config: &'a Config,
}

impl<'a> TypeVisitor for HmAstBuilder<'a> {
	type Output = HmAst;

	fn default_output(&self) -> Self::Output {
		HmAst::Unit
	}

	fn visit_path(
		&mut self,
		type_path: &syn::TypePath,
	) -> Self::Output {
		// Check for FnBrand pattern using shared helper
		if let Some(fn_brand_info) = get_fn_brand_info(type_path, self.config) {
			let input_hm_types: Vec<_> =
				fn_brand_info.inputs.iter().map(|ty| self.visit(ty)).collect();
			let output_hm = self.visit(&fn_brand_info.output);

			let input = if input_hm_types.is_empty() {
				HmAst::Unit
			} else if input_hm_types.len() == 1 {
				// SAFETY: length checked to be 1 above
				#[expect(clippy::indexing_slicing, reason = "Length checked above")]
				input_hm_types[0].clone()
			} else {
				HmAst::Tuple(input_hm_types)
			};
			return HmAst::Arrow(Box::new(input), Box::new(output_hm));
		}

		if let Some(type_path_inner) = &type_path.qself {
			let constructor_type = self.visit(&type_path_inner.ty);
			let Some(last_segment) = last_path_segment(&type_path.path) else {
				// Defensive fallback for malformed qualified paths
				return HmAst::Variable("unknown".to_string());
			};

			let mut args_list = Vec::new();

			if let PathArguments::AngleBracketed(args) = &last_segment.arguments {
				for arg in &args.args {
					if let GenericArgument::Type(inner_ty) = arg {
						args_list.push(self.visit(inner_ty));
					}
				}
			}

			// Merge constructor and args
			match constructor_type {
				HmAst::Variable(name) =>
					if args_list.is_empty() {
						HmAst::Variable(name)
					} else {
						HmAst::Constructor(name, args_list)
					},
				HmAst::Constructor(name, mut prev_args) => {
					prev_args.extend(args_list);
					HmAst::Constructor(name, prev_args)
				}
				_ => {
					// Fallback: treat the constructor as a string variable if possible, or just fail/print
					// For now, convert to string
					let name = format!("{constructor_type}");
					HmAst::Constructor(name, args_list)
				}
			}
		} else {
			// No QSelf
			if is_phantom_data_path(type_path) {
				return HmAst::Unit;
			}

			if type_path.path.segments.len() >= 2 {
				// SAFETY: segments.len() >= 2 checked above
				#[expect(clippy::indexing_slicing, reason = "Length checked above")]
				let first = &type_path.path.segments[0];
				let Some(last) = last_path_segment(&type_path.path) else {
					// Should be unreachable given the len() >= 2 check, but handle defensively
					return HmAst::Variable("unknown".to_string());
				};

				// Detect associated type access: Brand::Index where first segment
				// is a known generic type parameter. Return just the associated
				// type name (e.g., "Index") instead of the brand name.
				let first_name = first.ident.to_string();
				if type_path.path.segments.len() == 2
					&& self.generic_names.contains(&first_name)
					&& matches!(last.arguments, PathArguments::None)
				{
					return HmAst::Variable(last.ident.to_string());
				}

				let mut constructor_name = first_name;
				if self.config.concrete_types.contains(&constructor_name) {
					// Preserve concrete types as-is (keep original case)
				} else if self.generic_names.contains(&constructor_name) {
					// Keep type parameters in original case (uppercase)
				} else if constructor_name == types::SELF {
					// Use self_type_name if available, otherwise keep as "Self"
					constructor_name = self
						.config
						.self_type_name
						.clone()
						.unwrap_or_else(|| types::SELF.to_string());
				} else {
					constructor_name = format_brand_name(&constructor_name, self.config);
				}

				if let PathArguments::AngleBracketed(args) = &last.arguments {
					let mut type_args = Vec::new();
					for arg in &args.args {
						if let GenericArgument::Type(inner_ty) = arg {
							type_args.push(self.visit(inner_ty));
						}
					}
					if !type_args.is_empty() {
						return HmAst::Constructor(constructor_name, type_args);
					}
				}
				return HmAst::Variable(constructor_name);
			}

			// Simple path or Single segment
			let Some(segment) = last_path_segment(&type_path.path) else {
				// Defensive fallback for empty paths (shouldn't happen with valid Rust)
				return HmAst::Variable("unknown".to_string());
			};
			let name = segment.ident.to_string();

			if is_smart_pointer(&name)
				&& let Some(inner_ty) = get_smart_pointer_inner(segment)
			{
				return self.visit(inner_ty);
			}

			if let Some(sig) = self.fn_bounds.get(&name) {
				if let HmAst::Variable(v) = sig
					&& v == markers::FN_BRAND_MARKER
				{
					// Keep type parameters in original case
					return HmAst::Variable(name);
				}
				return sig.clone();
			}

			// Check if this is a concrete type that should be preserved
			if self.config.concrete_types.contains(&name) {
				// But still process generic arguments if present
				match &segment.arguments {
					PathArguments::AngleBracketed(args) => {
						let mut type_args = Vec::new();
						for arg in &args.args {
							if let GenericArgument::Type(inner_ty) = arg {
								type_args.push(self.visit(inner_ty));
							}
						}
						if type_args.is_empty() {
							return HmAst::Variable(name);
						} else {
							return HmAst::Constructor(name, type_args);
						}
					}
					_ => return HmAst::Variable(name),
				}
			}

			// Keep type parameters in original case (uppercase)
			if self.generic_names.contains(&name) {
				return HmAst::Variable(name);
			}

			// Handle Self with self_type_name if available
			if name == types::SELF {
				return HmAst::Variable(
					self.config.self_type_name.clone().unwrap_or_else(|| types::SELF.to_string()),
				);
			}

			let brand_name = format_brand_name(&name, self.config);

			match &segment.arguments {
				PathArguments::AngleBracketed(args) => {
					let mut type_args = Vec::new();
					for arg in &args.args {
						if let GenericArgument::Type(inner_ty) = arg {
							type_args.push(self.visit(inner_ty));
						}
					}
					if type_args.is_empty() {
						HmAst::Variable(brand_name)
					} else {
						HmAst::Constructor(brand_name, type_args)
					}
				}
				_ => HmAst::Variable(brand_name),
			}
		}
	}

	fn visit_macro(
		&mut self,
		type_macro: &syn::TypeMacro,
	) -> Self::Output {
		// Check for Apply! macro using shared helper
		if let Some((brand, args)) = get_apply_macro_parameters(type_macro) {
			let constructor_type = self.visit(&brand);
			let type_args: Vec<_> = args.iter().map(|ty| self.visit(ty)).collect();

			match constructor_type {
				HmAst::Variable(name) =>
					if type_args.is_empty() {
						HmAst::Variable(name)
					} else {
						HmAst::Constructor(name, type_args)
					},
				HmAst::Constructor(name, mut prev_args) => {
					prev_args.extend(type_args);
					HmAst::Constructor(name, prev_args)
				}
				_ => {
					let name = format!("{constructor_type}");
					HmAst::Constructor(name, type_args)
				}
			}
		} else {
			HmAst::Variable("macro".to_string())
		}
	}

	fn visit_reference(
		&mut self,
		type_ref: &syn::TypeReference,
	) -> Self::Output {
		let inner = self.visit(&type_ref.elem);
		if type_ref.mutability.is_some() {
			HmAst::MutableReference(Box::new(inner))
		} else {
			HmAst::Reference(Box::new(inner))
		}
	}

	fn visit_trait_object(
		&mut self,
		trait_object: &syn::TypeTraitObject,
	) -> Self::Output {
		// Erase auto traits and lifetimes from trait objects
		let mut bounds = Vec::new();
		for bound in &trait_object.bounds {
			if let syn::TypeParamBound::Trait(trait_bound) = bound
				&& let Some(segment) = last_path_segment(&trait_bound.path)
			{
				let name = segment.ident.to_string();
				if !self.config.ignored_traits().contains(&name) {
					bounds.push(trait_bound_to_hm_type(
						trait_bound,
						self.fn_bounds,
						self.generic_names,
						self.config,
					));
				}
			}
			// If path is empty, skip this bound (defensive handling)
		}

		if bounds.is_empty() {
			HmAst::TraitObject(Box::new(HmAst::Variable("_".to_string())))
		} else {
			// SAFETY: bounds checked non-empty above
			#[expect(clippy::indexing_slicing, reason = "Length checked above")]
			let inner = if bounds.len() == 1 { bounds[0].clone() } else { HmAst::Tuple(bounds) };
			HmAst::TraitObject(Box::new(inner))
		}
	}

	fn visit_impl_trait(
		&mut self,
		impl_trait: &syn::TypeImplTrait,
	) -> Self::Output {
		for bound in &impl_trait.bounds {
			if let TypeParamBound::Trait(trait_bound) = bound {
				return trait_bound_to_hm_type(
					trait_bound,
					self.fn_bounds,
					self.generic_names,
					self.config,
				);
			}
		}
		HmAst::Variable("impl_trait".to_string())
	}

	fn visit_bare_fn(
		&mut self,
		bare_fn: &syn::TypeBareFn,
	) -> Self::Output {
		// Erase unsafe and lifetimes from bare fns
		let inputs: Vec<HmAst> = bare_fn.inputs.iter().map(|arg| self.visit(&arg.ty)).collect();
		let output = match &bare_fn.output {
			ReturnType::Default => HmAst::Unit,
			ReturnType::Type(_, ty) => self.visit(ty),
		};
		// SAFETY: inputs.len() == 1 checked in condition
		#[expect(clippy::indexing_slicing, reason = "Length checked above")]
		let input_ty = if inputs.len() == 1 { inputs[0].clone() } else { HmAst::Tuple(inputs) };
		HmAst::Arrow(Box::new(input_ty), Box::new(output))
	}

	fn visit_tuple(
		&mut self,
		tuple: &syn::TypeTuple,
	) -> Self::Output {
		let types: Vec<HmAst> = tuple
			.elems
			.iter()
			.filter(|t| !crate::support::is_phantom_data(t))
			.map(|t| self.visit(t))
			.collect();
		if types.is_empty() {
			HmAst::Unit
		} else if types.len() == 1 {
			// SAFETY: types.len() == 1 checked above
			#[expect(clippy::indexing_slicing, reason = "Length checked above")]
			types[0].clone()
		} else {
			HmAst::Tuple(types)
		}
	}

	fn visit_array(
		&mut self,
		array: &syn::TypeArray,
	) -> Self::Output {
		let inner = self.visit(&array.elem);
		HmAst::List(Box::new(inner))
	}

	fn visit_slice(
		&mut self,
		slice: &syn::TypeSlice,
	) -> Self::Output {
		let inner = self.visit(&slice.elem);
		HmAst::List(Box::new(inner))
	}

	fn visit_other(
		&mut self,
		_ty: &syn::Type,
	) -> Self::Output {
		HmAst::Variable("_".to_string())
	}
}