use super::super::sentinel;
use super::super::split::coordinate;
use super::super::summary::ImportedSite;
use crate::embedded::placeholders::{internal_placeholder, publish_placeholders_with_positions};
use crate::embedded::walk::{
resolve::has_known_leading_statement, scope::has_diagnostic_leading_statement,
};
use std::ops::Range;
pub(super) fn publish(text: &str, sites: &[ImportedSite]) -> (String, Vec<(u32, u32)>) {
let holes = sentinel::find_all(text);
if holes.is_empty() {
return (text.to_string(), Vec::new());
}
let mut out = String::with_capacity(text.len());
let mut cursor = 0;
for (index, (range, site)) in holes.iter().enumerate() {
out.push_str(&text[cursor..range.start]);
if fragment_gap(text, range, sites.get(*site)) {
return if has_diagnostic_leading_statement(&out) {
publish_placeholders_with_positions(out)
} else {
(String::new(), Vec::new())
};
}
out.push_str(&internal_placeholder(index + 1));
cursor = range.end;
}
out.push_str(&text[cursor..]);
publish_placeholders_with_positions(out)
}
fn fragment_gap(text: &str, range: &Range<usize>, site: Option<&ImportedSite>) -> bool {
let Some(site) = site else {
return false;
};
if sentinel::in_identifier_slot(text, range.start) || value_operand(text, range.start) {
return false;
}
match site.constant {
Some(true) => true,
Some(false) => false,
None => site.member.is_none(),
}
}
fn value_operand(text: &str, hole_start: usize) -> bool {
text[..hole_start].trim_end().ends_with('=')
}
pub(super) fn trimmed_prefix(text: &str) -> Option<(String, (u32, u32))> {
let prefix = sentinel::prefix(text);
let kept = keep_prefix(text)?;
Some((kept, coordinate(text, prefix.len())))
}
fn keep_prefix(text: &str) -> Option<String> {
let prefix = sentinel::prefix(text);
has_known_leading_statement(prefix).then(|| prefix.to_string())
}