1use std::collections::{HashMap, HashSet};
7
8use crate::Program;
9use crate::compile::{CompileOptions, compile_modules_with_options, compile_modules_with_sites};
10use crate::diag::{DiagCode, Diagnostic, Severity};
11use crate::ident::normalize_name;
12use crate::program::{IdSite, StopKind};
13use crate::registry::Registry;
14
15pub const AUTO_ID_LEN: usize = 6;
17
18const ID_CHARS: &[u8; 36] = b"abcdefghijklmnopqrstuvwxyz0123456789";
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct MissingId {
24 pub module: String,
26 pub label: String,
28 pub kind: StopKind,
30 pub line: u32,
32 pub col: u32,
34}
35
36impl Program {
37 pub fn missing_ids(&self) -> Vec<MissingId> {
39 self.id_sites
40 .iter()
41 .filter(|s| s.id.is_none())
42 .map(|s| MissingId {
43 module: self.modules[s.module as usize].clone(),
44 label: s.label.clone(),
45 kind: s.kind,
46 line: s.line,
47 col: s.col,
48 })
49 .collect()
50 }
51
52 pub fn written_ids(&self, module: &str, label: &str) -> Vec<&str> {
54 self.id_sites
55 .iter()
56 .filter(|s| self.modules[s.module as usize] == module && s.label == label)
57 .filter_map(|s| s.id.as_deref())
58 .collect()
59 }
60}
61
62#[derive(Debug, Clone)]
64pub struct IdRng {
65 state: u64,
66}
67
68impl IdRng {
69 pub fn new(seed: u64) -> Self {
71 Self {
72 state: if seed == 0 {
73 0x9E37_79B9_7F4A_7C15
74 } else {
75 seed
76 },
77 }
78 }
79
80 pub fn next_u64(&mut self) -> u64 {
82 let mut x = self.state;
83 x ^= x >> 12;
84 x ^= x << 25;
85 x ^= x >> 27;
86 self.state = x;
87 x.wrapping_mul(0x2545_F491_4F6C_DD1D)
88 }
89
90 pub fn next_id(&mut self) -> String {
92 let mut out = String::with_capacity(AUTO_ID_LEN);
93 let mut v = self.next_u64();
94 for i in 0..AUTO_ID_LEN {
95 if i == 5 {
96 v = self.next_u64();
97 }
98 out.push(ID_CHARS[(v % 36) as usize] as char);
99 v /= 36;
100 }
101 out
102 }
103
104 pub fn unique_id(&mut self, used: &mut HashSet<String>) -> String {
106 loop {
107 let id = self.next_id();
108 if used.insert(id.clone()) {
109 return id;
110 }
111 }
112 }
113}
114
115#[derive(Debug, Clone, PartialEq, Eq)]
117pub struct Insertion {
118 pub module: String,
120 pub label: String,
122 pub kind: StopKind,
124 pub line: u32,
126 pub col: u32,
128 pub byte: usize,
130 pub id: String,
132 pub text: String,
134}
135
136fn byte_of(source: &str, line: u32, col: u32) -> Option<usize> {
138 let bom = if source.starts_with('\u{feff}') { 3 } else { 0 };
139 let body = &source[bom..];
140 let mut start = 0usize;
141 for _ in 1..line {
142 start += body[start..].find('\n')? + 1;
143 }
144 let rest = &body[start..];
145 let mut off = 0usize;
146 let mut chars = rest.char_indices();
147 for _ in 1..col {
148 let (i, c) = chars.next()?;
149 off = i + c.len_utf8();
150 }
151 Some(bom + start + off)
152}
153
154pub fn plan(
163 sources: &[(&str, &str)],
164 registry: &Registry,
165 options: &CompileOptions,
166 rng: &mut IdRng,
167) -> Result<Vec<Insertion>, Vec<Diagnostic>> {
168 let (result, failed_sites) = compile_modules_with_sites(sources, registry, options);
169 let diags = match result {
170 Ok((program, _)) => return Ok(plan_program(&program, sources, rng)),
171 Err(diags) => diags,
172 };
173 if !fixable_by_ids(&diags) {
174 return Err(diags);
175 }
176 let modules: Vec<String> = sources.iter().map(|(n, _)| normalize_name(n)).collect();
177 let plan = plan_sites(&modules, &failed_sites, sources, rng);
178 let applied: Vec<(String, String)> = sources
180 .iter()
181 .map(|(m, src)| {
182 let name = normalize_name(m);
183 let mine: Vec<Insertion> = plan.iter().filter(|i| i.module == name).cloned().collect();
184 ((*m).to_string(), apply(src, &mine))
185 })
186 .collect();
187 let refs: Vec<(&str, &str)> = applied
188 .iter()
189 .map(|(m, s)| (m.as_str(), s.as_str()))
190 .collect();
191 match compile_modules_with_options(&refs, registry, options) {
192 Ok(_) => Ok(plan),
193 Err(again) => Err(again),
194 }
195}
196
197fn fixable_by_ids(diags: &[Diagnostic]) -> bool {
199 let mut errors = diags.iter().filter(|d| d.severity == Severity::Error);
200 let Some(first) = errors.next() else {
201 return false;
202 };
203 std::iter::once(first)
204 .chain(errors)
205 .all(|d| matches!(d.code, DiagCode::OnceWithoutId | DiagCode::MissingTextId))
206}
207
208pub fn plan_program(
210 program: &Program,
211 sources: &[(&str, &str)],
212 rng: &mut IdRng,
213) -> Vec<Insertion> {
214 plan_sites(&program.modules, &program.id_sites, sources, rng)
215}
216
217fn plan_sites(
219 modules: &[String],
220 id_sites: &[IdSite],
221 sources: &[(&str, &str)],
222 rng: &mut IdRng,
223) -> Vec<Insertion> {
224 let src: HashMap<String, &str> = sources
226 .iter()
227 .map(|(m, s)| (normalize_name(m), *s))
228 .collect();
229 let mut used: HashMap<(String, String), HashSet<String>> = HashMap::new();
230 let mut out = Vec::new();
231 for s in id_sites {
232 let module = &modules[s.module as usize];
233 let set = used.entry((module.clone(), s.label.clone())).or_default();
234 if let Some(id) = &s.id {
235 set.insert(id.clone());
236 }
237 }
238 for s in id_sites {
239 if s.id.is_some() {
240 continue;
241 }
242 let module = &modules[s.module as usize];
243 let Some(source) = src.get(module).copied() else {
244 continue;
245 };
246 let Some(byte) = byte_of(source, s.line, s.col) else {
247 continue;
248 };
249 let set = used
250 .get_mut(&(module.clone(), s.label.clone()))
251 .expect("登録済み");
252 let id = rng.unique_id(set);
253 let spaced = source[..byte].ends_with([' ', '\t']);
254 let text = match (s.kind, spaced) {
255 (StopKind::Choice, true) => format!("#{id} "),
256 (StopKind::Choice, false) => format!(" #{id} "),
257 _ => format!(" #{id}"),
258 };
259 out.push(Insertion {
260 module: module.clone(),
261 label: s.label.clone(),
262 kind: s.kind,
263 line: s.line,
264 col: s.col,
265 byte,
266 id,
267 text,
268 });
269 }
270 out
271}
272
273pub fn apply(source: &str, insertions: &[Insertion]) -> String {
276 let mut sorted: Vec<&Insertion> = insertions.iter().collect();
277 sorted.sort_by_key(|i| i.byte);
278 let mut out = String::with_capacity(source.len() + sorted.len() * 10);
279 let mut last = 0;
280 for i in sorted {
281 out.push_str(&source[last..i.byte]);
282 out.push_str(&i.text);
283 last = i.byte;
284 }
285 out.push_str(&source[last..]);
286 out
287}
288
289#[cfg(test)]
290mod tests {
291 use super::*;
292 use crate::{Identity, Sugar, compile};
293
294 fn registry() -> Registry {
295 let mut r = Registry::new();
296 r.stop::<(String,), ()>("ui.say").unwrap();
297 r.stop::<(Option<Identity>, String), ()>("ui.say_as")
298 .unwrap();
299 r.stop::<(Vec<String>, Vec<Option<String>>), i64>("ui.choose")
300 .unwrap();
301 r.stop::<(f64,), ()>("flow.wait").unwrap();
302 r.bind(Sugar::Plain, "ui.say").unwrap();
303 r.bind(Sugar::Quote, "ui.say_as").unwrap();
304 r.bind(Sugar::Choice, "ui.choose").unwrap();
305 r
306 }
307
308 #[test]
309 fn position_hash_does_not_change_when_ids_are_added() {
310 let reg = registry();
311 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";
312 let before = compile(src, "main", ®).unwrap();
313 let ins = plan(
314 &[("main", src)],
315 ®,
316 &Default::default(),
317 &mut IdRng::new(1),
318 )
319 .unwrap();
320 let out = apply(src, &ins);
321 let after = compile(&out, "main", ®).unwrap();
322 let key = |p: &Program| {
323 p.labels
324 .iter()
325 .flat_map(|l| {
326 l.stops.iter().map(|s| {
327 (
328 s.hash,
329 s.kind,
330 s.text.clone(),
331 s.line,
332 s.choice.as_ref().map(|c| c.options.len()),
333 )
334 })
335 })
336 .collect::<Vec<_>>()
337 };
338 assert_eq!(key(&before), key(&after));
339 assert!(!after.labels[0].stops.is_empty());
340 assert!(after.missing_ids().is_empty());
341 assert_eq!(after.written_ids("main", "start").len(), 6);
342 }
343}