use std::collections::BTreeSet;
use std::ops::Range;
use granit_parser::{Event, Parser, ScalarStyle, StructureStyle};
use crate::text::{LF, block_header, line_end, line_start, trim_end};
use crate::{Error, Path, Segment};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Style {
Plain,
SingleQuoted,
DoubleQuoted,
Literal,
Folded,
Alias,
BlockSequence,
FlowSequence,
BlockMapping,
FlowMapping,
}
impl Style {
pub(crate) const fn is_block_collection(self) -> bool {
matches!(self, Self::BlockSequence | Self::BlockMapping)
}
#[cfg(feature = "serde")]
pub(crate) const fn is_scalar(self) -> bool {
matches!(
self,
Self::Plain | Self::SingleQuoted | Self::DoubleQuoted | Self::Literal | Self::Folded
)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Location {
pub start: usize,
pub end: usize,
pub line: usize,
pub column: usize,
}
impl Location {
pub(crate) fn of(source: &str, range: Range<usize>) -> Self {
let line = source[..range.start].matches(LF).count() + 1;
let column = source[line_start(source, range.start)..range.start]
.chars()
.count()
+ 1;
Self {
start: range.start,
end: range.end,
line,
column,
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct Key {
pub(crate) text: String,
pub(crate) range: Range<usize>,
}
#[derive(Clone, Debug)]
pub(crate) struct Node {
pub(crate) value: Range<usize>,
pub(crate) key: Option<Key>,
pub(crate) style: Style,
pub(crate) parent: Option<usize>,
pub(crate) children: Vec<usize>,
}
#[derive(Clone, Debug)]
pub(crate) struct Index {
pub(crate) nodes: Vec<Node>,
comment_lines: BTreeSet<usize>,
}
struct Frame {
node: usize,
pending_key: Option<Key>,
expect_key: bool,
flow: bool,
}
#[derive(Default)]
struct Builder {
nodes: Vec<Node>,
stack: Vec<Frame>,
comment_lines: BTreeSet<usize>,
documents: usize,
}
impl Builder {
fn event(
&mut self,
source: &str,
event: Event<'_>,
start: usize,
end: usize,
) -> Result<(), Error> {
match event {
Event::DocumentStart(..) => {
self.documents += 1;
if self.documents > 1 {
return Err(Error::Unsupported {
path: Path::root(),
what: "edit a stream of several documents",
});
}
}
Event::Comment(..) => {
let line = line_start(source, start);
if source[line..start].trim().is_empty() {
self.comment_lines.insert(line);
}
}
Event::Scalar(text, style, _, _) => {
self.scalar(source, text.into_owned(), style, start, end);
}
Event::Alias(_) => {
self.attach(Node::leaf(start..end, Style::Alias));
}
Event::SequenceStart(structure, ..) => self.open(false, structure, start),
Event::MappingStart(structure, ..) => self.open(true, structure, start),
Event::SequenceEnd | Event::MappingEnd => {
if let Some(frame) = self.stack.pop()
&& frame.flow
{
self.nodes[frame.node].value.end = end;
}
}
Event::StreamStart | Event::StreamEnd | Event::DocumentEnd => {}
#[expect(
clippy::match_same_arms,
reason = "Event is non-exhaustive; a later variant carries nothing this index tracks"
)]
_ => {}
}
Ok(())
}
fn scalar(&mut self, source: &str, text: String, style: ScalarStyle, start: usize, end: usize) {
if let Some(top) = self.stack.last_mut()
&& top.expect_key
{
top.pending_key = Some(Key {
text,
range: start..end,
});
top.expect_key = false;
return;
}
let range = match style {
ScalarStyle::Literal | ScalarStyle::Folded => match block_header(source, start) {
Some(header) => header..block_end(source, header, end),
None => start..trim_end(source, start, end),
},
ScalarStyle::Plain | ScalarStyle::SingleQuoted | ScalarStyle::DoubleQuoted => {
start..trim_end(source, start, end)
}
};
self.attach(Node::leaf(range, scalar_style(style)));
}
fn open(&mut self, mapping: bool, structure: StructureStyle, start: usize) {
let flow = matches!(structure, StructureStyle::Flow);
let style = match (mapping, flow) {
(true, true) => Style::FlowMapping,
(true, false) => Style::BlockMapping,
(false, true) => Style::FlowSequence,
(false, false) => Style::BlockSequence,
};
let node = self.attach(Node::leaf(start..start, style));
self.stack.push(Frame {
node,
pending_key: None,
expect_key: mapping,
flow,
});
}
fn attach(&mut self, mut node: Node) -> usize {
let id = self.nodes.len();
if let Some(top) = self.stack.last_mut() {
node.parent = Some(top.node);
node.key = top.pending_key.take();
top.expect_key = matches!(
self.nodes[top.node].style,
Style::BlockMapping | Style::FlowMapping
);
self.nodes[top.node].children.push(id);
}
self.nodes.push(node);
id
}
fn finish(mut self) -> Index {
for node in (0..self.nodes.len()).rev() {
if self.nodes[node].style.is_block_collection()
&& let Some(end) = self.nodes[node]
.children
.iter()
.map(|&child| self.nodes[child].value.end)
.max()
{
self.nodes[node].value.end = end;
}
}
Index {
nodes: self.nodes,
comment_lines: self.comment_lines,
}
}
}
impl Node {
fn leaf(value: Range<usize>, style: Style) -> Self {
Self {
value,
key: None,
style,
parent: None,
children: Vec::new(),
}
}
}
impl Index {
pub(crate) fn build(source: &str) -> Result<Self, Error> {
let mut builder = Builder::default();
for next in Parser::new_from_str(source) {
let (event, span) = next.map_err(|error| Error::Parse {
line: error.marker().line(),
column: error.marker().col() + 1,
message: error.info(),
})?;
let start = span.start.byte_offset().unwrap_or(0);
let end = span.end.byte_offset().unwrap_or(start);
builder.event(source, event, start, end)?;
}
Ok(builder.finish())
}
pub(crate) fn find(&self, path: &Path) -> Option<usize> {
self.walk(path).ok()
}
pub(crate) fn walk(&self, path: &Path) -> Result<usize, (usize, usize)> {
if self.nodes.is_empty() {
return Err((0, 0));
}
let mut at = 0;
for (depth, segment) in path.segments().iter().enumerate() {
let node = &self.nodes[at];
let child = match (node.style, segment) {
(Style::BlockMapping | Style::FlowMapping, Segment::Key(key)) => {
self.child_by_key(at, key)
}
(Style::BlockMapping | Style::FlowMapping, Segment::Index(index)) => {
self.child_by_key(at, &index.to_string())
}
(Style::BlockSequence | Style::FlowSequence, Segment::Index(index)) => {
node.children.get(*index).copied()
}
(Style::BlockSequence | Style::FlowSequence, Segment::Key(key)) => key
.parse::<usize>()
.ok()
.and_then(|index| node.children.get(index).copied()),
_ => None,
};
match child {
Some(child) => at = child,
None => return Err((at, depth)),
}
}
Ok(at)
}
fn child_by_key(&self, node: usize, key: &str) -> Option<usize> {
self.nodes[node].children.iter().copied().find(|&child| {
self.nodes[child]
.key
.as_ref()
.is_some_and(|k| k.text == key)
})
}
pub(crate) fn entry_start(&self, node: usize) -> usize {
let node = &self.nodes[node];
node.key
.as_ref()
.map_or(node.value.start, |key| key.range.start)
}
pub(crate) fn owned_start(&self, source: &str, node: usize) -> usize {
let mut start = line_start(source, self.entry_start(node));
while start > 0 {
let previous = line_start(source, start - 1);
if self.comment_lines.contains(&previous) {
start = previous;
} else {
break;
}
}
start
}
}
fn block_end(source: &str, header: usize, span_end: usize) -> usize {
let header_end = header
+ source[header..]
.find(char::is_whitespace)
.unwrap_or(source.len() - header);
let body = line_end(source, header_end);
let region = source.get(body..span_end).unwrap_or_default();
let Some(indent) = region
.lines()
.find(|line| !line.trim().is_empty())
.map(|line| line.len() - line.trim_start().len())
else {
return header_end;
};
let mut end = header_end;
let mut at = body;
for line in region.split_inclusive(LF) {
let content = line.trim_end_matches(LF);
if !content.trim().is_empty() || content.len() > indent {
end = at + content.len();
}
at += line.len();
}
end
}
fn scalar_style(style: ScalarStyle) -> Style {
match style {
ScalarStyle::SingleQuoted => Style::SingleQuoted,
ScalarStyle::DoubleQuoted => Style::DoubleQuoted,
ScalarStyle::Literal => Style::Literal,
ScalarStyle::Folded => Style::Folded,
ScalarStyle::Plain => Style::Plain,
}
}