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
//! Parsing for the `m_do!` macro input.
//!
//! Defines `DoInput` and `DoStatement` types and their `Parse` implementations.

use {
	proc_macro2::TokenTree,
	syn::{
		Expr,
		Pat,
		Token,
		Type,
		braced,
		parse::{
			Parse,
			ParseStream,
			discouraged::Speculative,
		},
	},
};

/// The parsed input to the `m_do!` macro.
///
/// Represents `[ref] [Brand] { statements... final_expr }`.
///
/// In explicit mode, `brand` is `Some(Brand)` and the macro generates
/// `explicit::bind::<Brand, ...>` calls. In inferred mode (brand omitted),
/// `brand` is `None` and the macro generates inference-based `bind` calls.
pub struct DoInput {
	/// Whether the `ref` qualifier is present, selecting by-reference dispatch.
	pub ref_mode: bool,
	/// The brand type, or `None` for inferred mode.
	pub brand: Option<Type>,
	/// The statements preceding the final expression.
	pub statements: Vec<DoStatement>,
	/// The final expression (returned as-is, no trailing `;`).
	pub final_expr: Expr,
}

/// A single statement in a `m_do!` block.
pub enum DoStatement {
	/// `pat <- expr;` or `pat: Type <- expr;` -- monadic bind.
	Bind {
		/// The binding pattern.
		pattern: Pat,
		/// Optional type annotation.
		ty: Option<Type>,
		/// The monadic expression to bind.
		expr: Expr,
	},
	/// `let pat = expr;` or `let pat: Type = expr;` -- pure let binding.
	Let {
		/// The binding pattern.
		pattern: Pat,
		/// Optional type annotation.
		ty: Option<Type>,
		/// The expression to bind.
		expr: Expr,
	},
	/// `expr;` -- monadic sequence (result discarded).
	Sequence {
		/// The monadic expression to sequence.
		expr: Expr,
	},
}

impl Parse for DoInput {
	fn parse(input: ParseStream) -> syn::Result<Self> {
		let ref_mode = input.peek(Token![ref]);
		if ref_mode {
			input.parse::<Token![ref]>()?;
		}

		// Inferred mode: `{ ... }` or `ref { ... }` (no brand before brace)
		// Explicit mode: `Brand { ... }` or `ref Brand { ... }`
		let brand: Option<Type> =
			if input.peek(syn::token::Brace) { None } else { Some(input.parse()?) };

		let content;
		braced!(content in input);

		let mut statements = Vec::new();

		loop {
			if content.is_empty() {
				return Err(content.error("m_do! block must contain at least one expression"));
			}

			// `let` binding
			if content.peek(Token![let]) {
				statements.push(parse_let_statement(&content)?);
				continue;
			}

			// Try bind: `pat: Type <- expr;` then `pat <- expr;`
			if let Some(bind) = try_parse_bind(&content)? {
				statements.push(bind);
				continue;
			}

			// Expression (sequence or final)
			let expr: Expr = content.parse()?;

			if content.peek(Token![;]) {
				content.parse::<Token![;]>()?;
				statements.push(DoStatement::Sequence {
					expr,
				});
				continue;
			}

			// Final expression
			if !content.is_empty() {
				return Err(syn::Error::new_spanned(
					&expr,
					"expected `;` after statement or end of block",
				));
			}

			return Ok(DoInput {
				ref_mode,
				brand,
				statements,
				final_expr: expr,
			});
		}
	}
}

/// Parses `let pat = expr;` or `let pat: Type = expr;`.
fn parse_let_statement(input: ParseStream) -> syn::Result<DoStatement> {
	input.parse::<Token![let]>()?;
	let pattern = Pat::parse_single(input)?;

	// Type annotation is part of let syntax, not the pattern
	let ty = if input.peek(Token![:]) {
		input.parse::<Token![:]>()?;
		Some(input.parse::<Type>()?)
	} else {
		None
	};

	input.parse::<Token![=]>()?;
	let expr: Expr = input.parse()?;
	input.parse::<Token![;]>()?;

	Ok(DoStatement::Let {
		pattern,
		ty,
		expr,
	})
}

