use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use crate::dsl::error::{Diagnostic, Location, MAX_DIAGNOSTICS, Raw, Span, capped};
use crate::dsl::lex::Comment;
use crate::dsl::policy::{Language, Note, NoteAnchor, NoteOrigin, Origins, Placement, Policy, ids};
#[derive(Debug, Clone)]
struct Extent {
id: String,
first: u32,
last: u32,
parent: Option<usize>,
depth: usize,
}
pub(crate) struct Builder {
file: Arc<str>,
language: Language,
pub policy: Policy,
pub origins: Origins,
diagnostics: Vec<Diagnostic>,
hidden: usize,
extents: Vec<Extent>,
open: Vec<usize>,
invariants: BTreeMap<String, usize>,
}
impl Builder {
pub fn new(file: Arc<str>, language: Language) -> Self {
Self {
file,
language,
policy: Policy::default(),
origins: Origins::default(),
diagnostics: Vec::new(),
hidden: 0,
extents: Vec::new(),
open: Vec::new(),
invariants: BTreeMap::new(),
}
}
pub fn location(&self, span: Span) -> Location {
Location::new(Arc::clone(&self.file), span.line, span.col, span.len.max(1))
}
pub fn report(&mut self, raw: Raw) {
if self.diagnostics.len() >= MAX_DIAGNOSTICS {
self.hidden += 1;
return;
}
self.diagnostics.push(raw.locate(&self.file));
}
pub fn conflict(&mut self, raw: Raw, first: Option<Location>) {
if self.diagnostics.len() >= MAX_DIAGNOSTICS {
self.hidden += 1;
return;
}
let mut diagnostic = raw.locate(&self.file);
diagnostic.related = first;
self.diagnostics.push(diagnostic);
}
pub fn declared(&self, id: &str) -> Option<Location> {
self.origins.exact(id).cloned()
}
pub fn mark(&mut self, id: &str, span: Span) {
let at = self.location(span);
self.origins.insert(id.to_string(), at);
}
pub fn open(&mut self, id: &str, span: Span) {
self.mark(id, span);
let at = self.extents.len();
self.extents.push(Extent {
id: id.to_string(),
first: span.line,
last: span.line,
parent: self.open.last().copied(),
depth: self.open.len(),
});
self.open.push(at);
}
pub fn rename(&mut self, from: &str, to: &str) {
let below = format!("{from}/");
for extent in self.extents.iter_mut().rev() {
if extent.id == from {
extent.id = to.to_string();
} else if let Some(rest) = extent.id.strip_prefix(&below) {
extent.id = format!("{to}/{rest}");
} else {
break;
}
}
self.origins.rename_prefix(from, to);
}
pub fn close(&mut self, last: Span) {
if let Some(at) = self.open.pop()
&& let Some(extent) = self.extents.get_mut(at)
{
extent.last = extent.last.max(last.line);
}
}
pub fn next_invariant(&mut self, kind: &str) -> String {
let count = self.invariants.entry(kind.to_string()).or_insert(0);
*count += 1;
ids::invariant(kind, *count)
}
pub fn finish(mut self, comments: &[Comment], indents: &HashMap<u32, u32>) -> (Policy, Origins, Vec<Diagnostic>) {
self.policy.notes = self.anchor_notes(comments, indents);
self.policy = std::mem::take(&mut self.policy).canonical();
let mut diagnostics = self.diagnostics;
diagnostics.sort_by_key(|d| d.location.as_ref().map(|at| (at.line, at.column)));
(self.policy, self.origins, capped(diagnostics, self.hidden))
}
fn anchor_notes(&self, comments: &[Comment], indents: &HashMap<u32, u32>) -> Vec<Note> {
let index = Index::new(&self.extents);
let mut notes = Vec::new();
let mut inlined: HashSet<String> = HashSet::new();
let mut at = 0;
while let Some(comment) = comments.get(at) {
if !comment.own_line {
at += 1;
let anchor = index
.inline_anchor(&self.extents, comment.span.line)
.or_else(|| index.own_line_anchor(&self.extents, comment.span.line, comment.span.line, false));
notes.extend(anchor.map(|(mut a, field)| {
if a.placement == Placement::Inline && (field.is_some() || !inlined.insert(a.element.clone())) {
a.placement = Placement::Inside;
}
self.note(comment, (a, field))
}));
continue;
}
let start = at;
let mut end = at;
while comments
.get(end + 1)
.is_some_and(|next| next.own_line && next.span.line == comments[end].span.line + 1)
{
end += 1;
}
let last = comments[end].span.line;
let mut from = start;
if self.language != Language::Blocks
&& let Some((p, next)) = index.glued_around(&self.extents, comments[start].span.line, last)
{
let indent_of = |at: usize| indents.get(&self.extents[at].first).copied().unwrap_or(1);
let indent = indent_of(p).max(next.map_or(0, indent_of));
while from <= end && comments[from].span.col > indent {
notes.push(self.note(&comments[from], anchor(&self.extents[p].id, Placement::Inside)));
from += 1;
}
}
if from <= end {
let anchor = index.own_line_anchor(&self.extents, comments[from].span.line, last, from > start);
for comment in &comments[from..=end] {
notes.extend(anchor.clone().map(|a| self.note(comment, a)));
}
}
at = end + 1;
}
notes
}
fn note(&self, comment: &Comment, (anchor, field): (NoteAnchor, Option<String>)) -> Note {
Note {
text: comment.text.clone(),
anchor,
origin: NoteOrigin {
file: self.file.to_string(),
language: self.language,
line: comment.span.line,
column: comment.span.col,
field,
},
}
}
}
type Anchored = (NoteAnchor, Option<String>);
struct Index {
starting: HashMap<u32, Vec<usize>>,
ending: HashMap<u32, Vec<usize>>,
children: Vec<Vec<usize>>,
}
impl Index {
fn new(extents: &[Extent]) -> Self {
let mut starting: HashMap<u32, Vec<usize>> = HashMap::new();
let mut ending: HashMap<u32, Vec<usize>> = HashMap::new();
let mut children = vec![Vec::new(); extents.len() + 1];
for (at, extent) in extents.iter().enumerate() {
starting.entry(extent.first).or_default().push(at);
ending.entry(extent.last).or_default().push(at);
children[extent.parent.unwrap_or(extents.len())].push(at);
}
Self {
starting,
ending,
children,
}
}
fn inline_anchor(&self, extents: &[Extent], line: u32) -> Option<Anchored> {
let deepest = |found: Option<&Vec<usize>>| {
found?
.iter()
.map(|at| &extents[*at])
.max_by_key(|e| (e.depth, std::cmp::Reverse(e.first)))
};
if let Some(extent) = deepest(self.starting.get(&line)) {
return Some(anchor(&extent.id, Placement::Inline));
}
deepest(self.ending.get(&line)).map(|e| anchor(&e.id, Placement::After))
}
fn container(&self, extents: &[Extent], first: u32, last: u32) -> Option<usize> {
let mut found = None;
let mut level = &self.children[extents.len()];
loop {
let below = level.partition_point(|at| extents[*at].first < first);
let Some(candidate) = below.checked_sub(1).map(|i| level[i]) else {
return found;
};
if extents[candidate].last <= last {
return found;
}
found = Some(candidate);
level = &self.children[candidate];
}
}
fn glued_around(&self, extents: &[Extent], first: u32, last: u32) -> Option<(usize, Option<usize>)> {
let container = self.container(extents, first, last);
let siblings = &self.children[container.unwrap_or(extents.len())];
let before = siblings.partition_point(|at| extents[*at].last < first);
let at = *siblings.get(before.checked_sub(1)?)?;
if extents[at].last + 1 != first {
return None;
}
let after = siblings.partition_point(|at| extents[*at].first <= last);
let next = siblings.get(after).copied().filter(|n| extents[*n].first == last + 1);
Some((at, next))
}
fn own_line_anchor(&self, extents: &[Extent], first: u32, last: u32, chained: bool) -> Option<Anchored> {
let container = self.container(extents, first, last);
let siblings = &self.children[container.unwrap_or(extents.len())];
let before = siblings.partition_point(|at| extents[*at].last < first);
let previous = before.checked_sub(1).map(|i| &extents[siblings[i]]);
let after = siblings.partition_point(|at| extents[*at].first <= last);
let next = siblings.get(after).map(|at| &extents[*at]);
let glued_above = chained || previous.is_some_and(|p| p.last + 1 == first);
let blank_below = next.is_none_or(|n| n.first != last + 1);
match (previous, next) {
(Some(p), _) if glued_above && blank_below => Some(anchor(&p.id, Placement::After)),
(_, Some(n)) => Some(anchor(&n.id, Placement::Before)),
(Some(p), None) => Some(anchor(&p.id, Placement::After)),
(None, None) => container
.and_then(|c| extents.get(c))
.map(|c| anchor(&c.id, Placement::Before)),
}
}
}
fn anchor(extent_id: &str, placement: Placement) -> Anchored {
let (element, field) = ids::split(extent_id);
(
NoteAnchor {
element: element.to_string(),
placement,
},
field.map(str::to_string),
)
}