use std::fmt;
use incremental_lang::{Grammar, Span, Tree};
use crate::{
lines::LineIndex,
position::{Encoding, Position, Range},
};
pub struct Document<G: Grammar> {
uri: Box<str>,
version: i32,
encoding: Encoding,
lines: LineIndex,
source: incremental_lang::Document<G>,
stale: bool,
}
impl<G: Grammar> Document<G> {
pub(crate) fn open(
grammar: G,
uri: &str,
version: i32,
text: String,
encoding: Encoding,
) -> Result<Self, incremental_lang::Error> {
let lines = LineIndex::new(&text);
let source = incremental_lang::Document::new(grammar, text)?;
Ok(Self {
uri: uri.into(),
version,
encoding,
lines,
source,
stale: false,
})
}
pub(crate) fn edit_span(&self, range: Option<Range>) -> Option<Span> {
let Some(range) = range else {
return Some(Span::new(0, self.source.text().len() as u32));
};
let lines = self.lines.len();
let exists = |at: Position| (at.line as usize) <= lines;
(exists(range.start) && exists(range.end)).then(|| self.span(range))
}
pub(crate) fn edit(&mut self, span: Span, text: &str) -> Result<(), incremental_lang::Error> {
let _reparse = self.source.edit(span, text)?;
self.lines.edit(
self.source.text(),
span.start().to_u32(),
span.end().to_u32(),
text.len() as u32,
);
Ok(())
}
pub(crate) fn is_stale(&self) -> bool {
self.stale
}
pub(crate) fn mark_stale(&mut self) {
self.stale = true;
}
pub(crate) fn synced(&mut self, version: i32) {
self.version = version;
self.stale = false;
}
pub(crate) fn positions(&self, offsets: &[u32], order: &mut Vec<u32>, out: &mut Vec<Position>) {
self.lines
.positions(self.source.text(), offsets, self.encoding, order, out);
}
pub(crate) fn width_of(&self, start: usize, end: usize) -> u32 {
let bytes = self.source.text().as_bytes();
bytes
.get(start..end)
.map_or(0, |slice| crate::lines::width(slice, self.encoding))
}
#[inline]
#[must_use]
pub fn uri(&self) -> &str {
&self.uri
}
#[inline]
#[must_use]
pub fn version(&self) -> i32 {
self.version
}
#[inline]
#[must_use]
pub fn text(&self) -> &str {
self.source.text()
}
#[inline]
#[must_use]
pub fn tree(&self) -> &Tree<G::Kind> {
self.source.tree()
}
#[inline]
#[must_use]
pub fn incremental(&self) -> &incremental_lang::Document<G> {
&self.source
}
#[inline]
#[must_use]
pub fn encoding(&self) -> Encoding {
self.encoding
}
#[inline]
#[must_use]
pub fn position(&self, offset: u32) -> Position {
self.lines
.position(self.source.text(), offset, self.encoding)
}
#[inline]
#[must_use]
pub fn offset(&self, position: Position) -> u32 {
self.lines
.offset(self.source.text(), position, self.encoding)
}
#[inline]
#[must_use]
pub fn range(&self, span: Span) -> Range {
Range::new(
self.position(span.start().to_u32()),
self.position(span.end().to_u32()),
)
}
#[inline]
#[must_use]
pub fn span(&self, range: Range) -> Span {
Span::new(self.offset(range.start), self.offset(range.end))
}
}
impl<G: Grammar + Clone> Document<G> {
pub(crate) fn rebuild(
&mut self,
span: Span,
text: &str,
) -> Result<(), incremental_lang::Error> {
let old = self.source.text();
let (start, end) = (span.start().to_usize(), span.end().to_usize());
if end > old.len() {
return Err(incremental_lang::Error::OutOfBounds {
span,
len: old.len() as u32,
});
}
if let Some(&offset) = [start, end].iter().find(|&&at| !old.is_char_boundary(at)) {
return Err(incremental_lang::Error::NotCharBoundary {
offset: offset as u32,
});
}
let mut spliced = String::with_capacity(old.len() - (end - start) + text.len());
spliced.push_str(&old[..start]);
spliced.push_str(text);
spliced.push_str(&old[end..]);
self.reset(spliced)
}
pub(crate) fn reset(&mut self, text: String) -> Result<(), incremental_lang::Error> {
let source = incremental_lang::Document::new(self.source.grammar().clone(), text)?;
self.lines = LineIndex::new(source.text());
self.source = source;
Ok(())
}
}
impl<G: Grammar> fmt::Debug for Document<G> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Document")
.field("uri", &self.uri)
.field("version", &self.version)
.field("encoding", &self.encoding)
.field("len", &self.source.text().len())
.field("stale", &self.stale)
.finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::Chars;
type Result = std::result::Result<(), incremental_lang::Error>;
fn open(
text: &str,
encoding: Encoding,
) -> std::result::Result<Document<Chars>, incremental_lang::Error> {
Document::open(Chars, "file:///t", 1, text.to_owned(), encoding)
}
fn change(doc: &mut Document<Chars>, range: Option<Range>, text: &str) -> Result {
let span = doc
.edit_span(range)
.ok_or(incremental_lang::Error::OutOfBounds {
span: Span::new(0, 0),
len: 0,
})?;
doc.edit(span, text)
}
#[test]
fn test_change_with_range_applies_utf16_edit() -> Result {
let mut doc = open("aπb\nc", Encoding::Utf16)?;
let range = Range::new(Position::new(0, 1), Position::new(0, 3));
change(&mut doc, Some(range), "Γ©")?;
assert_eq!(doc.text(), "aΓ©b\nc");
assert_eq!(doc.position(5), Position::new(1, 0));
assert_eq!(doc.lines, LineIndex::new(doc.text()));
Ok(())
}
#[test]
fn test_change_without_range_replaces_everything() -> Result {
let mut doc = open("old\ntext", Encoding::Utf8)?;
change(&mut doc, None, "new")?;
assert_eq!(doc.text(), "new");
assert_eq!(doc.lines, LineIndex::new("new"));
Ok(())
}
#[test]
fn test_edit_span_refuses_lines_the_document_does_not_have() -> Result {
let doc = open(
"ab
cd",
Encoding::Utf16,
)?; let at = |line, character| Position::new(line, character);
let range = |a, b| Some(Range::new(a, b));
assert_eq!(
doc.edit_span(range(at(0, 99), at(0, 99))),
Some(Span::new(2, 2))
);
assert_eq!(
doc.edit_span(range(at(2, 0), at(2, 7))),
Some(Span::new(5, 5))
);
assert_eq!(doc.edit_span(range(at(3, 0), at(3, 0))), None);
assert_eq!(doc.edit_span(range(at(0, 0), at(u32::MAX, 0))), None);
assert_eq!(doc.edit_span(None), Some(Span::new(0, 5)));
Ok(())
}
#[test]
fn test_rebuild_splices_and_reparses_from_scratch() -> Result {
let mut doc = open(
"one
two",
Encoding::Utf8,
)?;
doc.rebuild(
Span::new(3, 4),
"π
",
)?;
assert_eq!(
doc.text(),
"oneπ
two"
);
assert_eq!(doc.lines, LineIndex::new(doc.text()));
assert_eq!(doc.incremental().stats().full, 1);
let before = doc.text().to_owned();
assert!(doc.rebuild(Span::new(4, 4), "x").is_err()); assert!(doc.rebuild(Span::new(0, 99), "x").is_err());
assert_eq!(doc.text(), before);
Ok(())
}
#[test]
fn test_stale_flag_clears_on_sync() -> Result {
let mut doc = open("x", Encoding::Utf8)?;
assert!(!doc.is_stale());
doc.mark_stale();
assert!(doc.is_stale() && doc.version() == 1);
doc.synced(4);
assert!(!doc.is_stale() && doc.version() == 4);
Ok(())
}
#[test]
fn test_range_and_span_round_trip() -> Result {
let doc = open("one\r\ntwoπthree", Encoding::Utf16)?;
let span = Span::new(5, 12);
let range = doc.range(span);
assert_eq!(range, Range::new(Position::new(1, 0), Position::new(1, 5)));
assert_eq!(doc.span(range), span);
Ok(())
}
#[test]
fn test_debug_shows_identity_not_text() -> Result {
let doc = open("secret", Encoding::Utf16)?;
let shown = format!("{doc:?}");
assert!(shown.contains("file:///t") && !shown.contains("secret"));
Ok(())
}
}