spanner 0.2.0

map source code positions to easy-to-use structs
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
use {
	crate::{Arc, Buffer, BufferSource},
	::core::{
		hash::{Hash, Hasher},
		ops::{Add, AddAssign, Bound, Deref, Range, RangeBounds, Sub, SubAssign},
	},
	::tyfling::{debug, display},
};

/// a location in a [`Buffer`]
#[derive(Clone, Copy, Hash, Eq, PartialEq, Default)]
#[debug("({buf}: {pos})")]
pub struct Loc {
	/// the offset in the buffer
	pub pos: u32,
	pub(crate) buf: u16,
}

impl Loc {
	/// construct a [`Span`] starting at this location, with the given length
	#[inline]
	#[must_use]
	pub fn with_len(&self, len: u32) -> Span {
		Span::new(*self, *self + len)
	}

	/// returns whether both locations are in the same [`Buffer`]
	#[inline]
	#[must_use]
	pub fn same_buf_as(&self, rhs: &Loc) -> bool {
		self.buf == rhs.buf
	}
}

impl Add<u32> for Loc {
	type Output = Loc;

	fn add(mut self, rhs: u32) -> Self::Output {
		self += rhs;
		self
	}
}

impl AddAssign<u32> for Loc {
	fn add_assign(&mut self, rhs: u32) {
		self.pos += rhs;
	}
}

impl Sub<u32> for Loc {
	type Output = Loc;

	fn sub(mut self, rhs: u32) -> Self::Output {
		self -= rhs;
		self
	}
}

impl SubAssign<u32> for Loc {
	fn sub_assign(&mut self, rhs: u32) {
		self.pos -= rhs;
	}
}

impl Sub<Loc> for Loc {
	type Output = u32;

	fn sub(self, rhs: Loc) -> Self::Output {
		self.pos - rhs.pos
	}
}

#[cfg(feature = "miette")]
impl From<Loc> for ::miette::SourceOffset {
	fn from(loc: Loc) -> Self {
		(loc.pos as usize).into()
	}
}

/// a span of start and end [`Loc`]ations in a [`Buffer`]
#[derive(Clone, Copy, Hash, Eq, PartialEq, Default)]
#[debug("({buf}: {start}..{end})")]
pub struct Span {
	pub(crate) start: u32,
	pub(crate) end: u32,
	pub(crate) buf: u16,
}

impl Span {
	/// construct a span from two [`Loc`]ations
	///
	/// # Panics
	///
	/// if the span is backwards, or if the locations are in different [`Buffer`]s
	#[inline]
	#[must_use]
	#[track_caller]
	pub fn new(start: Loc, end: Loc) -> Self {
		assert_eq!(start.buf, end.buf, "span crosses different bufs");
		assert!(start.pos <= end.pos, "backwards span");
		Self {
			start: start.pos,
			end: end.pos,
			buf: start.buf,
		}
	}

	/// get the start of the span
	#[inline]
	#[must_use]
	pub fn start(&self) -> Loc {
		Loc {
			pos: self.start,
			buf: self.buf,
		}
	}

	/// get the start of the span
	#[inline]
	#[must_use]
	pub fn end(&self) -> Loc {
		Loc {
			pos: self.end,
			buf: self.buf,
		}
	}

	/// returns whether the span's length is 0
	#[inline]
	#[must_use]
	pub fn is_empty(&self) -> bool {
		self.len() == 0
	}

	/// the length in bytes this span covers
	#[inline]
	#[must_use]
	pub fn len(&self) -> u32 {
		self.end - self.start
	}

	/// returns whether this span contains the given [`Loc`]ation
	#[inline]
	#[must_use]
	pub fn contains(&self, loc: &Loc) -> bool {
		self.buf == loc.buf && self.start <= loc.pos && loc.pos < self.end
	}

	/// returns whether this span contains the given span
	#[inline]
	#[must_use]
	pub fn contains_span(&self, subspan: &Self) -> bool {
		self.buf == subspan.buf && self.start <= subspan.start && subspan.end <= self.end
	}

	/// take a sub-span, using a range of this span's source
	///
	/// # Panics
	///
	/// if the sub-span is backwards
	#[inline]
	#[must_use]
	pub fn subspan<B: RangeBounds<u32>>(self, range: B) -> Self {
		let span = Self {
			start: match range.start_bound() {
				Bound::Unbounded => self.start,
				Bound::Included(&bound) => self.start + bound,
				Bound::Excluded(&bound) => self.start + 1 + bound,
			},
			end: match range.end_bound() {
				Bound::Unbounded => self.end,
				Bound::Included(&bound) => self.start + 1 + bound,
				Bound::Excluded(&bound) => self.start + bound,
			},
			buf: self.buf,
		};
		assert!(span.start <= span.end, "backwards span");
		span
	}

