nushell/crates/nu-protocol/src/span.rs

76 lines
2.0 KiB
Rust
Raw Normal View History

use miette::SourceSpan;
2021-10-01 07:11:49 +02:00
use serde::{Deserialize, Serialize};
2021-11-03 01:26:09 +01:00
/// A spanned area of interest, generic over what kind of thing is of interest
#[derive(Clone, Debug, Serialize, Deserialize)]
2021-10-05 04:27:39 +02:00
pub struct Spanned<T>
where
T: Clone + std::fmt::Debug,
{
2021-10-01 23:53:13 +02:00
pub item: T,
pub span: Span,
}
2021-11-03 01:26:09 +01:00
/// Spans are a global offset across all seen files, which are cached in the engine's state. The start and
/// end offset together make the inclusive start/exclusive end pair for where to underline to highlight
/// a given point of interest.
2021-10-13 19:53:27 +02:00
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
2021-06-30 03:42:56 +02:00
pub struct Span {
pub start: usize,
pub end: usize,
}
impl From<Span> for SourceSpan {
fn from(s: Span) -> Self {
Self::new(s.start.into(), (s.end - s.start).into())
}
}
2021-06-30 03:42:56 +02:00
impl Span {
pub fn new(start: usize, end: usize) -> Span {
Span { start, end }
2021-06-30 03:42:56 +02:00
}
2021-07-01 02:01:04 +02:00
2021-12-19 08:46:13 +01:00
/// Note: Only use this for test data, *not* live data, as it will point into unknown source when used in errors
pub fn test_data() -> Span {
Span { start: 0, end: 0 }
2021-07-01 02:01:04 +02:00
}
2021-07-22 22:45:23 +02:00
pub fn offset(&self, offset: usize) -> Span {
Span {
start: self.start - offset,
end: self.end - offset,
}
}
2021-10-13 19:53:27 +02:00
pub fn contains(&self, pos: usize) -> bool {
pos >= self.start && pos < self.end
}
2022-01-04 00:14:33 +01:00
/// Point to the space just past this span, useful for missing
/// values
pub fn past(&self) -> Span {
Span {
start: self.end,
end: self.end,
}
}
2021-06-30 03:42:56 +02:00
}
2021-09-02 03:29:43 +02:00
2021-12-19 20:25:02 +01:00
/// Used when you have a slice of spans of at least size 1
2021-09-02 03:29:43 +02:00
pub fn span(spans: &[Span]) -> Span {
let length = spans.len();
if length == 0 {
2021-12-19 20:25:02 +01:00
// TODO: do this for now, but we might also want to protect against this case
Span { start: 0, end: 0 }
2021-09-02 03:29:43 +02:00
} else if length == 1 {
spans[0]
} else {
Span {
start: spans[0].start,
end: spans[length - 1].end,
}
}
}