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
use std::ops::Range;

#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Span {
	pub start: usize,
	pub end: usize,
}

impl std::fmt::Debug for Span {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "{}+{}", self.start, self.end-self.start)
	}
}

impl Span {
	pub fn new(start: usize, end: usize) -> Self {
		assert!(start <= end);
		Span { start, end }
	}

	pub fn new_at(pos: usize) -> Self {
		Span { start: pos, end: pos }
	}

	pub fn at_start(&self) -> Self {
		Span::new_at(self.start)
	}

	pub fn at_end(&self) -> Self {
		Span::new_at(self.end)
	}

	pub fn join(self, b: Span) -> Self {
		Span::new(
			self.start.min(b.start),
			self.end.max(b.end)
		)
	}

	pub fn connects(self, b: Span) -> bool {
		let a = self;
		a.end == b.start
	}

	pub fn as_range(self) -> Range<usize> {
		self.start..self.end
	}
}

impl std::ops::BitOr for Span {
	type Output = Self;

	fn bitor(self, rhs: Self) -> Self::Output {
		self.join(rhs)
	}
}

impl std::ops::BitOrAssign for Span {
	fn bitor_assign(&mut self, rhs: Self) {
		*self = *self | rhs;
	}
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Spanned<T>(pub Span, pub T);

impl<T: std::fmt::Debug> std::fmt::Debug for Spanned<T> {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		self.0.fmt(f)?;
		f.write_str("@")?;
		self.1.fmt(f)
	}
}

impl<A> Spanned<A> {
	pub fn map<B>(self, f: impl FnOnce(A) -> B) -> Spanned<B> {
		Spanned(self.0, f(self.1))
	}
}