use crate::sources::source_file::SourceFile;
use miette::{MietteError, SourceCode, SourceSpan, SpanContents};
use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Formatter};
#[derive(Clone, Serialize, Deserialize)]
pub struct Span {
pub position: usize,
pub length: usize,
pub source: SourceFile,
}
impl Debug for Span {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Span")
.field("position", &self.position)
.field("length", &self.length)
.finish()
}
}
impl Span {
pub fn from_length(source: &SourceFile, position: usize, length: usize) -> Self {
Self {
source: source.clone(),
position,
length,
}
}
pub fn from_end(source: &SourceFile, position: usize, end: usize) -> Self {
assert!(end >= position);
Self {
source: source.clone(),
position,
length: end - position,
}
}
pub fn end(&self) -> usize {
self.position + self.length
}
pub fn as_str(&self) -> &str {
&self.source.contents()[self.position..self.position + self.length]
}
pub fn merge(&self, other: &Span) -> Self {
Self::from_end(
&self.source,
self.position.min(other.position),
self.end().max(other.end()),
)
}
}
impl SourceCode for Span {
fn read_span<'a>(
&'a self,
span: &SourceSpan,
context_lines_before: usize,
context_lines_after: usize,
) -> Result<Box<dyn SpanContents<'a> + 'a>, MietteError> {
<str as SourceCode>::read_span(
self.source.contents_for_display(),
span,
context_lines_before,
context_lines_after,
)
}
}
impl From<Span> for SourceSpan {
fn from(span: Span) -> Self {
SourceSpan::from((span.position, span.length))
}
}