Skip to main content

yomi_core/
assign_ids.rs

1//! Planning of automatic stable IDs (the core of `yomi assign-ids`; section 5.8 of `spec/host/05-texts.md`).
2//!
3//! Finds, with pure functions, which lines can get an ID and where to append it. Reading and writing files is up to the
4//! caller. The random generator used to make IDs is a seedable hand-written one ([`IdRng`]), passed as an argument.
5
6use 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
15/// The length of an automatic ID (without `#`).
16pub const AUTO_ID_LEN: usize = 6;
17
18/// The characters used in IDs (lowercase letters and digits).
19const ID_CHARS: &[u8; 36] = b"abcdefghijklmnopqrstuvwxyz0123456789";
20
21/// One line that can have an ID but has none.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct MissingId {
24    /// The name of the module.
25    pub module: String,
26    /// The name of the label it belongs to.
27    pub label: String,
28    /// The kind of line (`Plain`, `Quote`, `Choice` (the text of an option), `Command` (a line of a stop command)).
29    pub kind: StopKind,
30    /// The line (1-based) of the position to append `#id`.
31    pub line: u32,
32    /// The column (1-based, in Unicode scalar values) of the position to append `#id`.
33    pub col: u32,
34}
35
36impl Program {
37    /// Lines that can have a stable ID but have none (in script order).
38    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    /// The stable IDs already written in the given label (in script order).
53    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/// The random generator for IDs (xorshift64*; can be fixed by a seed; not cryptographic).
63#[derive(Debug, Clone)]
64pub struct IdRng {
65    state: u64,
66}
67
68impl IdRng {
69    /// Creates it from a seed (0 is replaced with another value).
70    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    /// The next 64 bits.
81    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    /// Makes 6 characters of `[a-z0-9]`.
91    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    /// Makes an ID not in `used` and adds it to `used`.
105    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/// One addition.
116#[derive(Debug, Clone, PartialEq, Eq)]
117pub struct Insertion {
118    /// The name of the module.
119    pub module: String,
120    /// The name of the label it belongs to.
121    pub label: String,
122    /// The kind of line.
123    pub kind: StopKind,
124    /// The line of the position (1-based).
125    pub line: u32,
126    /// The column of the position (1-based).
127    pub col: u32,
128    /// The byte offset of the position (from the start of the original source, including the BOM).
129    pub byte: usize,
130    /// The ID to add (without `#`).
131    pub id: String,
132    /// The text to append (including surrounding spaces).
133    pub text: String,
134}
135
136/// Converts a (line, column) of the source to a byte offset that includes the BOM.
137fn 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
154/// Collects and compiles the scripts, and finds the IDs to give to lines without one and where to append them.
155///
156/// If there are compile errors, returns the diagnostics (and adds nothing). However, if every error is **caused by a
157/// missing ID** (`once_without_id` for a `once` option without an ID, or `missing_text_id` when `require_text_ids` is
158/// enabled), those lines get IDs too. The scripts with the IDs added are compiled again, and the result is returned only
159/// after confirming there are no errors (if that cannot be confirmed, the diagnostics of that compilation are returned and
160/// nothing is added). IDs are unique within a label (they do not collide with IDs already written). The result is in
161/// module order, then position order.
162pub 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    // Confirm there are no other errors in the scripts with the IDs added (write nothing until confirmed)
179    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
197/// Whether there is at least one error and all of them would disappear by adding IDs (missing IDs).
198fn 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
208/// Finds the positions to append from a compiled program (the second half of `plan`).
209pub 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
217/// Finds the positions to append from the lines that can have IDs (`modules` are module names indexed by a line's `module`).
218fn plan_sites(
219    modules: &[String],
220    id_sites: &[IdSite],
221    sources: &[(&str, &str)],
222    rng: &mut IdRng,
223) -> Vec<Insertion> {
224    // Look up module names after normalizing to NFC, the same as compilation
225    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
273/// Applies the additions to a source (the original text is unchanged except where text is appended). `insertions` must
274/// all be for the same module (in any order).
275pub 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", &reg).unwrap();
313        let ins = plan(
314            &[("main", src)],
315            &reg,
316            &Default::default(),
317            &mut IdRng::new(1),
318        )
319        .unwrap();
320        let out = apply(src, &ins);
321        let after = compile(&out, "main", &reg).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}