	/// construct a span that covers both this one and the given one (and anything between them)
	///
	/// # Panics
	///
	/// if the spans are in different [`Buffer`]s
	#[inline]
	#[must_use]
	#[track_caller]
	pub fn union(&self, with: &Self) -> Self {
		assert_eq!(self.buf, with.buf, "spans are in different bufs");
		Self {
			start: ::core::cmp::min(self.start, with.start),
			end: ::core::cmp::max(self.end, with.end),
			buf: self.buf,
		}
	}

	/// construct a span that covers the shared area of both this span and the given one
	///
	/// # Panics
	///
	/// if the spans are in different [`Buffer`]s
	#[inline]
	#[must_use]
	#[track_caller]
	pub fn intersection(&self, with: &Self) -> Option<Self> {
		assert_eq!(self.buf, with.buf, "spans are in different bufs");
		let span = Self {
			start: ::core::cmp::max(self.start, with.start),
			end: ::core::cmp::min(self.end, with.end),
			buf: self.buf,
		};
		(span.start <= span.end).then_some(span)
	}

	/// construct a [`Span`] starting where self starts, with the given length
	#[inline]
	#[must_use]
	pub fn with_len(&self, len: u32) -> Self {
		Self {
			start: self.start,
			end: self.start + len,
			buf: self.buf,
		}
	}

	/// returns whether both locations are in the same [`Buffer`]
	#[inline]
	#[must_use]
	pub fn same_buf_as(&self, loc: Loc) -> bool {
		self.buf == loc.buf
	}
}

impl From<Loc> for Span {
	fn from(loc: Loc) -> Self {
		Self::new(loc, loc)
	}
}

impl From<Range<Loc>> for Span {
	fn from(span: Range<Loc>) -> Self {
		Self::new(span.start, span.end)
	}
}

/// a span of start and end [Loc]ations in a [`Buffer`], including a reference to the [`Buffer`] itself
#[debug("({buf}+: {start}..{end})", buf = buf.index)]
#[display("{}", &**self)]
pub struct SrcSpan<Src: BufferSource> {
	pub(crate) start: u32,
	pub(crate) end: u32,
	pub(crate) buf: Arc<Buffer<Src>>,
}

impl<Src: BufferSource> SrcSpan<Src> {
	/// get the start of the span
	#[inline]
	#[must_use]
	pub fn start(&self) -> Loc {
		Loc {
			pos: self.start,
			buf: self.buf.index,
		}
	}

	/// get the start of the span
	#[inline]
	#[must_use]
	pub fn end(&self) -> Loc {
		Loc {
			pos: self.end,
			buf: self.buf.index,
		}
	}

	/// find the [`Span`] this source span refers to
	///
	/// this is a trivial operation
	#[inline]
	#[must_use]
	pub fn span(&self) -> Span {
		Span {
			start: self.start,
			end: self.end,
			buf: self.buf.index,
		}
	}

	/// returns whether the span's length is 0
	#[inline]
	#[must_use]
	pub fn is_empty(&self) -> bool {
		self.len() == 0
	}

	/// the length in bytes this span covers
	#[inline]
	#[must_use]
	pub fn len(&self) -> u32 {
		self.end - self.start
	}

	/// returns whether this span contains the given [`Loc`]ation
	#[inline]
	#[must_use]
	pub fn contains(&self, loc: &Loc) -> bool {
		self.buf.index == loc.buf && self.start <= loc.pos && loc.pos < self.end
	}

	/// returns whether this span contains the given span
	#[inline]
	#[must_use]
	pub fn contains_span(&self, span: &Span) -> bool {
		self.buf.index == span.buf && self.start <= span.start && span.end <= self.end
	}

	/// take a sub-span, using a range of this span's source
	///
	/// # Panics
	///
	/// if the sub-span is backwards
	#[inline]
	#[must_use]
	#[track_caller]
	pub fn subspan<B: RangeBounds<u32>>(&self, range: B) -> Self {
		let span = Self {
			start: match range.start_bound() {
				Bound::Unbounded => self.start,
				Bound::Included(&bound) => self.start + bound,
				Bound::Excluded(&bound) => self.start + 1 + bound,
			},
			end: match range.end_bound() {
				Bound::Unbounded => self.end,
				Bound::Included(&bound) => self.start + 1 + bound,
				Bound::Excluded(&bound) => self.start + bound,
			},
			buf: self.buf.clone(),
		};
		assert!(span.start <= span.end, "backwards span");
		span
	}