/// Speculatively tries to parse `pat <- expr;` or `pat: Type <- expr;`.
///
/// Returns `Ok(None)` if the current position doesn't match bind syntax.
/// Tries typed bind first, then falls back to simple bind.
fn try_parse_bind(input: ParseStream) -> syn::Result<Option<DoStatement>> {
	// Try typed bind: `pat: Type <- expr;`
	if let Some(bind) = try_parse_typed_bind(input)? {
		return Ok(Some(bind));
	}

	// Try simple bind: `pat <- expr;`
	try_parse_simple_bind(input)
}

/// Tries to parse `pat: Type <- expr;`.
///
/// Uses token-level scanning to find `<-` because `Type::parse` would greedily
/// consume the `<` as the start of generic arguments for types like `i32`.
/// The key insight is that `<-` never appears in valid Rust type syntax.
fn try_parse_typed_bind(input: ParseStream) -> syn::Result<Option<DoStatement>> {
	let fork = input.fork();

	let pattern = match fork.call(Pat::parse_single) {
		Ok(pat) => pat,
		Err(_) => return Ok(None),
	};

	if !fork.peek(Token![:]) || fork.peek(Token![::]) {
		return Ok(None);
	}
	fork.parse::<Token![:]>()?;

	// Collect type tokens until we find `<-`.
	// `<-` (less-than immediately followed by minus) never appears in valid Rust
	// type syntax, so the first occurrence marks the bind arrow boundary.
	let ty = match collect_type_before_arrow(&fork) {
		Some(ty) => ty,
		None => return Ok(None),
	};

	// Parse `<-`
	if fork.parse::<Token![<]>().is_err() || fork.parse::<Token![-]>().is_err() {
		return Ok(None);
	}

	let expr: Expr = fork.parse()?;
	fork.parse::<Token![;]>()?;
	input.advance_to(&fork);

	Ok(Some(DoStatement::Bind {
		pattern,
		ty: Some(ty),
		expr,
	}))
}

/// Tries to parse `pat <- expr;`.
fn try_parse_simple_bind(input: ParseStream) -> syn::Result<Option<DoStatement>> {
	let fork = input.fork();

	let pattern = match fork.call(Pat::parse_single) {
		Ok(pat) => pat,
		Err(_) => return Ok(None),
	};

	// Check for `<-` (two separate punct tokens)
	if !fork.peek(Token![<]) {
		return Ok(None);
	}
	fork.parse::<Token![<]>()?;

	if !fork.peek(Token![-]) {
		return Ok(None);
	}
	fork.parse::<Token![-]>()?;

	// Committed to bind
	let expr: Expr = fork.parse()?;
	fork.parse::<Token![;]>()?;
	input.advance_to(&fork);

	Ok(Some(DoStatement::Bind {
		pattern,
		ty: None,
		expr,
	}))
}

