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
//! Unified error handling for fp-macros.
//!
//! This module provides a comprehensive error system with rich context for
//! generating helpful compile-time error messages.

use {
	proc_macro2::{
		Span,
		TokenStream,
	},
	std::fmt,
	thiserror::Error,
};

/// Result type alias using our unified error type
pub type Result<T> = std::result::Result<T, Error>;

/// Main error type for fp-macros
#[derive(Debug, Error)]
pub enum Error {
	/// Parsing error from syn
	#[error("Parse error: {0}")]
	Parse(#[from] syn::Error),

	/// Validation error with span information and optional suggestion
	#[error("Validation error: {message}")]
	Validation {
		/// Error message
		message: String,
		/// Source code span
		span: Span,
		/// Optional suggestion for fixing the error
		suggestion: Option<String>,
	},

	/// Resolution error (e.g., Self type or associated type resolution)
	#[error("Resolution error: {message}")]
	Resolution {
		/// Error message
		message: String,
		/// Source code span
		span: Span,
		/// Available types for helpful error messages
		available_types: Vec<String>,
	},

	/// Unsupported feature error
	#[error("Unsupported feature: {0}")]
	Unsupported(#[from] UnsupportedFeature),

	/// Internal error (for "should never happen" cases)
	#[error("Internal error: {0}")]
	Internal(String),

	/// I/O error (for file operations)
	#[error("I/O error: {0}")]
	Io(#[from] std::io::Error),
}

/// Specific unsupported feature variants
#[derive(Debug, Error)]
pub enum UnsupportedFeature {
	/// Const generic parameters are not supported in Kind definitions
	#[error("Const generic parameters are not supported in Kind definitions")]
	ConstGenerics {
		/// Source code span
		span: Span,
	},

	/// Verbatim bounds are not supported
	#[error("Verbatim bounds are not supported")]
	VerbatimBounds {
		/// Source code span
		span: Span,
	},

	/// Complex types are not supported
	#[error("Complex type not supported: {description}")]
	ComplexTypes {
		/// Description of the unsupported type
		description: String,
		/// Source code span
		span: Span,
	},

	/// Unsupported generic argument
	#[error("Unsupported generic argument: {description}")]
	GenericArgument {
		/// Description of the unsupported argument
		description: String,
		/// Source code span
		span: Span,
	},

	/// Unsupported bound type
	#[error("Unsupported bound type: {description}")]
	BoundType {
		/// Description of the unsupported bound
		description: String,
		/// Source code span
		span: Span,
	},
}

impl Error {
	/// Create a validation error
	pub fn validation(
		span: Span,
		message: impl Into<String>,
	) -> Self {
		Self::Validation {
			message: message.into(),
			span,
			suggestion: None,
		}
	}

	/// Add a suggestion to this error
	pub fn with_suggestion(
		mut self,
		suggestion: impl Into<String>,
	) -> Self {
		if let Error::Validation {
			suggestion: s, ..
		} = &mut self
		{
			*s = Some(suggestion.into());
		}
		self
	}

	/// Create a resolution error with available types for helpful messages
	pub fn resolution(
		span: Span,
		message: impl Into<String>,
		available_types: Vec<String>,
	) -> Self {
		Self::Resolution {
			message: message.into(),
			span,
			available_types,
		}
	}

	/// Create an unsupported feature error
	pub fn unsupported(
		span: Span,
		feature: impl Into<String>,
	) -> Self {
		Self::Unsupported(UnsupportedFeature::ComplexTypes {
			description: feature.into(),
			span,
		})
	}

	/// Create an internal error (for "should never happen" cases)
	pub fn internal(message: impl Into<String>) -> Self {
		Self::Internal(message.into())
	}

	/// Get the span for this error
	pub fn span(&self) -> Span {
		match self {
			Error::Parse(e) => e.span(),
			Error::Validation {
				span, ..
			} => *span,
			Error::Resolution {
				span, ..
			} => *span,
			Error::Unsupported(u) => u.span(),
			Error::Internal(_) => Span::call_site(),
			Error::Io(_) => Span::call_site(),
		}
	}

	/// Add context to an error
	pub fn context(
		self,
		context: impl fmt::Display,
	) -> Self {
		match self {
			Error::Internal(msg) => Error::Internal(format!("{context}: {msg}")),
			Error::Validation {
				message,
				span,
				suggestion,
			} => Error::Validation {
				message: format!("{context}: {message}"),
				span,
				suggestion,
			},
			Error::Resolution {
				message,
				span,
				available_types,
			} => Error::Resolution {
				message: format!("{context}: {message}"),
				span,
				available_types,
			},
			Error::Parse(e) => {
				// Create new error with context and combine
				let ctx_error = syn::Error::new(e.span(), format!("{context}: {e}"));
				Error::Parse(ctx_error)
			}
			Error::Unsupported(u) => {
				// Unsupported features maintain original message
				// but we note the context by wrapping in Internal
				Error::Internal(format!("{context}: Unsupported feature: {u}"))
			}
			Error::Io(io) => Error::Internal(format!("{context}: I/O error: {io}")),
		}
	}

	/// Add context to an error (alias for context, more fluent API)
	pub fn with_context(
		self,
		context: impl fmt::Display,
	) -> Self {
		self.context(context)
	}
}

impl UnsupportedFeature {
	/// Get the span for this unsupported feature
	pub fn span(&self) -> Span {
		match self {
			UnsupportedFeature::ConstGenerics {
				span,
			} => *span,
			UnsupportedFeature::VerbatimBounds {
				span,
			} => *span,
			UnsupportedFeature::ComplexTypes {
				span, ..
			} => *span,
			UnsupportedFeature::GenericArgument {
				span, ..
			} => *span,
			UnsupportedFeature::BoundType {
				span, ..
			} => *span,
		}
	}
}

/// Convert our error to syn::Error for proc macro output
impl From<Error> for syn::Error {
	fn from(err: Error) -> Self {
		// If it's a wrapped syn::Error (Parse variant), return it directly
		// to preserve multiple combined errors (which would be lost if we
		// created a new syn::Error from the Display message).
		if let Error::Parse(e) = err {
			return e;
		}

		let span = err.span();
		let mut message = err.to_string();

		// Add suggestion directly to the message for Validation errors
		if let Error::Validation {
			suggestion: Some(s), ..
		} = &err
		{
			message = format!(
				r#"{message}
  help: {s}"#
			);
		}

		// Add available alternatives for Resolution errors
		if let Error::Resolution {
			available_types, ..
		} = &err && !available_types.is_empty()
		{
			message = format!(
				r#"{message}
  note: available alternatives: {}"#,
				available_types.join(", ")
			);
		}

		syn::Error::new(span, message)
	}
}

/// Utility for collecting and combining multiple errors.
/// Replaces the repeated pattern of error accumulation throughout the codebase.
pub struct ErrorCollector {
	errors: Vec<syn::Error>,
}

#[allow(dead_code, reason = "API kept for completeness")]
impl ErrorCollector {
	pub fn new() -> Self {
		Self {
			errors: Vec::new(),
		}
	}

	pub fn push(
		&mut self,
		error: syn::Error,
	) {
		self.errors.push(error);
	}

	pub fn extend<I>(
		&mut self,
		other_errors: I,
	) where
		I: IntoIterator<Item = syn::Error>, {
		self.errors.extend(other_errors);
	}

	/// Check if there are any errors collected
	pub fn has_errors(&self) -> bool {
		!self.errors.is_empty()
	}

	/// Get the number of errors collected
	pub fn len(&self) -> usize {
		self.errors.len()
	}

	/// Check if the collector is empty
	pub fn is_empty(&self) -> bool {
		self.errors.is_empty()
	}

	/// Consume the collector and return the inner vector of errors
	pub fn into_errors(self) -> Vec<syn::Error> {
		self.errors
	}

	/// Return an iterator over the collected errors
	pub fn iter(&self) -> std::slice::Iter<'_, syn::Error> {
		self.errors.iter()
	}

	pub fn finish(self) -> syn::Result<()> {
		if self.errors.is_empty() { Ok(()) } else { Err(Self::combine_errors(self.errors)) }
	}

	fn combine_errors(mut errors: Vec<syn::Error>) -> syn::Error {
		let mut combined = errors.remove(0);
		for err in errors {
			combined.combine(err);
		}
		combined
	}
}

impl Default for ErrorCollector {
	fn default() -> Self {
		Self::new()
	}
}

impl IntoIterator for ErrorCollector {
	type IntoIter = std::vec::IntoIter<syn::Error>;
	type Item = syn::Error;

	fn into_iter(self) -> Self::IntoIter {
		self.errors.into_iter()
	}
}

impl<'a> IntoIterator for &'a ErrorCollector {
	type IntoIter = std::slice::Iter<'a, syn::Error>;
	type Item = &'a syn::Error;

	fn into_iter(self) -> Self::IntoIter {
		self.errors.iter()
	}
}

/// Trait for collecting errors from fallible operations.
///
/// This trait provides methods to execute fallible operations and automatically
/// collect any errors that occur, allowing the program to continue processing
/// and report all errors at once.
///
/// # Examples
///
/// ```ignore
/// use crate::core::error_handling::{ErrorCollector, CollectErrors};
///
/// let mut errors = ErrorCollector::new();
///
/// // Collect an error from a fallible operation
/// if let Some(result) = errors.collect(|| parse_something()) {
///     // Use result if successful
/// }
///
/// // Collect with context for better error messages
/// if let Some(value) = errors.collect_with_context("parsing attribute", || parse_attr()) {
///     // Use value
/// }
///
/// // Finish and return all errors
/// errors.finish()?;
/// ```
#[allow(dead_code, reason = "API kept for completeness")]
pub trait CollectErrors {
	/// Execute a fallible operation, collecting any errors.
	///
	/// If the operation succeeds, returns `Some(value)`.
	/// If the operation fails, the error is collected and `None` is returned.
	///
	/// # Examples
	///
	/// ```ignore
	/// let mut errors = ErrorCollector::new();
	/// if let Some(sig) = errors.collect(|| parse_signature(&item)) {
	///     // Use sig
	/// }
	/// ```
	fn collect<F, T>(
		&mut self,
		f: F,
	) -> Option<T>
	where
		F: FnOnce() -> syn::Result<T>;

	/// Execute a fallible operation with context, collecting any errors.
	///
	/// If the operation succeeds, returns `Some(value)`.
	/// If the operation fails, the error is wrapped with the provided context
	/// and collected, and `None` is returned.
	///
	/// # Examples
	///
	/// ```ignore
	/// let mut errors = ErrorCollector::new();
	/// if let Some(docs) = errors.collect_with_context("generating docs", || generate_docs(&sig)) {
	///     // Use docs
	/// }
	/// ```
	fn collect_with_context<F, T>(
		&mut self,
		context: &str,
		f: F,
	) -> Option<T>
	where
		F: FnOnce() -> syn::Result<T>;

	/// Execute a fallible operation that returns our custom Error type.
	///
	/// Converts the error to syn::Error before collecting.
	fn collect_our_result<F, T>(
		&mut self,
		f: F,
	) -> Option<T>
	where
		F: FnOnce() -> Result<T>;

	/// Execute a fallible operation with context that returns our custom Error type.
	///
	/// Converts the error to syn::Error and adds context before collecting.
	fn collect_our_result_with_context<F, T>(
		&mut self,
		context: &str,
		f: F,
	) -> Option<T>
	where
		F: FnOnce() -> Result<T>;
}

impl CollectErrors for ErrorCollector {
	fn collect<F, T>(
		&mut self,
		f: F,
	) -> Option<T>
	where
		F: FnOnce() -> syn::Result<T>, {
		match f() {
			Ok(value) => Some(value),
			Err(e) => {
				self.push(e);
				None
			}
		}
	}

	fn collect_with_context<F, T>(
		&mut self,
		context: &str,
		f: F,
	) -> Option<T>
	where
		F: FnOnce() -> syn::Result<T>, {
		match f() {
			Ok(value) => Some(value),
			Err(e) => {
				let contextualized = syn::Error::new(e.span(), format!("{}: {}", context, e));
				self.push(contextualized);
				None
			}
		}
	}

	fn collect_our_result<F, T>(
		&mut self,
		f: F,
	) -> Option<T>
	where
		F: FnOnce() -> Result<T>, {
		match f() {
			Ok(value) => Some(value),
			Err(e) => {
				self.push(e.into());
				None
			}
		}
	}

	fn collect_our_result_with_context<F, T>(
		&mut self,
		context: &str,
		f: F,
	) -> Option<T>
	where
		F: FnOnce() -> Result<T>, {
		match f() {
			Ok(value) => Some(value),
			Err(e) => {
				let syn_err: syn::Error = e.into();
				let contextualized =
					syn::Error::new(syn_err.span(), format!("{}: {}", context, syn_err));
				self.push(contextualized);
				None
			}
		}
	}
}

/// Trait for converting errors to compile-time errors
pub trait ToCompileError {
	fn to_compile_error(self) -> TokenStream;
}

impl ToCompileError for Error {
	fn to_compile_error(self) -> TokenStream {
		let syn_error: syn::Error = self.into();
		syn_error.to_compile_error()
	}
}

#[cfg(test)]
#[expect(clippy::unwrap_used, reason = "Tests use panicking operations for brevity and clarity")]
mod tests {
	use super::*;

	#[test]
	fn test_error_span() {
		let span = Span::call_site();
		let err = Error::validation(span, "test message");
		assert_eq!(format!("{:?}", err.span()), format!("{:?}", span), "Span should be preserved");
	}

	#[test]
	fn test_validation_error() {
		let span = Span::call_site();
		let err = Error::validation(span, "invalid input");
		assert!(err.to_string().contains("invalid input"));
	}

	#[test]
	fn test_validation_error_with_suggestion() {
		let span = Span::call_site();
		let err = Error::validation(span, "invalid input").with_suggestion("try this instead");
		let syn_err: syn::Error = err.into();
		let err_str = syn_err.to_string();
		eprintln!("Error string: '{err_str}'");
		eprintln!("Contains 'invalid input': {}", err_str.contains("invalid input"));
		eprintln!("Contains 'try this instead': {}", err_str.contains("try this instead"));
		assert!(err_str.contains("invalid input"));
		// Note: syn::Error combines multiple errors but doesn't add "help:" prefix
		// The suggestion is included in the combined error message
		assert!(err_str.contains("try this instead"));
	}

	#[test]
	fn test_resolution_error() {
		let span = Span::call_site();
		let err = Error::resolution(span, "cannot resolve", vec!["Type1".to_string()]);
		assert!(err.to_string().contains("cannot resolve"));
	}

	#[test]
	fn test_unsupported_const_generics() {
		let span = Span::call_site();
		let err = UnsupportedFeature::ConstGenerics {
			span,
		};
		assert!(err.to_string().contains("Const generic parameters are not supported"));
	}

	#[test]
	fn test_error_context() {
		let err = Error::internal("original message");
		let err_with_context = err.context("while processing");
		assert!(err_with_context.to_string().contains("while processing: original message"));
	}

	#[test]
	fn test_syn_error_conversion() {
		let span = Span::call_site();
		let err = Error::validation(span, "test error");
		let syn_err: syn::Error = err.into();
		assert!(syn_err.to_string().contains("test error"));
	}

	#[test]
	fn test_resolution_error_with_available_types() {
		let span = Span::call_site();
		let err = Error::resolution(
			span,
			"cannot find type",
			vec!["String".to_string(), "Vec".to_string()],
		);
		let syn_err: syn::Error = err.into();
		let err_string = syn_err.to_string();
		assert!(err_string.contains("cannot find type"));
		// The "available alternatives" note is combined as a separate error
	}

	// Tests for CollectErrors trait
	#[test]
	fn test_collect_success() {
		let mut errors = ErrorCollector::new();
		let result = errors.collect(|| Ok::<_, syn::Error>(42));
		assert_eq!(result, Some(42));
		assert!(errors.is_empty());
	}

	#[test]
	fn test_collect_error() {
		let mut errors = ErrorCollector::new();
		let result =
			errors.collect(|| Err::<i32, _>(syn::Error::new(Span::call_site(), "test error")));
		assert_eq!(result, None);
		assert_eq!(errors.len(), 1);
	}

	#[test]
	fn test_collect_with_context() {
		let mut errors = ErrorCollector::new();
		let result = errors.collect_with_context("parsing", || {
			Err::<i32, _>(syn::Error::new(Span::call_site(), "failed"))
		});
		assert_eq!(result, None);
		assert_eq!(errors.len(), 1);
		let combined_err = errors.finish().unwrap_err();
		assert!(combined_err.to_string().contains("parsing"));
		assert!(combined_err.to_string().contains("failed"));
	}

	#[test]
	fn test_collect_our_result() {
		let mut errors = ErrorCollector::new();
		let result = errors.collect_our_result(|| Ok::<_, Error>(100));
		assert_eq!(result, Some(100));
		assert!(errors.is_empty());
	}

	#[test]
	fn test_collect_our_result_error() {
		let mut errors = ErrorCollector::new();
		let result = errors.collect_our_result(|| {
			Err::<i32, _>(Error::validation(Span::call_site(), "validation failed"))
		});
		assert_eq!(result, None);
		assert_eq!(errors.len(), 1);
	}

	#[test]
	fn test_collect_our_result_with_context() {
		let mut errors = ErrorCollector::new();
		let result = errors.collect_our_result_with_context("in function", || {
			Err::<i32, _>(Error::validation(Span::call_site(), "bad value"))
		});
		assert_eq!(result, None);
		assert_eq!(errors.len(), 1);
		let combined_err = errors.finish().unwrap_err();
		assert!(combined_err.to_string().contains("in function"));
		assert!(combined_err.to_string().contains("bad value"));
	}

	#[test]
	fn test_multiple_collects() {
		let mut errors = ErrorCollector::new();

		let r1 = errors.collect(|| Ok::<_, syn::Error>(1));
		let r2 = errors.collect(|| Err::<i32, _>(syn::Error::new(Span::call_site(), "error 1")));
		let r3 = errors.collect(|| Ok::<_, syn::Error>(3));
		let r4 = errors.collect(|| Err::<i32, _>(syn::Error::new(Span::call_site(), "error 2")));

		assert_eq!(r1, Some(1));
		assert_eq!(r2, None);
		assert_eq!(r3, Some(3));
		assert_eq!(r4, None);
		assert_eq!(errors.len(), 2);

		let combined_err = errors.finish().unwrap_err();
		// syn::Error::combine() combines errors for to_compile_error() output
		// to_string() only shows the first error, so we check to_compile_error() instead
		let compile_err_str = combined_err.to_compile_error().to_string();
		assert!(compile_err_str.contains("error 1"));
		assert!(compile_err_str.contains("error 2"));
	}

	#[test]
	fn test_error_collector_methods() {
		let mut errors = ErrorCollector::new();
		assert!(errors.is_empty());
		assert!(!errors.has_errors());
		assert_eq!(errors.len(), 0);

		errors.push(syn::Error::new(Span::call_site(), "error 1"));
		assert!(!errors.is_empty());
		assert!(errors.has_errors());
		assert_eq!(errors.len(), 1);

		errors.push(syn::Error::new(Span::call_site(), "error 2"));
		assert_eq!(errors.len(), 2);
	}

	#[test]
	fn test_to_compile_error() {
		let err = Error::validation(Span::call_site(), "test error");
		let token_stream = err.to_compile_error();
		let output = token_stream.to_string();
		assert!(!output.is_empty());
	}
}