xdy 0.10.0

Complex RPG dice expression evaluator with histogram support.
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
//! # Source span position test cases
//!
//! Herein are the test cases that verify the source-span positions computed
//! by the parser for every AST node, including primary and dice expressions,
//! arithmetic operators, function and parameter nodes, [`Spanned::span`]
//! variant dispatch, and [`Spanned::untethered`] normalisation.

use crate::{
	ast::*,
	parser::*,
	span::{SourceSpan, Spanned}
};
use pretty_assertions::assert_eq;

////////////////////////////////////////////////////////////////////////////////
//                        Source span position tests.                         //
////////////////////////////////////////////////////////////////////////////////

/// Shorthand for building a [`SourceSpan`] from a pair of offsets.
fn span(start: usize, end: usize) -> SourceSpan { SourceSpan { start, end } }

////////////////////////////////////////////////////////////////////////////////
//                         Primary-expression spans.                          //
////////////////////////////////////////////////////////////////////////////////

/// A [`Constant`]'s span covers exactly its numeric literal.
#[test]
fn test_constant_span()
{
	let (_, result) = constant(Span::new("42")).unwrap();
	assert_eq!(result.span, span(0, 2));
}

/// A negative numeric literal parses directly to a [`Constant`] with a negative
/// value (rather than a [`Neg`] wrapping a positive [`Constant`]), so that
/// `i32::MIN` is representable. The span covers the leading `-` as well as the
/// digits.
#[test]
fn test_negative_constant_span()
{
	let (_, result) = expression(Span::new("-123")).unwrap();
	assert_eq!(result.span(), span(0, 4));
	match result
	{
		Expression::Constant(c) =>
		{
			assert_eq!(c.value, -123);
			assert_eq!(c.span, span(0, 4));
		},
		other => panic!("expected Constant, got {:?}", other)
	}
}

/// A [`Variable`]'s span includes the surrounding braces.
#[test]
fn test_variable_span_includes_braces()
{
	let (_, result) = variable(Span::new("{abc}")).unwrap();
	assert_eq!(result.name, "abc");
	assert_eq!(result.span, span(0, 5));
}

/// A [`Variable`] embedded in a larger expression preserves its brace-inclusive
/// span, and the enclosing binary op takes its span from its children.
#[test]
fn test_variable_span_inside_expression()
{
	let (_, result) = expression(Span::new("{x} + 1")).unwrap();
	match result
	{
		Expression::Arithmetic(ArithmeticExpression::Add(add)) =>
		{
			assert_eq!(add.span, span(0, 7));
			match add.left.as_ref()
			{
				Expression::Variable(v) => assert_eq!(v.span, span(0, 3)),
				other => panic!("expected Variable, got {:?}", other)
			}
		},
		other => panic!("expected Add, got {:?}", other)
	}
}

/// A [`Range`]'s span includes both `[` and `]`; the endpoint expressions'
/// spans do not.
#[test]
fn test_range_span_includes_brackets()
{
	let (_, result) = range(Span::new("[1:20]")).unwrap();
	assert_eq!(result.span, span(0, 6));
	assert_eq!(result.start.span(), span(1, 2));
	assert_eq!(result.end.span(), span(3, 5));
}

/// A [`Group`]'s span includes its delimiters; the inner expression's span does
/// not.
#[test]
fn test_group_span_includes_delimiters()
{
	let (_, result) = expression(Span::new("(1 + 2)")).unwrap();
	match result
	{
		Expression::Group(group) =>
		{
			assert_eq!(group.span, span(0, 7));
			assert_eq!(group.expression.span(), span(1, 6));
		},
		other => panic!("expected Group, got {:?}", other)
	}
}

/// Nested [`Group`]s each carry their own brace-inclusive span.
#[test]
fn test_nested_group_spans()
{
	let (_, result) = expression(Span::new("((1+2))")).unwrap();
	match result
	{
		Expression::Group(outer) =>
		{
			assert_eq!(outer.span, span(0, 7));
			match outer.expression.as_ref()
			{
				Expression::Group(inner) =>
				{
					assert_eq!(inner.span, span(1, 6));
					assert_eq!(inner.expression.span(), span(2, 5));
				},
				other => panic!("expected inner Group, got {:?}", other)
			}
		},
		other => panic!("expected outer Group, got {:?}", other)
	}
}

