sokf_core/model/extends.rs
1//! This module resolves the `extends` of each store's manifest, the chain of
2//! stores whose schemas a store inherits, and the schema that governs a type
3//! in a store through that chain (`SOKF_SCHEMA_96`, `SOKF_SCHEMA_97`). It
4//! also rebases the paths of an inherited schema onto the inheriting store
5//! (`SOKF_SCHEMA_98`).
6
7use super::{Identity, Knowledge, Model, Query, SchemaRef};
8use crate::RepoPath;
9
10/// A `Broken` says why the `extends` of a store's manifest gives the store
11/// no chain (`SOKF_FORMAT_206`, `SOKF_FORMAT_207`).
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum Broken {
14 /// The `extends` names no knowledge store of the repository. The
15 /// variant holds the value as written.
16 NoStore(String),
17 /// The `extends` names an identity that more than one store holds. The
18 /// variant holds the value as written.
19 Shared(String),
20 /// The chain of `extends` from the store comes back to the store.
21 Cycle,
22}
23
24/// `Chains` holds, for each store, its chain of `extends` and why it has
25/// none, resolved once when the model is built.
26#[derive(Debug, Clone, Default)]
27pub struct Chains {
28 /// The chain of each store: the store itself, the store that it
29 /// extends, and so on. A chain stops at a store that extends nothing, at
30 /// a broken store, which inherits nothing, and before a store that it
31 /// already holds, so a broken store's chain holds only itself
32 /// (FORMAT-5_AC-10).
33 pub chains: Vec<Vec<usize>>,
34 /// Why each store's `extends` is broken, or `None` (`broken`).
35 pub broken: Vec<Option<Broken>>,
36}
37
38impl Chains {
39 /// `of` resolves the chain of every store of `knowledges`.
40 pub fn of(knowledges: &[Knowledge]) -> Self {
41 let broken: Vec<Option<Broken>> = (0..knowledges.len())
42 .map(|k| broken(knowledges, k))
43 .collect();
44 let chains = (0..knowledges.len())
45 .map(|k| {
46 let mut chain = vec![k];
47 let mut at = k;
48 while broken[at].is_none() {
49 match parent_of(knowledges, at) {
50 Ok(Some(p)) if !chain.contains(&p) => {
51 chain.push(p);
52 at = p;
53 }
54 _ => break,
55 }
56 }
57 chain
58 })
59 .collect();
60 Chains { chains, broken }
61 }
62}
63
64/// `parent_of` returns the store that the manifest of store `k` names in
65/// `extends`, or `None` when the manifest names none. It looks the
66/// identity up among the current identities first, then the former ones,
67/// and resolves to nothing when two stores share it.
68pub(crate) fn parent_of(knowledges: &[Knowledge], k: usize) -> Result<Option<usize>, Broken> {
69 let Some(written) = knowledges[k]
70 .manifest
71 .as_ref()
72 .and_then(|m| m.extends.as_deref())
73 else {
74 return Ok(None);
75 };
76 let wanted = Identity::parse(written).ok_or_else(|| Broken::NoStore(written.to_string()))?;
77 let (hits, _) = super::stores::matching_in(knowledges, |i| *i == wanted);
78 match hits.as_slice() {
79 [one] => Ok(Some(*one)),
80 [] => Err(Broken::NoStore(written.to_string())),
81 _ => Err(Broken::Shared(written.to_string())),
82 }
83}
84
85/// `broken` returns why store `k` has no chain: its `extends` names no
86/// store, or the chain from it comes back to it. It returns `None` for a
87/// store whose `extends` resolves, or that has none.
88pub(crate) fn broken(knowledges: &[Knowledge], k: usize) -> Option<Broken> {
89 let mut seen = vec![k];
90 let mut at = k;
91 loop {
92 match parent_of(knowledges, at) {
93 Err(b) if at == k => return Some(b),
94 Ok(Some(p)) if p == k => return Some(Broken::Cycle),
95 Ok(Some(p)) if !seen.contains(&p) => {
96 seen.push(p);
97 at = p;
98 }
99 _ => return None,
100 }
101 }
102}
103
104/// `claimants_in` returns the schemas that govern `type_name` in the store
105/// whose chain is `chain`: the store's own schemas of the type, or else
106/// those of the nearest store of its chain that holds one
107/// (`SOKF_SCHEMA_96`, `SOKF_SCHEMA_97`). A schema of additional files
108/// dispatches on no type, so no store inherits it (`SOKF_SCHEMA_99`).
109/// `visit` sees each store that the lookup reads.
110// sokf-implements: SOKF_SCHEMA_99
111// sokf-implements: FORMAT-5_AC-7
112pub(crate) fn claimants_in(
113 knowledges: &[Knowledge],
114 chain: &[usize],
115 type_name: &str,
116 visit: &mut dyn FnMut(usize),
117) -> Vec<SchemaRef> {
118 for &s in chain {
119 visit(s);
120 let own = knowledges[s].schemas_for(type_name);
121 if !own.is_empty() {
122 return own
123 .iter()
124 .map(|&index| SchemaRef {
125 knowledge: s,
126 index,
127 })
128 .collect();
129 }
130 }
131 Vec::new()
132}
133
134/// `inherited_in` returns each schema that store `k` inherits: for each
135/// type that no store nearer in the chain declares, every schema of the
136/// type in the nearest store that declares it.
137pub(crate) fn inherited_in(knowledges: &[Knowledge], chain: &[usize]) -> Vec<SchemaRef> {
138 let k = chain[0];
139 let mut declared: std::collections::BTreeSet<&str> = knowledges[k]
140 .schemas_by_type
141 .keys()
142 .map(String::as_str)
143 .collect();
144 let mut found = Vec::new();
145 for &s in &chain[1..] {
146 let mut types: Vec<(&String, &Vec<usize>)> = knowledges[s].schemas_by_type.iter().collect();
147 types.sort();
148 let mut here = Vec::new();
149 for (t, indexes) in types {
150 if declared.contains(t.as_str()) {
151 continue;
152 }
153 here.push(t.as_str());
154 found.extend(indexes.iter().map(|&index| SchemaRef {
155 knowledge: s,
156 index,
157 }));
158 }
159 declared.extend(here);
160 }
161 found
162}
163
164/// `rebase` returns `path`, a path or a glob of a schema in the store at
165/// `from`, at the same place under the store at `to`, when it lies under
166/// `from`, and unchanged otherwise (`SOKF_SCHEMA_98`).
167// sokf-implements: SOKF_SCHEMA_98
168// sokf-implements: FORMAT-5_AC-6
169pub fn rebase(path: &str, from: &RepoPath, to: &RepoPath) -> String {
170 let from = from.as_str().trim_end_matches('/');
171 let to = to.as_str().trim_end_matches('/');
172 match path.strip_prefix(from) {
173 Some(rest) if rest.is_empty() || rest.starts_with('/') => format!("{to}{rest}"),
174 _ => path.to_string(),
175 }
176}
177
178impl Model {
179 /// `own_roots` returns the number of own stores, those of
180 /// `knowledge.roots`, which come before the registered ones
181 /// (CLI-6_AC-116).
182 pub fn own_roots(&self) -> usize {
183 self.knowledges.len() - self.tree.registered_count.min(self.knowledges.len())
184 }
185
186 /// `broken` returns why store `k` has no chain of `extends`, or `None`
187 /// when it has one.
188 pub fn broken(&self, k: usize) -> Option<&Broken> {
189 self.chains.broken.get(k)?.as_ref()
190 }
191
192 /// `in_broken_store` returns whether `path` lies in a store whose
193 /// `extends` is broken, whose files no check and no fix touches
194 /// (FORMAT-5_AC-10).
195 pub fn in_broken_store(&self, path: &RepoPath) -> bool {
196 self.knowledge_of(path)
197 .is_some_and(|k| self.broken(k).is_some())
198 }
199
200 /// `inherited` returns each schema that store `k` inherits.
201 pub fn inherited(&self, k: usize) -> Vec<SchemaRef> {
202 inherited_in(&self.knowledges, &self.chains.chains[k])
203 }
204
205 /// `claimants` returns the schemas that govern `type_name` in store `k`,
206 /// through the chain of `extends`. It records the schema query of each
207 /// store that it reads, so that a schema that a store of the chain
208 /// adds, removes, or changes makes the reader dirty (CACHE-1_AC-15).
209 pub fn claimants(&self, k: usize, type_name: &str) -> Vec<SchemaRef> {
210 let Some(chain) = self.chains.chains.get(k) else {
211 return Vec::new();
212 };
213 claimants_in(&self.knowledges, chain, type_name, &mut |s| {
214 self.note(Query::Schema {
215 knowledge: s,
216 key: type_name.to_string(),
217 });
218 })
219 }
220
221 /// `declares` returns whether store `k` declares `type_name`, in a
222 /// schema of its own or in one that it inherits (CLI-6_AC-117).
223 pub fn declares(&self, k: usize, type_name: &str) -> bool {
224 !self.claimants(k, type_name).is_empty()
225 }
226}
227
228#[cfg(test)]
229mod tests {
230 use super::*;
231
232 fn p(s: &str) -> RepoPath {
233 RepoPath::parse(s).unwrap()
234 }
235
236 #[test]
237 fn rebases_a_path_under_the_schema_store_only() {
238 let (from, to) = (p("/knowledge"), p("/packs/login"));
239 assert_eq!(
240 rebase("/knowledge/contracts", &from, &to),
241 "/packs/login/contracts"
242 );
243 assert_eq!(rebase("/knowledge", &from, &to), "/packs/login");
244 assert_eq!(
245 rebase("/knowledge/json/**/*.schema.json", &from, &to),
246 "/packs/login/json/**/*.schema.json"
247 );
248 assert_eq!(rebase("/knowledgebase/x", &from, &to), "/knowledgebase/x");
249 assert_eq!(rebase("/elsewhere", &from, &to), "/elsewhere");
250 }
251}