xdy 0.13.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
//! # Explicit-stack traversal
//!
//! Herein is the traversal that underlies the hand-written [`Debug`],
//! [`PartialEq`], and [`Hash`] implementations of [`Expression`] and
//! [`DiceExpression`]. It expands a node into a stream of [events](Event) that
//! mirrors the shape of the derived [`Debug`] format — structs, tuples, field
//! names, and leaves — using an explicit stack in place of recursion, so its
//! stack depth is constant however deep the tree.
//!
//! The stream serves all three traits at once:
//!
//! - [`debug`] renders the stream in the derived format, both compact (`{:?}`)
//!   and pretty (`{:#?}`).
//! - [`eq`] compares two streams in lockstep. The stream encodes the tree
//!   faithfully — every variant, field, and leaf — so two trees are equal if
//!   and only if their streams are.
//! - [`hash`] hashes the stream, which is therefore consistent with [`eq`].
//!
//! The recursive fields of every AST type are either [`Expression`]s or
//! [`DiceExpression`]s, so these two types are the only [nodes](Node); the
//! struct and enum types between them are expanded inline. The other AST types
//! derive their traits, which bottom out here after a single level.

use std::{
	fmt::{self, Debug, Formatter, Write},
	hash::{Hash, Hasher}
};

use super::{
	Add, ArithmeticExpression, Constant, DiceExpression, Div, Exp, Expression,
	Mod, Mul, Sub, Variable
};
use crate::span::SourceSpan;

////////////////////////////////////////////////////////////////////////////////
//                                  Events.                                   //
////////////////////////////////////////////////////////////////////////////////

/// A node from which a traversal starts, and at which it expands the tree.
#[derive(Copy, Clone)]
pub(super) enum Node<'a, 'src>
{
	/// An arbitrary expression.
	Expression(&'a Expression<'src>),

	/// A dice expression.
	Dice(&'a DiceExpression<'src>)
}