////////////////////////////////////////////////////////////////////////////////
//                           Dice-expression spans.                           //
////////////////////////////////////////////////////////////////////////////////

/// A bare [`StandardDice`]'s span covers the count, the `d`/`D` operator, and
/// the face count — exactly the source text of the dice expression.
#[test]
fn test_standard_dice_span()
{
	let (_, result) = dice(Span::new("3D6")).unwrap();
	match result
	{
		DiceExpression::Standard(sd) =>
		{
			assert_eq!(sd.span, span(0, 3));
			assert_eq!(sd.count.span(), span(0, 1));
			assert_eq!(sd.faces.span(), span(2, 3));
		},
		other => panic!("expected Standard, got {:?}", other)
	}
}

/// A [`StandardDice`] with variable count and variable faces takes its span
/// from the start of the count through the closing brace of the faces.
#[test]
fn test_standard_dice_with_variable_operands_span()
{
	let (_, result) = dice(Span::new("{x}D{y}")).unwrap();
	match result
	{
		DiceExpression::Standard(sd) =>
		{
			assert_eq!(sd.span, span(0, 7));
			assert_eq!(sd.count.span(), span(0, 3));
			assert_eq!(sd.faces.span(), span(4, 7));
		},
		other => panic!("expected Standard, got {:?}", other)
	}
}

/// A [`StandardDice`] with a parenthesized count takes its span from the
/// opening `(` of the group through the end of the faces.
#[test]
fn test_standard_dice_with_group_count_span()
{
	let (_, result) = dice(Span::new("(1+2)D6")).unwrap();
	match result
	{
		DiceExpression::Standard(sd) =>
		{
			assert_eq!(sd.span, span(0, 7));
			assert_eq!(sd.count.span(), span(0, 5));
			assert_eq!(sd.faces.span(), span(6, 7));
		},
		other => panic!("expected Standard, got {:?}", other)
	}
}

/// A [`CustomDice`]'s span starts at the count and extends through the closing
/// `]` of the face list.
#[test]
fn test_custom_dice_span()
{
	let (_, result) = dice(Span::new("2D[1,2,3]")).unwrap();
	match result
	{
		DiceExpression::Custom(cd) =>
		{
			assert_eq!(cd.span, span(0, 9));
			assert_eq!(cd.count.span(), span(0, 1));
			assert_eq!(cd.faces, vec![1, 2, 3]);
		},
		other => panic!("expected Custom, got {:?}", other)
	}
}

/// A [`CustomDice`] with negative face values still covers through the closing
/// `]`; face values do not have their own spans but are recorded verbatim.
#[test]
fn test_custom_dice_with_negative_faces_span()
{
	let (_, result) = dice(Span::new("3D[-1,0,1]")).unwrap();
	match result
	{
		DiceExpression::Custom(cd) =>
		{
			assert_eq!(cd.span, span(0, 10));
			assert_eq!(cd.faces, vec![-1, 0, 1]);
		},
		other => panic!("expected Custom, got {:?}", other)
	}
}

/// A [`DropLowest`]'s span extends from the start of the inner dice to the end
/// of the drop clause. The inner [`StandardDice`]'s own span covers only the
/// dice, not the drop clause.
#[test]
fn test_drop_lowest_no_count_span()
{
	let (_, result) = dice(Span::new("3d6 drop lowest")).unwrap();
	match result
	{
		DiceExpression::DropLowest(drop) =>
		{
			assert_eq!(drop.span, span(0, 15));
			match drop.dice.as_ref()
			{
				DiceExpression::Standard(std_dice) =>
				{
					assert_eq!(std_dice.span, span(0, 3));
				},
				other => panic!("expected StandardDice, got {:?}", other)
			}
			assert!(drop.drop.is_none());
		},
		other => panic!("expected DropLowest, got {:?}", other)
	}
}

/// A [`DropLowest`] with an explicit drop count extends its span through that
/// drop count, while the inner dice retains its pre-clause span.
#[test]
fn test_drop_lowest_with_count_span()
{
	let (_, result) = dice(Span::new("4D6 drop lowest 2")).unwrap();
	match result
	{
		DiceExpression::DropLowest(drop) =>
		{
			assert_eq!(drop.span, span(0, 17));
			assert_eq!(drop.dice.span(), span(0, 3));
			assert_eq!(
				drop.drop.as_ref().expect("drop count").span(),
				span(16, 17)
			);
		},
		other => panic!("expected DropLowest, got {:?}", other)
	}
}

