Skip to main content

yomi_core/
schema_file.rs

1//! Frozen schema files (`yomi schema freeze`, `yomi schema extract`) and the template of `migrate` blocks
2//! (`yomi migrate-init`); sections 7.3 and 6.14 of the spec.
3
4use std::collections::BTreeMap;
5
6use crate::diag::{Diagnostic, Severity};
7use crate::program::Program;
8use crate::syntax::parser::schema::{fnv1a_bytes, parse_schema_file};
9use crate::type_expand::Expander;
10use crate::vm::{LoadError, persistent, save};
11
12/// The schema inside a save or persistent data.
13pub(crate) struct Embedded {
14    pub version: u32,
15    pub types: Vec<(String, String)>,
16    /// The script variables (`module.variable`, type).
17    pub var_types: Vec<(String, String)>,
18}
19
20/// A variable of a schema.
21struct Var {
22    name: String,
23    persistent: bool,
24    ty: String,
25}
26
27fn split_name(name: &str) -> (&str, &str) {
28    name.rsplit_once('.').unwrap_or(("", name))
29}
30
31/// `struct { a: int }` of the type `game.Item` becomes `struct Item { a: int }`.
32fn declaration(name: &str, signature: &str) -> String {
33    let (kind, rest) = signature.split_once(' ').unwrap_or((signature, ""));
34    format!("{kind} {} {rest}", split_name(name).1)
35}
36
37/// The declarations and the variables of one module (`name`, text).
38type ModuleItems<'a> = (Vec<(&'a str, String)>, Vec<(&'a str, String)>);
39
40/// Writes a frozen schema file (7.3). `types` are `(module.Type, shape)`.
41fn render(version: u32, types: &[(String, String)], vars: &[Var]) -> String {
42    let mut modules: BTreeMap<&str, ModuleItems<'_>> = BTreeMap::new();
43    for (name, sig) in types {
44        let (module, short) = split_name(name);
45        modules
46            .entry(module)
47            .or_default()
48            .0
49            .push((short, declaration(name, sig)));
50    }
51    for v in vars {
52        let (module, short) = split_name(&v.name);
53        let kind = if v.persistent { "persistent" } else { "save" };
54        modules
55            .entry(module)
56            .or_default()
57            .1
58            .push((short, format!("{kind} var {short}: {}", v.ty)));
59    }
60    let mut body = String::from("\n");
61    for (module, (mut decls, mut vars)) in modules {
62        decls.sort();
63        vars.sort();
64        body.push_str(&format!("module {module} {{\n"));
65        for (_, text) in decls.iter().chain(&vars) {
66            body.push_str(&format!("    {text}\n"));
67        }
68        body.push_str("}\n");
69    }
70    format!(
71        "schema {version} hash \"{:016x}\"\n{body}",
72        fnv1a_bytes(body.as_bytes())
73    )
74}
75
76fn program_vars(program: &Program) -> Vec<Var> {
77    program
78        .globals
79        .iter()
80        .map(|g| Var {
81            name: format!("{}.{}", program.modules[g.module as usize], g.name),
82            persistent: g.persistent,
83            ty: g.ty.name(),
84        })
85        .collect()
86}
87
88fn program_types(program: &Program) -> Vec<(String, String)> {
89    program
90        .types
91        .iter()
92        .map(|t| (t.name.clone(), t.signature()))
93        .collect()
94}
95
96/// The content of `schema/vN.yomi` for the current scripts (`N` is [`Program::schema_version`]).
97pub fn frozen_schema(program: &Program) -> String {
98    render(
99        program.schema_version(),
100        &program_types(program),
101        &program_vars(program),
102    )
103}
104
105/// Why the schema could not be taken out of a save.
106#[non_exhaustive]
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub enum ExtractError {
109    /// Neither a save nor persistent data was given.
110    NothingGiven,
111    /// The bytes cannot be read (bad magic, old format version, bad checksum, ...).
112    Load(LoadError),
113    /// The save and the persistent data have different schema versions.
114    VersionsDiffer {
115        /// The schema version of the save.
116        save: u32,
117        /// The schema version of the persistent data.
118        persistent: u32,
119    },
120}
121
122/// Rebuilds the content of a frozen schema file from the schema embedded in a save and/or persistent data. The version in
123/// the header is the schema version of the save.
124pub fn extract_schema(
125    save: Option<&[u8]>,
126    persistent: Option<&[u8]>,
127) -> Result<String, ExtractError> {
128    let s = save
129        .map(save::embedded_schema)
130        .transpose()
131        .map_err(ExtractError::Load)?;
132    let p = persistent
133        .map(persistent::embedded_schema)
134        .transpose()
135        .map_err(ExtractError::Load)?;
136    let (version, mut types, mut vars) = match (&s, &p) {
137        (None, None) => return Err(ExtractError::NothingGiven),
138        (Some(s), Some(p)) if s.version != p.version => {
139            return Err(ExtractError::VersionsDiffer {
140                save: s.version,
141                persistent: p.version,
142            });
143        }
144        (Some(s), _) => (s.version, Vec::new(), Vec::new()),
145        (None, Some(p)) => (p.version, Vec::new(), Vec::new()),
146    };
147    for (e, is_persistent) in [(&s, false), (&p, true)] {
148        let Some(e) = e else { continue };
149        for t in &e.types {
150            if !types.contains(t) {
151                types.push(t.clone());
152            }
153        }
154        vars.extend(e.var_types.iter().map(|(name, ty)| Var {
155            name: name.clone(),
156            persistent: is_persistent,
157            ty: ty.clone(),
158        }));
159    }
160    Ok(render(version, &types, &vars))
161}
162
163/// Writes the type with the names of its declared types prefixed by `v<version>::`.
164fn prefixed(ty: &str, version: u32, decls: &[(String, String)]) -> String {
165    let mut out = String::new();
166    let mut token = String::new();
167    let flush = |token: &mut String, out: &mut String| {
168        if decls.iter().any(|(n, _)| n == token) {
169            out.push_str(&format!("v{version}::"));
170        }
171        out.push_str(token);
172        token.clear();
173    };
174    for c in ty.chars() {
175        if c.is_alphanumeric() || c == '_' || c == '.' || c == ':' {
176            token.push(c);
177        } else {
178            flush(&mut token, &mut out);
179            out.push(c);
180        }
181    }
182    flush(&mut token, &mut out);
183    out
184}
185
186/// The `migrate` block that `yomi migrate-init` makes from the latest frozen schema (`frozen`, the content of
187/// `schema/v<version>.yomi`) and the current scripts: every line inside is a comment (candidates for `rename` and
188/// `convert`). `None` if the variables did not change. If the frozen schema cannot be read, its diagnostics.
189pub fn migrate_template(
190    program: &Program,
191    frozen: &str,
192    version: u32,
193) -> Result<Option<String>, Vec<Diagnostic>> {
194    let module = format!("schema/v{version}");
195    let (ast, diags) = parse_schema_file(frozen, &module, &format!("{module}.yomi"));
196    if diags.iter().any(|d| d.severity == Severity::Error) {
197        return Err(diags);
198    }
199    let mut old_types: Vec<(String, String)> = Vec::new();
200    let mut old_vars: Vec<Var> = Vec::new();
201    for m in &ast.modules {
202        for t in &m.types {
203            old_types.push((
204                format!("{}.{}", m.path, t.name),
205                crate::compile::signature_of(&t.kind),
206            ));
207        }
208        for v in &m.vars {
209            old_vars.push(Var {
210                name: format!("{}.{}", m.path, v.name),
211                persistent: v.persistent,
212                ty: crate::syntax::canon::ty(&v.ty),
213            });
214        }
215    }
216    let new_types = program_types(program);
217    let new_vars = program_vars(program);
218    let old_x = Expander::new(&old_types);
219    let new_x = Expander::new(&new_types);
220    let mut lines: Vec<String> = Vec::new();
221    let removed: Vec<&Var> = old_vars
222        .iter()
223        .filter(|o| !new_vars.iter().any(|n| n.name == o.name))
224        .collect();
225    let added: Vec<&Var> = new_vars
226        .iter()
227        .filter(|n| !old_vars.iter().any(|o| o.name == n.name))
228        .collect();
229    for r in &removed {
230        for a in &added {
231            if r.persistent == a.persistent && old_x.expand(&r.ty) == new_x.expand(&a.ty) {
232                lines.push(format!("// rename v{version}::{} -> {}", r.name, a.name));
233            }
234        }
235    }
236    for o in &old_vars {
237        let Some(n) = new_vars.iter().find(|n| n.name == o.name) else {
238            continue;
239        };
240        if o.persistent == n.persistent && old_x.expand(&o.ty) != new_x.expand(&n.ty) {
241            lines.push(format!(
242                "// convert v{version}::{}: {} -> {} = |v| v",
243                o.name,
244                prefixed(&o.ty, version, &old_types),
245                n.ty
246            ));
247        }
248    }
249    let differs = !removed.is_empty() || !added.is_empty() || !lines.is_empty();
250    if !differs {
251        return Ok(None);
252    }
253    let mut out = format!("migrate {} {{\n", version + 1);
254    for l in lines {
255        out.push_str(&format!("    {l}\n"));
256    }
257    out.push_str("}\n");
258    Ok(Some(out))
259}