/// An event in the traversal of an AST. The events mirror the calls that the
/// derived [`Debug`] implementations make on a [`Formatter`].
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub(super) enum Event<'a, 'src>
{
	/// Open a struct, e.g., `Group { … }`. Its fields follow, each introduced
	/// by a [`Field`](Self::Field), and a [`Close`](Self::Close) ends it.
	Struct(&'static str),

	/// Open a tuple, e.g., `Group(…)` or `Some(…)`. Its fields follow, and a
	/// [`Close`](Self::Close) ends it.
	Tuple(&'static str),

	/// Name the next field of the innermost struct.
	Field(&'static str),

	/// A leaf, i.e., a value that is not an [`Expression`] or a
	/// [`DiceExpression`].
	Leaf(Leaf<'a, 'src>),

	/// A unit value, e.g., `None`.
	Unit(&'static str),

	/// Close the innermost struct or tuple.
	Close
}

/// A leaf of an AST.
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub(super) enum Leaf<'a, 'src>
{
	/// A source span.
	Span(SourceSpan),

	/// The name of a binding.
	Name(&'a str),

	/// A constant.
	Constant(Constant),

	/// A variable reference.
	Variable(&'a Variable<'src>),

	/// The faces of a custom die.
	Faces(&'a [i32])
}

impl Leaf<'_, '_>
{
	/// Answer the leaf as a [`Debug`] trait object.
	///
	/// # Returns
	/// The leaf's value.
	fn as_debug(&self) -> &dyn Debug
	{
		match self
		{
			Leaf::Span(span) => span,
			Leaf::Name(name) => name,
			Leaf::Constant(constant) => constant,
			Leaf::Variable(variable) => variable,
			Leaf::Faces(faces) => faces
		}
	}
}

/// An entry on the stack of [`Events`]: either an event ready to emit, or a
/// node awaiting expansion.
#[derive(Copy, Clone)]
enum Item<'a, 'src>
{
	/// An event ready to emit.
	Event(Event<'a, 'src>),

	/// A node awaiting expansion.
	Node(Node<'a, 'src>)
}

/// The stream of [events](Event) for a pre-order traversal of an AST. The stack
/// holds the pending work of every open node, so its length grows with the
/// depth of the tree, but the machine stack does not.
pub(super) struct Events<'a, 'src>
{
	/// The pending items, the next of which is on top.
	stack: Vec<Item<'a, 'src>>
}

impl<'a, 'src> Events<'a, 'src>
{
	/// Begin a traversal.
	///
	/// # Parameters
	/// - `root`: The node at which to start.
	///
	/// # Returns
	/// The stream of events.
	pub(super) fn new(root: Node<'a, 'src>) -> Self
	{
		Events {
			stack: vec![Item::Node(root)]
		}
	}

	/// Schedule the specified items, the first of which will be next.
	///
	/// # Parameters
	/// - `items`: The items, in order of emission.
	fn schedule(&mut self, items: &[Item<'a, 'src>])
	{
		self.stack.extend(items.iter().rev());
	}

	/// Expand a node into its events, scheduling its children for expansion
	/// in turn.
	///
	/// # Parameters
	/// - `node`: The node.
	fn expand(&mut self, node: Node<'a, 'src>)
	{
		match node
		{
			Node::Expression(expression) => self.expand_expression(expression),
			Node::Dice(dice) => self.expand_dice(dice)
		}
	}

	/// Expand an [`Expression`].
	///
	/// # Parameters
	/// - `expression`: The expression.
	fn expand_expression(&mut self, expression: &'a Expression<'src>)
	{
		match expression
		{
			Expression::Group(group) => self.schedule(&[
				tuple("Group"),
				structure("Group"),
				field("expression"),
				expression_node(&group.expression),
				field("span"),
				span(group.span),
				close(),
				close()
			]),
			Expression::Constant(constant) => self.schedule(&[
				tuple("Constant"),
				leaf(Leaf::Constant(*constant)),
				close()
			]),
			Expression::Variable(variable) => self.schedule(&[
				tuple("Variable"),
				leaf(Leaf::Variable(variable)),
				close()
			]),
			Expression::Binding(binding) => self.schedule(&[
				tuple("Binding"),
				structure("Binding"),
				field("name"),
				leaf(Leaf::Name(&binding.name)),
				field("name_span"),
				span(binding.name_span),
				field("expression"),
				expression_node(&binding.expression),
				field("span"),
				span(binding.span),
				close(),
				close()
			]),
			Expression::Range(range) => self.schedule(&[
				tuple("Range"),
				structure("Range"),
				field("start"),
				expression_node(&range.start),
				field("end"),
				expression_node(&range.end),
				field("span"),
				span(range.span),
				close(),
				close()
			]),
			Expression::Dice(dice) =>
			{
				self.schedule(&[tuple("Dice"), dice_node(dice), close()])
			},
			Expression::Arithmetic(arithmetic) =>
			{
				self.expand_arithmetic(arithmetic)
			},
		}
	}

	/// Expand an [`Expression::Arithmetic`].
	///
	/// # Parameters
	/// - `arithmetic`: The arithmetic expression.
	fn expand_arithmetic(&mut self, arithmetic: &'a ArithmeticExpression<'src>)
	{
		match arithmetic
		{
			ArithmeticExpression::Add(Add { left, right, span })
			| ArithmeticExpression::Sub(Sub { left, right, span })
			| ArithmeticExpression::Mul(Mul { left, right, span })
			| ArithmeticExpression::Div(Div { left, right, span })
			| ArithmeticExpression::Mod(Mod { left, right, span })
			| ArithmeticExpression::Exp(Exp { left, right, span }) =>
			{
				let name = match arithmetic
				{
					ArithmeticExpression::Add(_) => "Add",
					ArithmeticExpression::Sub(_) => "Sub",
					ArithmeticExpression::Mul(_) => "Mul",
					ArithmeticExpression::Div(_) => "Div",
					ArithmeticExpression::Mod(_) => "Mod",
					ArithmeticExpression::Exp(_) => "Exp",
					ArithmeticExpression::Neg(_) => unreachable!()
				};
				self.schedule(&[
					tuple("Arithmetic"),
					tuple(name),
					structure(name),
					field("left"),
					expression_node(left),
					field("right"),
					expression_node(right),
					field("span"),
					self::span(*span),
					close(),
					close(),
					close()
				])
			},
			ArithmeticExpression::Neg(neg) => self.schedule(&[
				tuple("Arithmetic"),
				tuple("Neg"),
				structure("Neg"),
				field("operand"),
				expression_node(&neg.operand),
				field("span"),
				span(neg.span),
				close(),
				close(),
				close()
			])
		}
	}

	/// Expand a [`DiceExpression`].
	///
	/// # Parameters
	/// - `dice`: The dice expression.
	fn expand_dice(&mut self, dice: &'a DiceExpression<'src>)
	{
		let (variant, name, dice, drop, span) = match dice
		{
			DiceExpression::Standard(standard) =>
			{
				return self.schedule(&[
					tuple("Standard"),
					structure("StandardDice"),
					field("count"),
					expression_node(&standard.count),
					field("faces"),
					expression_node(&standard.faces),
					field("span"),
					span(standard.span),
					close(),
					close()
				])
			},
			DiceExpression::Custom(custom) =>
			{
				return self.schedule(&[
					tuple("Custom"),
					structure("CustomDice"),
					field("count"),
					expression_node(&custom.count),
					field("faces"),
					leaf(Leaf::Faces(&custom.faces)),
					field("span"),
					span(custom.span),
					close(),
					close()
				])
			},
			DiceExpression::DropLowest(clause) => (
				"DropLowest",
				"DropLowest",
				&clause.dice,
				&clause.drop,
				clause.span
			),
			DiceExpression::DropHighest(clause) => (
				"DropHighest",
				"DropHighest",
				&clause.dice,
				&clause.drop,
				clause.span
			)
		};
		// Schedule the parts in reverse, since each goes atop its successor.
		self.schedule(&[field("span"), self::span(span), close(), close()]);
		match drop
		{
			None => self.schedule(&[Item::Event(Event::Unit("None"))]),
			Some(drop) =>
			{
				self.schedule(&[tuple("Some"), expression_node(drop), close()])
			},
		}
		self.schedule(&[
			tuple(variant),
			structure(name),
			field("dice"),
			dice_node(dice),
			field("drop")
		]);
	}
}

impl<'a, 'src> Iterator for Events<'a, 'src>
{
	type Item = Event<'a, 'src>;

	fn next(&mut self) -> Option<Self::Item>
	{
		loop
		{
			match self.stack.pop()?
			{
				Item::Event(event) => return Some(event),
				Item::Node(node) => self.expand(node)
			}
		}
	}
}

/// Answer an item that opens a struct.
///
/// # Parameters
/// - `name`: The name of the struct.
///
/// # Returns
/// The item.
fn structure<'a, 'src>(name: &'static str) -> Item<'a, 'src>
{
	Item::Event(Event::Struct(name))
}

/// Answer an item that opens a tuple.
///
/// # Parameters
/// - `name`: The name of the tuple.
///
/// # Returns
/// The item.
fn tuple<'a, 'src>(name: &'static str) -> Item<'a, 'src>
{
	Item::Event(Event::Tuple(name))
}

/// Answer an item that names a field.
///
/// # Parameters
/// - `name`: The name of the field.
///
/// # Returns
/// The item.
fn field<'a, 'src>(name: &'static str) -> Item<'a, 'src>
{
	Item::Event(Event::Field(name))
}

/// Answer an item that closes a struct or tuple.
///
/// # Returns
/// The item.
fn close<'a, 'src>() -> Item<'a, 'src> { Item::Event(Event::Close) }

/// Answer an item for a leaf.
///
/// # Parameters
/// - `leaf`: The leaf.
///
/// # Returns
/// The item.
fn leaf<'a, 'src>(leaf: Leaf<'a, 'src>) -> Item<'a, 'src>
{
	Item::Event(Event::Leaf(leaf))
}

/// Answer an item for a source span.
///
/// # Parameters
/// - `span`: The span.
///
/// # Returns
/// The item.
fn span<'a, 'src>(span: SourceSpan) -> Item<'a, 'src> { leaf(Leaf::Span(span)) }

/// Answer an item for an expression awaiting expansion.
///
/// # Parameters
/// - `expression`: The expression.
///
/// # Returns
/// The item.
fn expression_node<'a, 'src>(expression: &'a Expression<'src>)
-> Item<'a, 'src>
{
	Item::Node(Node::Expression(expression))
}

/// Answer an item for a dice expression awaiting expansion.
///
/// # Parameters
/// - `dice`: The dice expression.
///
/// # Returns
/// The item.
fn dice_node<'a, 'src>(dice: &'a DiceExpression<'src>) -> Item<'a, 'src>
{
	Item::Node(Node::Dice(dice))
}

////////////////////////////////////////////////////////////////////////////////
//                              Debug rendering.                              //
////////////////////////////////////////////////////////////////////////////////

/// Render an AST in the derived [`Debug`] format, compact or pretty according
/// to the formatter's [alternate](Formatter::alternate) flag.
///
/// # Parameters
/// - `root`: The root of the AST.
/// - `f`: The formatter.
///
/// # Returns
/// The result of writing to the formatter.
///
/// # Errors
/// Propagates any error from the formatter.
///
/// # Notes
/// In compact mode, leaves are rendered directly with `f`, so every formatter
/// flag reaches them, as in the derived format. In pretty mode, leaves are
/// rendered with `{:#?}` through an [`Indenter`], so other flags (e.g., `x` in
/// `{:#x?}`) do not reach them. The derived format keeps them, by nesting a
/// formatter per level; stable Rust offers no way to do so iteratively.
pub(super) fn debug(root: Node<'_, '_>, f: &mut Formatter<'_>) -> fmt::Result
{
	let pretty = f.alternate();
	let mut open = Vec::<Container>::new();
	for event in Events::new(root)
	{
		match event
		{
			Event::Struct(name) | Event::Tuple(name) =>
			{
				begin_value(f, &mut open, pretty)?;
				f.write_str(name)?;
				open.push(Container {
					is_struct: matches!(event, Event::Struct(_)),
					has_fields: false
				});
			},
			Event::Unit(name) =>
			{
				begin_value(f, &mut open, pretty)?;
				f.write_str(name)?;
				end_value(f, &open, pretty)?;
			},
			Event::Leaf(leaf) =>
			{
				begin_value(f, &mut open, pretty)?;
				if pretty
				{
					let mut indenter = Indenter {
						f,
						levels: open.len(),
						on_newline: false
					};
					write!(indenter, "{:#?}", leaf.as_debug())?;
				}
				else
				{
					leaf.as_debug().fmt(f)?;
				}
				end_value(f, &open, pretty)?;
			},
			Event::Field(name) =>
			{
				let levels = open.len();
				let container = open
					.last_mut()
					.expect("a field must belong to an open struct");
				if pretty
				{
					if !container.has_fields
					{
						f.write_str(" {\n")?;
					}
					indent(f, levels)?;
				}
				else
				{
					f.write_str(
						if container.has_fields { ", " } else { " { " }
					)?;
				}
				container.has_fields = true;
				f.write_str(name)?;
				f.write_str(": ")?;
			},
			Event::Close =>
			{
				let container = open
					.pop()
					.expect("a close must match an open struct or tuple");
				if container.has_fields
				{
					if pretty
					{
						indent(f, open.len())?;
					}
					f.write_str(match (container.is_struct, pretty)
					{
						(true, true) => "}",
						(true, false) => " }",
						(false, _) => ")"
					})?;
				}
				end_value(f, &open, pretty)?;
			}
		}
	}
	Ok(())
}

/// A struct or tuple that [`debug`] has opened but not yet closed.
struct Container
{
	/// Whether the container is a struct, rather than a tuple.
	is_struct: bool,

	/// Whether the container has rendered any fields yet.
	has_fields: bool
}

/// Begin rendering a value. A value inside a tuple is a new field of that
/// tuple, so it needs a separator; a value inside a struct follows the
/// separator that its [`Field`](Event::Field) already rendered.
///
/// # Parameters
/// - `f`: The formatter.
/// - `open`: The open containers.
/// - `pretty`: Whether to render in pretty mode.
///
/// # Returns
/// The result of writing to the formatter.
///
/// # Errors
/// Propagates any error from the formatter.
fn begin_value(
	f: &mut Formatter<'_>,
	open: &mut [Container],
	pretty: bool
) -> fmt::Result
{
	let levels = open.len();
	match open.last_mut()
	{
		Some(container) if !container.is_struct =>
		{
			if pretty
			{
				if !container.has_fields
				{
					f.write_str("(\n")?;
				}
				indent(f, levels)?;
			}
			else
			{
				f.write_str(if container.has_fields { ", " } else { "(" })?;
			}
			container.has_fields = true;
			Ok(())
		},
		_ => Ok(())
	}
}

/// Finish rendering a value. In pretty mode, a value inside a container ends
/// its line with a comma.
///
/// # Parameters
/// - `f`: The formatter.
/// - `open`: The open containers.
/// - `pretty`: Whether to render in pretty mode.
///
/// # Returns
/// The result of writing to the formatter.
///
/// # Errors
/// Propagates any error from the formatter.
fn end_value(
	f: &mut Formatter<'_>,
	open: &[Container],
	pretty: bool
) -> fmt::Result
{
	if pretty && !open.is_empty()
	{
		f.write_str(",\n")?;
	}
	Ok(())
}

/// Write the indentation for the specified number of levels, four spaces per
/// level.
///
/// # Parameters
/// - `f`: The destination.
/// - `levels`: The number of levels.
///
/// # Returns
/// The result of writing to the destination.
///
/// # Errors
/// Propagates any error from the destination.
fn indent(f: &mut impl Write, levels: usize) -> fmt::Result
{
	/// A run of 64 spaces, written in chunks to keep deep indentation cheap.
	const SPACES: &str =
		"                                                                ";
	let mut remaining = 4 * levels;
	while remaining > 0
	{
		let chunk = remaining.min(SPACES.len());
		f.write_str(&SPACES[..chunk])?;
		remaining -= chunk;
	}
	Ok(())
}

/// A writer that indents every line but the first, as the
/// [`Formatter`]'s own pad adapter does for each level of the derived pretty
/// [`Debug`] format.
struct Indenter<'f, 'b>
{
	/// The underlying formatter.
	f: &'f mut Formatter<'b>,

	/// The number of levels by which to indent.
	levels: usize,

	/// Whether the last character written was a newline.
	on_newline: bool
}

impl Write for Indenter<'_, '_>
{
	fn write_str(&mut self, s: &str) -> fmt::Result
	{
		for line in s.split_inclusive('\n')
		{
			if self.on_newline
			{
				indent(self.f, self.levels)?;
			}
			self.on_newline = line.ends_with('\n');
			self.f.write_str(line)?;
		}
		Ok(())
	}
}

////////////////////////////////////////////////////////////////////////////////
//                           Equality and hashing.                            //
////////////////////////////////////////////////////////////////////////////////

/// Compare two ASTs for structural equality, including spans.
///
/// # Parameters
/// - `left`: The root of the first AST.
/// - `right`: The root of the second AST.
///
/// # Returns
/// `true` if the ASTs are equal, `false` otherwise.
pub(super) fn eq(left: Node<'_, '_>, right: Node<'_, '_>) -> bool
{
	Events::new(left).eq(Events::new(right))
}

/// Hash an AST, consistently with [`eq`].
///
/// # Parameters
/// - `root`: The root of the AST.
/// - `state`: The hasher.
pub(super) fn hash<H: Hasher>(root: Node<'_, '_>, state: &mut H)
{
	Events::new(root).for_each(|event| event.hash(state));
}