use std::collections::{HashMap, HashSet};
use crate::Program;
use crate::compile::{CompileOptions, compile_modules_with_options, compile_modules_with_sites};
use crate::diag::{DiagCode, Diagnostic, Severity};
use crate::ident::normalize_name;
use crate::program::{IdSite, StopKind};
use crate::registry::Registry;
pub const AUTO_ID_LEN: usize = 6;
const ID_CHARS: &[u8; 36] = b"abcdefghijklmnopqrstuvwxyz0123456789";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MissingId {
pub module: String,
pub label: String,
pub kind: StopKind,
pub line: u32,
pub col: u32,
}
impl Program {
pub fn missing_ids(&self) -> Vec<MissingId> {
self.id_sites
.iter()
.filter(|s| s.id.is_none())
.map(|s| MissingId {
module: self.modules[s.module as usize].clone(),
label: s.label.clone(),
kind: s.kind,
line: s.line,
col: s.col,
})
.collect()
}
pub fn written_ids(&self, module: &str, label: &str) -> Vec<&str> {
self.id_sites
.iter()
.filter(|s| self.modules[s.module as usize] == module && s.label == label)
.filter_map(|s| s.id.as_deref())
.collect()
}
}
#[derive(Debug, Clone)]
pub struct IdRng {
state: u64,
}
impl IdRng {
pub fn new(seed: u64) -> Self {
Self {
state: if seed == 0 {
0x9E37_79B9_7F4A_7C15
} else {
seed
},
}
}
pub fn next_u64(&mut self) -> u64 {
let mut x = self.state;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.state = x;
x.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
pub fn next_id(&mut self) -> String {
let mut out = String::with_capacity(AUTO_ID_LEN);
let mut v = self.next_u64();
for i in 0..AUTO_ID_LEN {
if i == 5 {
v = self.next_u64();
}
out.push(ID_CHARS[(v % 36) as usize] as char);
v /= 36;
}
out
}
pub fn unique_id(&mut self, used: &mut HashSet<String>) -> String {
loop {
let id = self.next_id();
if used.insert(id.clone()) {
return id;
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Insertion {
pub module: String,
pub label: String,
pub kind: StopKind,
pub line: u32,
pub col: u32,
pub byte: usize,
pub id: String,
pub text: String,
}
fn byte_of(source: &str, line: u32, col: u32) -> Option<usize> {
let bom = if source.starts_with('\u{feff}') { 3 } else { 0 };
let body = &source[bom..];
let mut start = 0usize;
for _ in 1..line {
start += body[start..].find('\n')? + 1;
}
let rest = &body[start..];
let mut off = 0usize;
let mut chars = rest.char_indices();
for _ in 1..col {
let (i, c) = chars.next()?;
off = i + c.len_utf8();
}
Some(bom + start + off)
}
pub fn plan(
sources: &[(&str, &str)],
registry: &Registry,
options: &CompileOptions,
rng: &mut IdRng,
) -> Result<Vec<Insertion>, Vec<Diagnostic>> {
let (result, failed_sites) = compile_modules_with_sites(sources, registry, options);
let diags = match result {
Ok((program, _)) => return Ok(plan_program(&program, sources, rng)),
Err(diags) => diags,
};
if !fixable_by_ids(&diags) {
return Err(diags);
}
let modules: Vec<String> = sources.iter().map(|(n, _)| normalize_name(n)).collect();
let plan = plan_sites(&modules, &failed_sites, sources, rng);
let applied: Vec<(String, String)> = sources
.iter()
.map(|(m, src)| {
let name = normalize_name(m);
let mine: Vec<Insertion> = plan.iter().filter(|i| i.module == name).cloned().collect();
((*m).to_string(), apply(src, &mine))
})
.collect();
let refs: Vec<(&str, &str)> = applied
.iter()
.map(|(m, s)| (m.as_str(), s.as_str()))
.collect();
match compile_modules_with_options(&refs, registry, options) {
Ok(_) => Ok(plan),
Err(again) => Err(again),
}
}
fn fixable_by_ids(diags: &[Diagnostic]) -> bool {
let mut errors = diags.iter().filter(|d| d.severity == Severity::Error);
let Some(first) = errors.next() else {
return false;
};
std::iter::once(first)
.chain(errors)
.all(|d| matches!(d.code, DiagCode::OnceWithoutId | DiagCode::MissingTextId))
}
pub fn plan_program(
program: &Program,
sources: &[(&str, &str)],
rng: &mut IdRng,
) -> Vec<Insertion> {
plan_sites(&program.modules, &program.id_sites, sources, rng)
}
fn plan_sites(
modules: &[String],
id_sites: &[IdSite],
sources: &[(&str, &str)],
rng: &mut IdRng,
) -> Vec<Insertion> {
let src: HashMap<String, &str> = sources
.iter()
.map(|(m, s)| (normalize_name(m), *s))
.collect();
let mut used: HashMap<(String, String), HashSet<String>> = HashMap::new();
let mut out = Vec::new();
for s in id_sites {
let module = &modules[s.module as usize];
let set = used.entry((module.clone(), s.label.clone())).or_default();
if let Some(id) = &s.id {
set.insert(id.clone());
}
}
for s in id_sites {
if s.id.is_some() {
continue;
}
let module = &modules[s.module as usize];
let Some(source) = src.get(module).copied() else {
continue;
};
let Some(byte) = byte_of(source, s.line, s.col) else {
continue;
};
let set = used
.get_mut(&(module.clone(), s.label.clone()))
.expect("登録済み");
let id = rng.unique_id(set);
let spaced = source[..byte].ends_with([' ', '\t']);
let text = match (s.kind, spaced) {
(StopKind::Choice, true) => format!("#{id} "),
(StopKind::Choice, false) => format!(" #{id} "),
_ => format!(" #{id}"),
};
out.push(Insertion {
module: module.clone(),
label: s.label.clone(),
kind: s.kind,
line: s.line,
col: s.col,
byte,
id,
text,
});
}
out
}
pub fn apply(source: &str, insertions: &[Insertion]) -> String {
let mut sorted: Vec<&Insertion> = insertions.iter().collect();
sorted.sort_by_key(|i| i.byte);
let mut out = String::with_capacity(source.len() + sorted.len() * 10);
let mut last = 0;
for i in sorted {
out.push_str(&source[last..i.byte]);
out.push_str(&i.text);
last = i.byte;
}
out.push_str(&source[last..]);
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Identity, Sugar, compile};
fn registry() -> Registry {
let mut r = Registry::new();
r.stop::<(String,), ()>("ui.say").unwrap();
r.stop::<(Option<Identity>, String), ()>("ui.say_as")
.unwrap();
r.stop::<(Vec<String>, Vec<Option<String>>), i64>("ui.choose")
.unwrap();
r.stop::<(f64,), ()>("flow.wait").unwrap();
r.bind(Sugar::Plain, "ui.say").unwrap();
r.bind(Sugar::Quote, "ui.say_as").unwrap();
r.bind(Sugar::Choice, "ui.choose").unwrap();
r
}
#[test]
fn position_hash_does_not_change_when_ids_are_added() {
let reg = registry();
let src = "identity 案内人 = \"案内人\"\nlabel start {\n あ \n 案内人「い」\n 「う\n え」\n @flow.wait(1.0)\n choice {\n 「は」 => jump start\n 「ひ」 once #h => jump start\n }\n}\n";
let before = compile(src, "main", ®).unwrap();
let ins = plan(
&[("main", src)],
®,
&Default::default(),
&mut IdRng::new(1),
)
.unwrap();
let out = apply(src, &ins);
let after = compile(&out, "main", ®).unwrap();
let key = |p: &Program| {
p.labels
.iter()
.flat_map(|l| {
l.stops.iter().map(|s| {
(
s.hash,
s.kind,
s.text.clone(),
s.line,
s.choice.as_ref().map(|c| c.options.len()),
)
})
})
.collect::<Vec<_>>()
};
assert_eq!(key(&before), key(&after));
assert!(!after.labels[0].stops.is_empty());
assert!(after.missing_ids().is_empty());
assert_eq!(after.written_ids("main", "start").len(), 6);
}
}