use super::super::{Gap, PARSE_GAP, ROUTINE_GAP};
use super::{EmbeddedSqlCall, Positions, SqlFactSite, SqlStatementFileFacts};
use std::collections::{BTreeMap, BTreeSet};
#[derive(Default)]
pub(super) struct AlternativeGaps {
counts: BTreeMap<Gap, usize>,
}
impl AlternativeGaps {
pub(super) fn record(
&mut self,
call: &EmbeddedSqlCall,
variant_index: usize,
statement: &SqlStatementFileFacts,
observed: &mut BTreeSet<usize>,
) -> bool {
let truncated = call
.variants
.get(variant_index)
.is_some_and(|variant| variant.variants_truncated);
if truncated {
self.counts.insert(
(
call.line as usize,
"executor SQL alternatives are incomplete",
),
1,
);
}
let mut positions = None;
let mut parse_gaps = Vec::new();
for (site, line) in statement.parse_failure_sites() {
let error_line = match site {
SqlFactSite::ParseFailure(index) => statement.parse_failures[index].error_line,
_ => None,
};
let imported = statement
.variant_locations
.as_ref()
.and_then(|locations| locations.position(site))
.is_some_and(|position| position.source_path.is_some());
let line = if imported { call.line as usize } else { line };
let diagnostic_line = error_line.map_or(line, |error_line| {
positions
.get_or_insert_with(|| Positions::new(call, variant_index))
.source(error_line, 1)
.1
});
observed.insert(diagnostic_line);
parse_gaps.push((line, PARSE_GAP));
}
let routine_gaps = statement
.lock_inventory_unanalyzed
.iter()
.filter(|_| !truncated)
.map(|&line| {
let (_, line, _) = positions
.get_or_insert_with(|| Positions::new(call, variant_index))
.source(line, 1);
(line, ROUTINE_GAP)
});
let mut counts = BTreeMap::new();
for gap in parse_gaps
.into_iter()
.filter(|_| !truncated)
.chain(routine_gaps)
{
*counts.entry(gap).or_insert(0) += 1;
}
for (gap, count) in counts {
let previous = self.counts.entry(gap).or_default();
*previous = (*previous).max(count);
}
truncated || statement.parse_failed
}
pub(super) fn append_to(self, gaps: &mut Vec<Gap>) {
for (gap, count) in self.counts {
gaps.extend(std::iter::repeat_n(gap, count));
}
}
}