/// A [`DropHighest`] without an explicit drop count carries a span extending
/// through the `highest` keyword.
#[test]
fn test_drop_highest_no_count_span()
{
	let (_, result) = dice(Span::new("4D6 drop highest")).unwrap();
	match result
	{
		DiceExpression::DropHighest(drop) =>
		{
			assert_eq!(drop.span, span(0, 16));
			assert_eq!(drop.dice.span(), span(0, 3));
			assert!(drop.drop.is_none());
		},
		other => panic!("expected DropHighest, got {:?}", other)
	}
}

/// A [`DropHighest`] with an explicit drop count extends its span through that
/// drop count.
#[test]
fn test_drop_highest_with_count_span()
{
	let (_, result) = dice(Span::new("4D6 drop highest 1")).unwrap();
	match result
	{
		DiceExpression::DropHighest(drop) =>
		{
			assert_eq!(drop.span, span(0, 18));
			assert_eq!(drop.dice.span(), span(0, 3));
			assert_eq!(
				drop.drop.as_ref().expect("drop count").span(),
				span(17, 18)
			);
		},
		other => panic!("expected DropHighest, got {:?}", other)
	}
}

/// Stacked drop clauses produce nested wrappers, each with a span extending
/// through its own clause; inner wrappers keep the pre-outer-clause span.
#[test]
fn test_stacked_drop_clauses_span()
{
	let (_, result) =
		dice(Span::new("8D6 drop lowest 3 drop highest 1")).unwrap();
	match result
	{
		DiceExpression::DropHighest(outer) =>
		{
			assert_eq!(outer.span, span(0, 32));
			match outer.dice.as_ref()
			{
				DiceExpression::DropLowest(inner) =>
				{
					assert_eq!(inner.span, span(0, 17));
					assert_eq!(inner.dice.span(), span(0, 3));
				},
				other => panic!("expected inner DropLowest, got {:?}", other)
			}
		},
		other => panic!("expected outer DropHighest, got {:?}", other)
	}
}

////////////////////////////////////////////////////////////////////////////////
//                        Arithmetic-expression spans.                        //
////////////////////////////////////////////////////////////////////////////////

/// A binary [`Add`] derives its span from its children: start of `left` through
/// end of `right`. Whitespace inside the expression is *included* (because
/// `right.span().end` is past the last operand character), but whitespace
/// *outside* the binary op is not.
#[test]
fn test_add_span_from_children()
{
	let (_, result) = expression(Span::new("1 + 22")).unwrap();
	assert_eq!(result.span(), span(0, 6));
	match result
	{
		Expression::Arithmetic(ArithmeticExpression::Add(add)) =>
		{
			assert_eq!(add.left.span(), span(0, 1));
			assert_eq!(add.right.span(), span(4, 6));
			assert_eq!(add.span, span(0, 6));
		},
		other => panic!("expected Add, got {:?}", other)
	}
}

/// A binary [`Sub`] takes its span from its operands.
#[test]
fn test_sub_span_from_children()
{
	let (_, result) = expression(Span::new("10 - 3")).unwrap();
	match result
	{
		Expression::Arithmetic(ArithmeticExpression::Sub(sub)) =>
		{
			assert_eq!(sub.span, span(0, 6));
			assert_eq!(sub.left.span(), span(0, 2));
			assert_eq!(sub.right.span(), span(5, 6));
		},
		other => panic!("expected Sub, got {:?}", other)
	}
}

/// A binary [`Mul`] takes its span from its operands.
#[test]
fn test_mul_span_from_children()
{
	let (_, result) = expression(Span::new("2 * 3")).unwrap();
	match result
	{
		Expression::Arithmetic(ArithmeticExpression::Mul(mul)) =>
		{
			assert_eq!(mul.span, span(0, 5));
			assert_eq!(mul.left.span(), span(0, 1));
			assert_eq!(mul.right.span(), span(4, 5));
		},
		other => panic!("expected Mul, got {:?}", other)
	}
}

/// A binary [`Div`] takes its span from its operands.
#[test]
fn test_div_span_from_children()
{
	let (_, result) = expression(Span::new("10 / 2")).unwrap();
	match result
	{
		Expression::Arithmetic(ArithmeticExpression::Div(div)) =>
		{
			assert_eq!(div.span, span(0, 6));
			assert_eq!(div.left.span(), span(0, 2));
			assert_eq!(div.right.span(), span(5, 6));
		},
		other => panic!("expected Div, got {:?}", other)
	}
}

