use oneyaml_core::{Diagnostic, Settings, Severity};
use super::arena::{Arena, shift_span};
use super::{NONE, SyntaxKind, SyntaxTree, TreeEditError};
#[must_use = "a detached fragment is dropped unless it is inserted"]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Fragment {
pub(super) arena: Arena,
pub(super) context: String,
pub(super) has_tags: bool,
}
impl Fragment {
pub fn parse(text: &str) -> Result<Self, TreeEditError> {
Self::parse_with(text, &Settings::new())
}
pub fn parse_with(text: &str, settings: &Settings) -> Result<Self, TreeEditError> {
let tree = SyntaxTree::parse_with(text, settings);
if let Some(d) = tree.diagnostics().find(|d| d.severity == Severity::Error) {
return Err(TreeEditError::Syntax { code: d.code });
}
let mut roots = Vec::new();
for c in tree.root().children() {
let implicit = c.kind() == SyntaxKind::Document
&& !c.children().any(|d| {
matches!(
d.kind(),
SyntaxKind::DocumentStartMarker
| SyntaxKind::DocumentEndMarker
| SyntaxKind::YamlDirective
| SyntaxKind::TagDirective
| SyntaxKind::ReservedDirective
)
});
if implicit {
roots.extend(c.children().map(|n| n.slot()));
} else {
roots.push(c.slot());
}
}
let (arena, has_tags) = tree.copy_forest(&roots)?;
Ok(Self {
arena,
context: String::new(),
has_tags,
})
}
#[must_use]
pub fn text(&self) -> &str {
self.arena.source.get(..self.arena.tiled).unwrap_or("")
}
#[must_use]
pub fn len(&self) -> usize {
self.arena.kinds.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.arena.kinds.is_empty()
}
pub fn root_kinds(&self) -> impl Iterator<Item = SyntaxKind> + '_ {
let flat = self.arena.flat();
flat.roots().filter_map(move |i| flat.kind(i))
}
#[must_use]
#[doc(hidden)]
pub fn root_count(&self) -> usize {
self.arena.flat().roots().count()
}
pub fn diagnostics(
&self,
) -> impl ExactSizeIterator<Item = std::borrow::Cow<'_, Diagnostic>> + '_ {
self.arena.diagnostics.iter().map(|(_, d)| d.view())
}
#[must_use]
pub fn has_errors(&self) -> bool {
self.diagnostics().any(|d| d.severity == Severity::Error)
}
pub fn unwrap_root(self, index: usize) -> Result<Self, TreeEditError> {
let flat = self.arena.flat();
let roots: Vec<usize> = flat.roots().collect();
let p = *roots.get(index).ok_or(TreeEditError::Position {
position: index,
len: roots.len(),
})?;
let kind = flat.kind(p).ok_or(TreeEditError::Internal)?;
if kind.is_token() || kind == SyntaxKind::Error {
return Err(TreeEditError::ReadOnly { kind });
}
let p32 = u32::try_from(p).map_err(|_| TreeEditError::Internal)?;
if flat.first_child(p).is_none() && !flat.diagnostics_at(p).is_empty() {
return Err(TreeEditError::ReadOnly { kind });
}
let down = |i: u32| {
if i > p32 && i != NONE {
i.saturating_sub(1)
} else {
i
}
};
let a = &self.arena;
let mut out = Arena {
source: a.source.clone(),
tiled: a.tiled,
..Arena::default()
};
for (i, ((k, parent), word)) in a.kinds.iter().zip(&a.parents).zip(&a.words).enumerate() {
if i == p {
continue;
}
out.kinds.push(*k);
out.parents
.push(if *parent == p32 { NONE } else { down(*parent) });
out.words
.push(if k.is_token() { *word } else { down(*word) });
}
let len = u32::try_from(out.kinds.len()).map_err(|_| TreeEditError::Internal)?;
out.extras = a
.extras
.iter()
.filter(|(i, _)| *i != p32)
.map(|(i, e)| (down(*i), *e))
.collect();
out.diagnostics = a
.diagnostics
.iter()
.map(|(i, d)| (down(*i), d.clone()))
.filter(|(i, _)| *i < len)
.collect();
let has_tags = tags_outside_documents(&out);
Ok(Self {
arena: out,
context: self.context,
has_tags,
})
}
pub fn concat(self, other: Self) -> Result<Self, TreeEditError> {
if self.has_tags && other.has_tags && self.context != other.context {
return Err(TreeEditError::TagContext);
}
let context = if self.has_tags || !other.has_tags {
self.context
} else {
other.context
};
let (a, b) = (self.arena, other.arena);
let big = |n: usize| u32::try_from(n).ok().filter(|n| *n < NONE);
let ta = a.tiled;
let tb = b.tiled;
let tail_a = a.source.get(ta..).unwrap_or("");
let tail_b = b.source.get(tb..).unwrap_or("");
let total = a.source.len().saturating_add(b.source.len());
big(total).ok_or(TreeEditError::Capacity)?;
let na = big(a.kinds.len()).ok_or(TreeEditError::Capacity)?;
big(a.kinds.len().saturating_add(b.kinds.len())).ok_or(TreeEditError::Capacity)?;
let ta32 = big(ta).ok_or(TreeEditError::Capacity)?;
let mut source = String::with_capacity(total);
source.push_str(a.source.get(..ta).unwrap_or(""));
source.push_str(b.source.get(..tb).unwrap_or(""));
source.push_str(tail_a);
source.push_str(tail_b);
let tiled = ta.saturating_add(tb);
let mut out = Arena {
source,
tiled,
kinds: a.kinds,
parents: a.parents,
words: a.words,
extras: Vec::new(),
diagnostics: a.diagnostics,
};
out.extras = a
.extras
.into_iter()
.map(|(i, mut e)| {
e.tag_prefix = e.tag_prefix.map(|p| p.saturating_add(tb));
(i, e)
})
.collect();
for ((k, parent), word) in b.kinds.iter().zip(&b.parents).zip(&b.words) {
out.kinds.push(*k);
out.parents.push(if *parent == NONE {
NONE
} else {
parent.saturating_add(na)
});
out.words.push(if k.is_token() {
word.saturating_add(ta32)
} else {
word.saturating_add(na)
});
}
let tail_shift = ta.saturating_add(tail_a.len());
for (i, mut e) in b.extras {
e.tag_prefix = e.tag_prefix.map(|p| p.saturating_add(tail_shift));
if let Some(h) = e.block.as_mut() {
h.span = shift_span(h.span, 0, ta);
}
out.extras.push((i.saturating_add(na), e));
}
for (i, mut d) in b.diagnostics {
d.shift(0, ta);
out.diagnostics.push((i.saturating_add(na), d));
}
let has_tags = self.has_tags || other.has_tags;
Ok(Self {
arena: out,
context,
has_tags,
})
}
}
impl Fragment {
pub(super) fn ends_line(&self) -> bool {
self.text().ends_with(['\n', '\r'])
}
pub(super) fn split_last_break(self) -> Result<(Self, Option<Self>), TreeEditError> {
let flat = self.arena.flat();
let Some(last) = flat.roots().last() else {
return Ok((self, None));
};
if flat.kind(last) != Some(SyntaxKind::LineBreak) || last == 0 {
return Ok((self, None));
}
if last.checked_add(1) != Some(flat.len()) {
return Err(TreeEditError::Internal);
}
let span = flat.token_span(last);
let text = flat.token_text(last).to_owned();
let diagnostics = flat.diagnostics_at(last).to_vec();
let mut body = self.arena;
let old_tiled = body.tiled;
let len = span.end.saturating_sub(span.start);
let lo = body
.diagnostics
.partition_point(|(i, _)| (*i as usize) < last);
body.diagnostics.truncate(lo);
body.kinds.truncate(last);
body.parents.truncate(last);
body.words.truncate(last);
let tail = body.source.get(old_tiled..).unwrap_or("").to_owned();
body.source.truncate(span.start);
body.source.push_str(&tail);
body.tiled = span.start;
for (_, e) in &mut body.extras {
e.tag_prefix = e.tag_prefix.map(|p| p.saturating_sub(len));
}
let has_tags = tags_outside_documents(&body);
let mut brk = Arena {
source: text,
tiled: len,
kinds: vec![SyntaxKind::LineBreak],
parents: vec![NONE],
words: vec![0],
..Arena::default()
};
brk.diagnostics = diagnostics
.into_iter()
.map(|(_, mut d)| {
d.shift(span.start, 0);
(0, d)
})
.collect();
Ok((
Self {
arena: body,
context: self.context,
has_tags,
},
Some(Self {
arena: brk,
context: String::new(),
has_tags: false,
}),
))
}
}
pub(super) fn tags_outside_documents(arena: &Arena) -> bool {
let flat = arena.flat();
let mut docs: Vec<usize> = Vec::new();
for i in 0..flat.len() {
while docs.last().is_some_and(|end| *end <= i) {
docs.pop();
}
match flat.kind(i) {
Some(SyntaxKind::Document) => docs.push(flat.end(i)),
Some(SyntaxKind::Tag) if docs.is_empty() => return true,
_ => {}
}
}
false
}