	/// construct a span that covers both this one and the given one (and anything between them)
	///
	/// # Panics
	///
	/// if the spans are in different [`Buffer`]s
	#[inline]
	#[must_use]
	#[track_caller]
	pub fn union(&self, with: &Self) -> Self {
		assert_eq!(
			self.buf.index, with.buf.index,
			"spans are in different bufs"
		);
		Self {
			start: ::core::cmp::min(self.start, with.start),
			end: ::core::cmp::max(self.end, with.end),
			buf: self.buf.clone(),
		}
	}

	/// construct a span that covers the shared area of both this span and the given one
	///
	/// # Panics
	///
	/// if the spans are in different [`Buffer`]s
	#[inline]
	#[must_use]
	#[track_caller]
	pub fn intersection(&self, with: &Self) -> Option<Self> {
		assert_eq!(
			self.buf.index, with.buf.index,
			"spans are in different bufs"
		);
		let span = Self {
			start: ::core::cmp::max(self.start, with.start),
			end: ::core::cmp::min(self.end, with.end),
			buf: self.buf.clone(),
		};
		(span.start <= span.end).then_some(span)
	}

	/// construct a [`Span`] starting where self starts, with the given length
	#[inline]
	#[must_use]
	pub fn with_len(&self, len: u32) -> Self {
		Self {
			start: self.start,
			end: self.start + len,
			buf: self.buf.clone(),
		}
	}

	/// returns whether both locations are in the same [`Buffer`]
	#[inline]
	#[must_use]
	pub fn same_buf_as(&self, loc: Loc) -> bool {
		self.buf.index == loc.buf
	}

	/// the underlying [`Buffer`] this span is referencing
	#[inline]
	#[must_use]
	pub fn buf(&self) -> &Arc<Buffer<Src>> {
		&self.buf
	}
}

impl<Src: BufferSource> Deref for SrcSpan<Src> {
	type Target = str;

	fn deref(&self) -> &Self::Target {
		&self.buf.src.source()[self.start as usize..self.end as usize]
	}
}

impl<Src: BufferSource> Clone for SrcSpan<Src> {
	fn clone(&self) -> Self {
		Self {
			start: self.start,
			end: self.end,
			buf: Arc::clone(&self.buf),
		}
	}
}

impl<Src: BufferSource> Hash for SrcSpan<Src> {
	fn hash<H: Hasher>(&self, state: &mut H) {
		self.start.hash(state);
		self.end.hash(state);
		self.buf.hash(state);
	}
}

impl<Src: BufferSource> PartialEq for SrcSpan<Src> {
	fn eq(&self, rhs: &Self) -> bool {
		self.start == rhs.start && self.end == rhs.end && self.buf == rhs.buf
	}
}

impl<Src: BufferSource> Eq for SrcSpan<Src> {}

impl<Src: BufferSource> From<SrcSpan<Src>> for Span {
	fn from(src_span: SrcSpan<Src>) -> Self {
		Self {
			start: src_span.start,
			end: src_span.end,
			buf: src_span.buf.index,
		}
	}
}

#[cfg(feature = "miette")]
impl<Src: BufferSource> From<SrcSpan<Src>> for ::miette::SourceSpan {
	fn from(span: SrcSpan<Src>) -> Self {
		(span.start as usize..span.end as usize).into()
	}
}

/// a value annotated with a [`Loc`]ation
#[derive(Clone, Copy, Hash, Eq, PartialEq)]
#[debug("{f0:?} {f1:#?}")]
pub struct Locd<#[debug] T: ?Sized>(pub Loc, pub T);

/// a value annotated with a [`Span`]
#[derive(Clone, Copy, Hash, Eq, PartialEq)]
#[debug("{f0:?} {f1:#?}")]
pub struct Spanned<#[debug] T: ?Sized>(pub Span, pub T);

/// a value annotated with a [`SrcSpan`]
#[derive(Clone, Hash, Eq, PartialEq)]
#[debug("{f0:?} {f1:#?}")]
pub struct SrcSpanned<#[debug] T: ?Sized, Src: BufferSource>(pub SrcSpan<Src>, pub T);

/// helper extension trait to quickly wrap values
pub trait SpannerExt: Sized {
	/// helper extension method to quickly wrap values in [`Locd`]
	fn locd(self, loc: Loc) -> Locd<Self> {
		Locd(loc, self)
	}

	/// helper extension method to quickly wrap values in [`Spanned`]
	fn spanned(self, span: Span) -> Spanned<Self> {
		Spanned(span, self)
	}

	/// helper extension method to quickly wrap values in [`SrcSpanned`]
	fn src_spanned<Src: BufferSource>(self, src_span: SrcSpan<Src>) -> SrcSpanned<Self, Src> {
		SrcSpanned(src_span, self)
	}
}

impl<T> SpannerExt for T {}