/// A binary [`Mod`] takes its span from its operands.
#[test]
fn test_mod_span_from_children()
{
	let (_, result) = expression(Span::new("10 % 3")).unwrap();
	match result
	{
		Expression::Arithmetic(ArithmeticExpression::Mod(r#mod)) =>
		{
			assert_eq!(r#mod.span, span(0, 6));
			assert_eq!(r#mod.left.span(), span(0, 2));
			assert_eq!(r#mod.right.span(), span(5, 6));
		},
		other => panic!("expected Mod, got {:?}", other)
	}
}

/// A binary [`Exp`] takes its span from its operands.
#[test]
fn test_exp_span_from_children()
{
	let (_, result) = expression(Span::new("2 ^ 10")).unwrap();
	match result
	{
		Expression::Arithmetic(ArithmeticExpression::Exp(exp)) =>
		{
			assert_eq!(exp.span, span(0, 6));
			assert_eq!(exp.left.span(), span(0, 1));
			assert_eq!(exp.right.span(), span(4, 6));
		},
		other => panic!("expected Exp, got {:?}", other)
	}
}

/// Exponentiation is right-associative: `2^3^2` parses as `2 ^ (3 ^ 2)`. The
/// outer [`Exp`] covers the whole expression; the inner [`Exp`] is the right
/// child and carries the trailing sub-span.
#[test]
fn test_exp_right_associative_span()
{
	let (_, result) = expression(Span::new("2^3^2")).unwrap();
	match result
	{
		Expression::Arithmetic(ArithmeticExpression::Exp(outer)) =>
		{
			assert_eq!(outer.span, span(0, 5));
			assert_eq!(outer.left.span(), span(0, 1));
			match outer.right.as_ref()
			{
				Expression::Arithmetic(ArithmeticExpression::Exp(inner)) =>
				{
					assert_eq!(inner.span, span(2, 5));
					assert_eq!(inner.left.span(), span(2, 3));
					assert_eq!(inner.right.span(), span(4, 5));
				},
				other => panic!("expected inner Exp, got {:?}", other)
			}
		},
		other => panic!("expected outer Exp, got {:?}", other)
	}
}

/// A [`Neg`] of a variable takes its span from the leading `-` through the
/// closing brace of the variable.
#[test]
fn test_neg_of_variable_span()
{
	let (_, result) = expression(Span::new("-{x}")).unwrap();
	match result
	{
		Expression::Arithmetic(ArithmeticExpression::Neg(neg)) =>
		{
			assert_eq!(neg.span, span(0, 4));
			assert_eq!(neg.operand.span(), span(1, 4));
		},
		other => panic!("expected Neg, got {:?}", other)
	}
}

/// A [`Neg`] of a parenthesized expression takes its span from the leading `-`
/// through the closing `)` of the group.
#[test]
fn test_neg_of_group_span()
{
	let (_, result) = expression(Span::new("-(1+2)")).unwrap();
	match result
	{
		Expression::Arithmetic(ArithmeticExpression::Neg(neg)) =>
		{
			assert_eq!(neg.span, span(0, 6));
			assert_eq!(neg.operand.span(), span(1, 6));
		},
		other => panic!("expected Neg, got {:?}", other)
	}
}

/// Double-negation (`-` applied to a negative constant) produces a [`Neg`]
/// wrapping a [`Constant`]. The outer [`Neg`] begins at the leading `-` and
/// extends through the constant.
#[test]
fn test_neg_of_negative_constant_span()
{
	let (_, result) = expression(Span::new("- -1")).unwrap();
	match result
	{
		Expression::Arithmetic(ArithmeticExpression::Neg(neg)) =>
		{
			assert_eq!(neg.span, span(0, 4));
			match neg.operand.as_ref()
			{
				Expression::Constant(c) =>
				{
					assert_eq!(c.value, -1);
					assert_eq!(c.span, span(2, 4));
				},
				other => panic!("expected Constant, got {:?}", other)
			}
		},
		other => panic!("expected outer Neg, got {:?}", other)
	}
}

/// A [`Neg`] of a dice expression (`-3D6`) takes its span from the leading `-`
/// through the end of the dice, using the general negation path because
/// [`negative_constant`] bails when followed by `d`/`D`.
#[test]
fn test_neg_of_dice_span()
{
	let (_, result) = expression(Span::new("-3D6")).unwrap();
	match result
	{
		Expression::Arithmetic(ArithmeticExpression::Neg(neg)) =>
		{
			assert_eq!(neg.span, span(0, 4));
			match neg.operand.as_ref()
			{
				Expression::Dice(DiceExpression::Standard(sd)) =>
				{
					assert_eq!(sd.span, span(1, 4));
				},
				other => panic!("expected StandardDice, got {:?}", other)
			}
		},
		other => panic!("expected Neg, got {:?}", other)
	}
}

////////////////////////////////////////////////////////////////////////////////
//                       Function and parameter spans.                        //
////////////////////////////////////////////////////////////////////////////////

/// Each [`Parameter`] carries the span of its identifier, and the enclosing
/// [`Function`] covers the whole source.
#[test]
fn test_parameter_and_function_spans()
{
	let source = "x, y: 1";
	let (_, result) = function(Span::new(source)).unwrap();
	assert_eq!(result.span, span(0, 7));
	let parameters = result.parameters.as_ref().unwrap();
	assert_eq!(parameters[0].span, span(0, 1));
	assert_eq!(parameters[1].span, span(3, 4));
	assert_eq!(result.body.span(), span(6, 7));
}

/// A [`Function`] with no parameters has its span anchored at the start of the
/// body.
#[test]
fn test_function_no_parameters_span()
{
	let (_, result) = function(Span::new("42")).unwrap();
	assert!(result.parameters.is_none());
	assert_eq!(result.span, span(0, 2));
	assert_eq!(result.body.span(), span(0, 2));
}

/// [`Parameter`] spans cover only the identifier, not surrounding whitespace or
/// separators, regardless of how much whitespace the source contains.
#[test]
fn test_parameter_span_excludes_whitespace()
{
	let source = "  abc  ,  def  : 1";
	let (_, result) = function(Span::new(source)).unwrap();
	let parameters = result.parameters.as_ref().unwrap();
	assert_eq!(parameters[0].name, "abc");
	assert_eq!(parameters[0].span, span(2, 5));
	assert_eq!(parameters[1].name, "def");
	assert_eq!(parameters[1].span, span(10, 13));
}

/// [`Parser::parse`] strips leading whitespace before invoking [`function`], so
/// the resulting [`Function`] span begins at the first non-whitespace byte.
/// Trailing whitespace is stripped outside the body, so the span end matches
/// the body end.
#[test]
fn test_parser_parse_strips_outer_whitespace_from_function_span()
{
	let ast = Parser::parse("  1D6   ").unwrap();
	assert_eq!(ast.span, span(2, 5));
	assert_eq!(ast.body.span(), span(2, 5));
}

////////////////////////////////////////////////////////////////////////////////
//                          Spanned::span dispatch.                           //
////////////////////////////////////////////////////////////////////////////////

/// [`Expression::span`] dispatches to the active variant, returning the same
/// span as the contained node would.
#[test]
fn test_expression_span_dispatches_to_variant()
{
	// Group.
	let group = expression(Span::new("(1)")).unwrap().1;
	assert_eq!(group.span(), span(0, 3));
	assert!(matches!(group, Expression::Group(_)));

	// Constant.
	let constant_expr = expression(Span::new("7")).unwrap().1;
	assert_eq!(constant_expr.span(), span(0, 1));
	assert!(matches!(constant_expr, Expression::Constant(_)));

	// Variable.
	let variable_expr = expression(Span::new("{x}")).unwrap().1;
	assert_eq!(variable_expr.span(), span(0, 3));
	assert!(matches!(variable_expr, Expression::Variable(_)));

	// Range.
	let range_expr = expression(Span::new("[1:6]")).unwrap().1;
	assert_eq!(range_expr.span(), span(0, 5));
	assert!(matches!(range_expr, Expression::Range(_)));

	// Binding.
	let binding_expr = expression(Span::new("x@(3D6)")).unwrap().1;
	assert_eq!(binding_expr.span(), span(0, 7));
	assert!(matches!(binding_expr, Expression::Binding(_)));

	// Dice.
	let dice_expr = expression(Span::new("2D8")).unwrap().1;
	assert_eq!(dice_expr.span(), span(0, 3));
	assert!(matches!(dice_expr, Expression::Dice(_)));

	// Arithmetic.
	let arith_expr = expression(Span::new("1+2")).unwrap().1;
	assert_eq!(arith_expr.span(), span(0, 3));
	assert!(matches!(arith_expr, Expression::Arithmetic(_)));
}

/// [`DiceExpression::span`] dispatches to the active variant.
#[test]
fn test_dice_expression_span_dispatches_to_variant()
{
	let standard = dice(Span::new("2D8")).unwrap().1;
	assert_eq!(standard.span(), span(0, 3));
	assert!(matches!(standard, DiceExpression::Standard(_)));

	let custom = dice(Span::new("2D[1,2]")).unwrap().1;
	assert_eq!(custom.span(), span(0, 7));
	assert!(matches!(custom, DiceExpression::Custom(_)));

	let drop_lowest = dice(Span::new("4D6 drop lowest")).unwrap().1;
	assert_eq!(drop_lowest.span(), span(0, 15));
	assert!(matches!(drop_lowest, DiceExpression::DropLowest(_)));

	let drop_highest = dice(Span::new("4D6 drop highest")).unwrap().1;
	assert_eq!(drop_highest.span(), span(0, 16));
	assert!(matches!(drop_highest, DiceExpression::DropHighest(_)));
}

/// [`ArithmeticExpression::span`] dispatches to the active variant. The parser
/// produces these only wrapped inside [`Expression::Arithmetic`], so we unwrap
/// once to exercise the inner dispatch.
#[test]
fn test_arithmetic_expression_span_dispatches_to_variant()
{
	fn unwrap_arith(expr: Expression<'_>) -> ArithmeticExpression<'_>
	{
		match expr
		{
			Expression::Arithmetic(a) => a,
			other => panic!("expected Arithmetic, got {:?}", other)
		}
	}

	let add = unwrap_arith(expression(Span::new("1+2")).unwrap().1);
	assert_eq!(add.span(), span(0, 3));
	assert!(matches!(add, ArithmeticExpression::Add(_)));

	let sub = unwrap_arith(expression(Span::new("3-1")).unwrap().1);
	assert_eq!(sub.span(), span(0, 3));
	assert!(matches!(sub, ArithmeticExpression::Sub(_)));

	let mul = unwrap_arith(expression(Span::new("2*3")).unwrap().1);
	assert_eq!(mul.span(), span(0, 3));
	assert!(matches!(mul, ArithmeticExpression::Mul(_)));

	let div = unwrap_arith(expression(Span::new("6/2")).unwrap().1);
	assert_eq!(div.span(), span(0, 3));
	assert!(matches!(div, ArithmeticExpression::Div(_)));

	let r#mod = unwrap_arith(expression(Span::new("7%3")).unwrap().1);
	assert_eq!(r#mod.span(), span(0, 3));
	assert!(matches!(r#mod, ArithmeticExpression::Mod(_)));

	let exp = unwrap_arith(expression(Span::new("2^3")).unwrap().1);
	assert_eq!(exp.span(), span(0, 3));
	assert!(matches!(exp, ArithmeticExpression::Exp(_)));

	let neg = unwrap_arith(expression(Span::new("-{x}")).unwrap().1);
	assert_eq!(neg.span(), span(0, 4));
	assert!(matches!(neg, ArithmeticExpression::Neg(_)));
}

/// [`Function::span`] and [`Parameter::span`] expose the struct field through
/// the [`Spanned`] trait. Other tests access the field directly; this one
/// exercises the trait dispatch specifically.
#[test]
fn test_function_and_parameter_spanned_trait_dispatch()
{
	let ast = Parser::parse("a, b: 1").unwrap();
	// Exercise the trait method, not the struct field.
	assert_eq!(Spanned::span(&ast), span(0, 7));
	let params = ast.parameters.as_ref().unwrap();
	assert_eq!(Spanned::span(&params[0]), span(0, 1));
	assert_eq!(Spanned::span(&params[1]), span(3, 4));
}

////////////////////////////////////////////////////////////////////////////////
//                       Spanned::untethered coverage.                        //
////////////////////////////////////////////////////////////////////////////////

/// [`Spanned::untethered`] zeroes every span in a complex AST — including
/// parameter spans, arithmetic operand spans, dice wrapper spans, and nested
/// variable spans — without altering the structure or identifiers.
#[test]
fn test_untethered_zeroes_all_spans()
{
	let ast = Parser::parse("a, b: {a}D6 drop lowest 1 + {b}").unwrap();
	assert_ne!(ast.span, SourceSpan::default());
	let untethered = ast.untethered();

	assert_eq!(untethered.span, SourceSpan::default());
	let parameters = untethered.parameters.as_ref().unwrap();
	assert_eq!(parameters[0].name, "a");
	assert_eq!(parameters[0].span, SourceSpan::default());
	assert_eq!(parameters[1].name, "b");
	assert_eq!(parameters[1].span, SourceSpan::default());

	// Walk the body: Add(DropLowest(Standard(Variable, Constant), Some(1)),
	// Variable).
	match untethered.body
	{
		Expression::Arithmetic(ArithmeticExpression::Add(add)) =>
		{
			assert_eq!(add.span, SourceSpan::default());
			match *add.left
			{
				Expression::Dice(DiceExpression::DropLowest(drop)) =>
				{
					assert_eq!(drop.span, SourceSpan::default());
					let drop_count =
						drop.drop.as_ref().expect("explicit drop count");
					assert_eq!(drop_count.span(), SourceSpan::default());
					match *drop.dice
					{
						DiceExpression::Standard(sd) =>
						{
							assert_eq!(sd.span, SourceSpan::default());
							assert_eq!(sd.count.span(), SourceSpan::default());
							assert_eq!(sd.faces.span(), SourceSpan::default());
						},
						other =>
						{
							panic!("expected Standard, got {:?}", other)
						}
					}
				},
				other => panic!("expected DropLowest, got {:?}", other)
			}
			match *add.right
			{
				Expression::Variable(v) =>
				{
					assert_eq!(v.name, "b");
					assert_eq!(v.span, SourceSpan::default());
				},
				other => panic!("expected Variable, got {:?}", other)
			}
		},
		other => panic!("expected Add, got {:?}", other)
	}
}

/// [`Spanned::untethered`] on a parameter-less function leaves `parameters` as
/// `None` rather than materializing an empty vector.
#[test]
fn test_untethered_preserves_none_parameters()
{
	let ast = Parser::parse("1D6").unwrap();
	let untethered = ast.untethered();
	assert!(untethered.parameters.is_none());
	assert_eq!(untethered.span, SourceSpan::default());
}

/// [`Spanned::untethered`] on a [`CustomDice`] preserves the face vector
/// exactly (faces are raw `i32` values with no span of their own).
#[test]
fn test_untethered_custom_dice_preserves_faces()
{
	let ast = Parser::parse("2D[-1,0,1]").unwrap();
	let untethered = ast.untethered();
	match untethered.body
	{
		Expression::Dice(DiceExpression::Custom(cd)) =>
		{
			assert_eq!(cd.faces, vec![-1, 0, 1]);
			assert_eq!(cd.span, SourceSpan::default());
			assert_eq!(cd.count.span(), SourceSpan::default());
		},
		other => panic!("expected Custom, got {:?}", other)
	}
}

/// [`Spanned::untethered`] on a [`DropHighest`] without an explicit count keeps
/// the `drop` field as `None` (the optional payload is preserved verbatim).
#[test]
fn test_untethered_drop_highest_no_count()
{
	let ast = Parser::parse("4D6 drop highest").unwrap();
	let untethered = ast.untethered();
	match untethered.body
	{
		Expression::Dice(DiceExpression::DropHighest(drop)) =>
		{
			assert!(drop.drop.is_none());
			assert_eq!(drop.span, SourceSpan::default());
		},
		other => panic!("expected DropHighest, got {:?}", other)
	}
}

/// [`Spanned::untethered`] applied twice is idempotent: the second application
/// is a no-op on already-zeroed spans.
#[test]
fn test_untethered_is_idempotent()
{
	let ast = Parser::parse("1 + {x}").unwrap();
	let once = ast.untethered();
	let twice = once.untethered();
	assert_eq!(once, twice);
}

/// A structurally identical AST built by hand with default spans compares equal
/// to the [`Spanned::untethered`] form of the parser-originated AST.
#[test]
fn test_untethered_matches_hand_built_equivalent()
{
	let untethered = Parser::parse("{x} + 1").unwrap().untethered();
	let handbuilt = Function {
		parameters: None,
		body: Expression::Arithmetic(ArithmeticExpression::Add(Add {
			left: Box::new(Expression::Variable(Variable {
				name: "x",
				span: SourceSpan::default()
			})),
			right: Box::new(Expression::Constant(Constant {
				value: 1,
				span: SourceSpan::default()
			})),
			span: SourceSpan::default()
		})),
		span: SourceSpan::default()
	};
	assert_eq!(untethered, handbuilt);
}

////////////////////////////////////////////////////////////////////////////////
//                          Local-binding spans.                              //
////////////////////////////////////////////////////////////////////////////////

/// A [`Binding`] parsed from `x@(3D6)` has a full span covering the bound name
/// through the closing `)`, and a [`Binding::name_span`] covering just the
/// identifier.
#[test]
fn test_binding_span_covers_name_through_close_paren()
{
	let (_, expr) = expression(Span::new("x@(3D6)")).unwrap();
	match expr
	{
		Expression::Binding(b) =>
		{
			assert_eq!(b.name, "x");
			assert_eq!(b.name_span, span(0, 1));
			assert_eq!(b.span, span(0, 7));
			assert_eq!(b.expression.span(), span(3, 6));
		},
		other => panic!("expected Binding, got {:?}", other)
	}
}

/// A multi-word [`Binding`] identifier carries internal whitespace in its
/// [`Binding::name_span`], which covers the entire trimmed name.
#[test]
fn test_binding_multiword_name_span()
{
	let (_, expr) = expression(Span::new("a new id@(1D4)")).unwrap();
	match expr
	{
		Expression::Binding(b) =>
		{
			assert_eq!(b.name, "a new id");
			assert_eq!(b.name_span, span(0, 8));
			assert_eq!(b.span, span(0, 14));
		},
		other => panic!("expected Binding, got {:?}", other)
	}
}

/// Whitespace between the bound name, the `@`, and the parenthesized
/// expression is tolerated by the parser. [`Binding::name_span`] excludes the
/// whitespace; the full span extends through the closing `)`.
#[test]
fn test_binding_allows_whitespace_around_at_sign()
{
	let (_, expr) = expression(Span::new("x @ ( 3 + 2 )")).unwrap();
	match expr
	{
		Expression::Binding(b) =>
		{
			assert_eq!(b.name, "x");
			assert_eq!(b.name_span, span(0, 1));
			assert_eq!(b.span, span(0, 13));
		},
		other => panic!("expected Binding, got {:?}", other)
	}
}

/// Nested bindings — `a@(b@(1D4) + {b})` — preserve the full and name spans
/// of both the outer and inner [`Binding`]s.
#[test]
fn test_nested_binding_spans()
{
	let source = "a@(b@(1D4) + {b})";
	let (_, expr) = expression(Span::new(source)).unwrap();
	match expr
	{
		Expression::Binding(outer) =>
		{
			assert_eq!(outer.name, "a");
			assert_eq!(outer.name_span, span(0, 1));
			assert_eq!(outer.span, span(0, 17));
			// The bound expression is an `Add`; its left operand is the
			// inner binding.
			match outer.expression.as_ref()
			{
				Expression::Arithmetic(ArithmeticExpression::Add(add)) =>
				{
					match add.left.as_ref()
					{
						Expression::Binding(inner) =>
						{
							assert_eq!(inner.name, "b");
							assert_eq!(inner.name_span, span(3, 4));
							assert_eq!(inner.span, span(3, 10));
						},
						other =>
						{
							panic!("expected inner Binding, got {:?}", other)
						}
					}
				},
				other => panic!("expected Add, got {:?}", other)
			}
		},
		other => panic!("expected outer Binding, got {:?}", other)
	}
}

/// [`Spanned::untethered`] on a [`Binding`] zeroes both [`Binding::span`] and
/// [`Binding::name_span`], and recurses into the bound expression.
#[test]
fn test_untethered_binding_zeroes_all_spans()
{
	let ast = Parser::parse("x@(3D6) + {x}").unwrap();
	let untethered = ast.untethered();
	match &untethered.body
	{
		Expression::Arithmetic(ArithmeticExpression::Add(add)) =>
		{
			match add.left.as_ref()
			{
				Expression::Binding(b) =>
				{
					assert_eq!(b.name, "x");
					assert_eq!(b.name_span, SourceSpan::default());
					assert_eq!(b.span, SourceSpan::default());
					assert_eq!(b.expression.span(), SourceSpan::default());
				},
				other => panic!("expected Binding, got {:?}", other)
			}
		},
		other => panic!("expected Add, got {:?}", other)
	}
}