/// Collects tokens from the stream until `<-` is found, then parses them as a `Type`.
///
/// Returns `None` if no `<-` is found or the collected tokens don't form a valid type.
/// Advances the input past the collected type tokens on success.
fn collect_type_before_arrow(input: ParseStream) -> Option<Type> {
	let fork = input.fork();
	let mut tokens = proc_macro2::TokenStream::new();

	while !fork.is_empty() {
		// `<-` never appears in valid Rust type syntax, so the first
		// `<` immediately followed by `-` is always the bind arrow.
		if fork.peek(Token![<]) {
			let check = fork.fork();
			let _ = check.parse::<Token![<]>().ok()?;
			if check.peek(Token![-]) {
				break;
			}
		}

		let tt: TokenTree = fork.parse().ok()?;
		tokens.extend(std::iter::once(tt));
	}

	if tokens.is_empty() {
		return None;
	}

	let ty: Type = syn::parse2(tokens).ok()?;
	input.advance_to(&fork);
	Some(ty)
}

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

	#[test]
	fn parse_basic_bind() {
		let input: DoInput = parse_str(
			"OptionBrand {
				x <- Some(5);
				pure(x)
			}",
		)
		.expect("failed to parse");

		assert!(matches!(input.statements[0], DoStatement::Bind { .. }));
		assert_eq!(input.statements.len(), 1);
	}

	#[test]
	fn parse_let_binding() {
		let input: DoInput = parse_str(
			"OptionBrand {
				let z = 42;
				pure(z)
			}",
		)
		.expect("failed to parse");

		assert!(matches!(input.statements[0], DoStatement::Let { .. }));
	}

	#[test]
	fn parse_sequence() {
		let input: DoInput = parse_str(
			"OptionBrand {
				Some(());
				pure(5)
			}",
		)
		.expect("failed to parse");

		assert!(matches!(input.statements[0], DoStatement::Sequence { .. }));
	}

	#[test]
	fn parse_typed_bind() {
		let input: DoInput = parse_str(
			"OptionBrand {
				x: i32 <- Some(5);
				pure(x)
			}",
		)
		.expect("failed to parse");

		if let DoStatement::Bind {
			ty, ..
		} = &input.statements[0]
		{
			assert!(ty.is_some());
		} else {
			panic!("expected Bind");
		}
	}

	#[test]
	fn parse_typed_bind_generic() {
		let input: DoInput = parse_str(
			"OptionBrand {
				x: Vec<i32> <- Some(vec![1]);
				pure(x)
			}",
		)
		.expect("failed to parse");

		if let DoStatement::Bind {
			ty, ..
		} = &input.statements[0]
		{
			assert!(ty.is_some());
		} else {
			panic!("expected Bind");
		}
	}

	#[test]
	fn parse_discard_bind() {
		let input: DoInput = parse_str(
			"OptionBrand {
				_ <- Some(());
				pure(5)
			}",
		)
		.expect("failed to parse");

		assert!(matches!(input.statements[0], DoStatement::Bind { .. }));
	}

	#[test]
	fn parse_only_final_expr() {
		let input: DoInput = parse_str(
			"OptionBrand {
				pure(42)
			}",
		)
		.expect("failed to parse");

		assert!(input.statements.is_empty());
	}

	#[test]
	fn parse_multiple_statements() {
		let input: DoInput = parse_str(
			"OptionBrand {
				x <- Some(5);
				y <- Some(x + 1);
				let z = x * y;
				Some(());
				pure(z)
			}",
		)
		.expect("failed to parse");

		assert_eq!(input.statements.len(), 4);
		assert!(matches!(input.statements[0], DoStatement::Bind { .. }));
		assert!(matches!(input.statements[1], DoStatement::Bind { .. }));
		assert!(matches!(input.statements[2], DoStatement::Let { .. }));
		assert!(matches!(input.statements[3], DoStatement::Sequence { .. }));
	}

	#[test]
	fn parse_empty_block_fails() {
		let result = parse_str::<DoInput>("OptionBrand {}");
		assert!(result.is_err());
	}

	#[test]
	fn parse_ref_mode() {
		let input: DoInput = parse_str(
			"ref OptionBrand {
				x <- Some(5);
				pure(x)
			}",
		)
		.expect("failed to parse");

		assert!(input.ref_mode);
		assert!(matches!(input.statements[0], DoStatement::Bind { .. }));
	}

	#[test]
	fn parse_non_ref_mode() {
		let input: DoInput = parse_str(
			"OptionBrand {
				x <- Some(5);
				pure(x)
			}",
		)
		.expect("failed to parse");

		assert!(!input.ref_mode);
		assert!(input.brand.is_some());
	}

	#[test]
	fn parse_inferred_mode() {
		let input: DoInput = parse_str(
			"{
				x <- Some(5);
				Some(x + 1)
			}",
		)
		.expect("failed to parse");

		assert!(!input.ref_mode);
		assert!(input.brand.is_none());
		assert_eq!(input.statements.len(), 1);
		assert!(matches!(input.statements[0], DoStatement::Bind { .. }));
	}

	#[test]
	fn parse_inferred_ref_mode() {
		let input: DoInput = parse_str(
			"ref {
				x <- Some(5);
				Some(x + 1)
			}",
		)
		.expect("failed to parse");

		assert!(input.ref_mode);
		assert!(input.brand.is_none());
	}
}