Skip to main content

sokf_core/model/
knowledge.rs

1//! This module defines `Knowledge` and `Model`, which index the parsed tree.
2
3use std::collections::{BTreeMap, BTreeSet, HashMap};
4
5use super::{
6    AdditionalFile, Asset, Document, Fallback, IndexFile, Manifest, Query, Recorder,
7    SchemaDocument, SchemaRef,
8};
9use crate::{FileKind, Finding, RepoPath, Tree};
10
11// sokf:begin knowledge
12/// A `Knowledge` is one knowledge store.
13#[derive(Debug)]
14pub struct Knowledge {
15    /// The root directory.
16    pub root: RepoPath,
17    /// The manifest, when the manifest file exists.
18    pub manifest: Option<Manifest>,
19    /// The path of the manifest.
20    pub manifest_path: RepoPath,
21    /// The schemas, by path.
22    pub schemas: Vec<SchemaDocument>,
23    /// The documents, by path.
24    pub documents: Vec<Document>,
25    /// The index files, by path.
26    pub indexes: Vec<IndexFile>,
27    /// The assets, by path (FORMAT-1_AC-1).
28    pub assets: Vec<Asset>,
29    /// The documents, by `id`. An id that more than one document has is a
30    /// duplicate.
31    pub by_id: HashMap<String, Vec<usize>>,
32    /// The documents, by path.
33    pub by_path: HashMap<RepoPath, usize>,
34    /// The documents, by `type`.
35    pub by_type: HashMap<String, Vec<usize>>,
36    /// The schemas, by the type that each one dispatches on.
37    pub schemas_by_type: HashMap<String, Vec<usize>>,
38    /// The assets, by path.
39    pub asset_by_path: HashMap<RepoPath, usize>,
40    /// The assets, by the path of their sidecar.
41    pub asset_of_sidecar: HashMap<RepoPath, usize>,
42}
43// sokf:end knowledge
44
45impl Knowledge {
46    /// `insert_document` adds a document to the store and indexes it by id,
47    /// type, and path. When the document is the sidecar of an asset, it
48    /// also pairs the asset with it.
49    pub(super) fn insert_document(&mut self, doc: Document) {
50        let index = self.documents.len();
51        if let Some(id) = doc.id() {
52            self.by_id.entry(id.to_string()).or_default().push(index);
53        }
54        if let Some(t) = doc.type_name() {
55            self.by_type.entry(t.to_string()).or_default().push(index);
56        }
57        self.by_path.insert(doc.path.clone(), index);
58        if let Some(&a) = self.asset_of_sidecar.get(&doc.path) {
59            self.assets[a].sidecar = Some(index);
60        }
61        self.documents.push(doc);
62    }
63
64    /// `document` returns the document with `id`, when exactly one document
65    /// has it. A schema is a document of type `Schema`, so `document`
66    /// resolves the id of a schema too.
67    pub fn document(&self, id: &str) -> Option<&Document> {
68        if self.ids(id).len() != 1 {
69            return None;
70        }
71        match self.by_id.get(id).map(Vec::as_slice) {
72            Some([one]) => Some(&self.documents[*one]),
73            _ => self.schema_by_id(id).map(|i| &self.schemas[i].doc),
74        }
75    }
76
77    /// `ids` returns the path of every document and schema that has `id`.
78    pub fn ids(&self, id: &str) -> Vec<&RepoPath> {
79        let mut paths: Vec<&RepoPath> = self
80            .by_id
81            .get(id)
82            .into_iter()
83            .flatten()
84            .map(|&i| &self.documents[i].path)
85            .collect();
86        paths.extend(
87            self.schemas
88                .iter()
89                .filter(|s| s.doc.id() == Some(id))
90                .map(|s| &s.doc.path),
91        );
92        paths
93    }
94
95    /// `documents_of` returns the documents of type `type_name`.
96    pub fn documents_of(&self, type_name: &str) -> impl Iterator<Item = &Document> {
97        self.by_type
98            .get(type_name)
99            .into_iter()
100            .flatten()
101            .map(|&i| &self.documents[i])
102    }
103
104    /// `schemas_for` returns the indexes of the schemas that dispatch on
105    /// `type_name`.
106    pub fn schemas_for(&self, type_name: &str) -> &[usize] {
107        self.schemas_by_type
108            .get(type_name)
109            .map(Vec::as_slice)
110            .unwrap_or_default()
111    }
112
113    /// `is_document` reports whether `path` is a document of this knowledge
114    /// store, schemas included.
115    pub fn is_document(&self, path: &RepoPath) -> bool {
116        self.by_path.contains_key(path) || self.schemas.iter().any(|s| &s.doc.path == path)
117    }
118
119    /// `asset_of` returns the asset that the document at `sidecar`
120    /// describes, if there is one.
121    pub fn asset_of(&self, sidecar: &RepoPath) -> Option<&Asset> {
122        self.asset_of_sidecar.get(sidecar).map(|&i| &self.assets[i])
123    }
124
125    /// `asset_at` returns the asset at `path`, if there is one.
126    pub fn asset_at(&self, path: &RepoPath) -> Option<&Asset> {
127        self.asset_by_path.get(path).map(|&i| &self.assets[i])
128    }
129
130    /// `schema_key` returns the key of schema `i`. The key is the value of
131    /// the schema's `type` const. A schema that has no such const
132    /// dispatches only by its globs, and its key is its path (CACHE-1_AC-15).
133    pub fn schema_key(&self, i: usize) -> String {
134        let s = &self.schemas[i];
135        s.type_const
136            .clone()
137            .unwrap_or_else(|| s.doc.path.to_string())
138    }
139
140    /// `schema_by_id` returns the index of the schema with `id`, when exactly
141    /// one schema has it.
142    pub fn schema_by_id(&self, id: &str) -> Option<usize> {
143        let mut found = self
144            .schemas
145            .iter()
146            .enumerate()
147            .filter(|(_, s)| s.id() == id);
148        let first = found.next()?;
149        found.next().is_none().then_some(first.0)
150    }
151}
152
153// sokf:begin model
154/// A `Model` holds every knowledge store, every additional file, and the tree.
155#[derive(Debug)]
156pub struct Model {
157    /// The knowledge stores, in configuration order.
158    pub knowledges: Vec<Knowledge>,
159    /// The additional files that the run has loaded, by path.
160    pub additional: Vec<AdditionalFile>,
161    /// Each additional file that a schema's globs match, by path, whether the
162    /// run has loaded it or not. The value is the schema whose glob matches
163    /// the file, or none when the globs of more than one schema match it
164    /// (CACHE-1_AC-15).
165    pub dispatch: BTreeMap<RepoPath, Option<SchemaRef>>,
166    /// The walked tree.
167    pub tree: Tree,
168    /// The findings of the build, such as files that fail to load and globs
169    /// that clash.
170    pub problems: Vec<Finding>,
171    /// The reads of the run. The recorder keeps each query that the check of
172    /// a file makes, under the path of that file (CACHE-1_AC-4).
173    pub reads: Recorder,
174    /// The cache. It supplies facts about the documents that the run did not
175    /// load (CACHE-1_AC-21).
176    pub fallback: Option<Box<dyn Fallback>>,
177    /// The markers of each file outside the knowledge roots that the run has
178    /// loaded, by path. The markers come from a scan of the file, or from the
179    /// rows that the cache keeps for it.
180    pub markers: BTreeMap<RepoPath, Vec<crate::markers::MarkerRow>>,
181    /// What the run does with markers. It is `Off` until a check sets it.
182    pub marker_check: crate::MarkerCheck,
183    /// `plans` holds the files that the documents plan (`SOKF_SCHEMA_53`).
184    pub plans: super::PlanIndex,
185    /// `chains` holds the chain of `extends` of each store, resolved when
186    /// the model is built (`SOKF_SCHEMA_96`).
187    pub chains: super::extends::Chains,
188    /// `history` holds the history of git, which the model opens when the
189    /// first check of a `verified` entry asks for it.
190    pub(crate) history: std::cell::OnceCell<crate::history::History>,
191}
192// sokf:end model
193
194/// A `Located` is what a path is in the model, together with the index of
195/// the knowledge store, for a file of a knowledge store.
196#[derive(Debug, Clone, Copy, PartialEq)]
197pub enum Located<'a> {
198    /// A document of a knowledge store.
199    Document(usize, &'a Document),
200    /// A schema of a knowledge store.
201    Schema(usize, &'a SchemaDocument),
202    /// An additional file.
203    Additional(&'a AdditionalFile),
204    /// An index file of a knowledge store.
205    Index(usize, &'a IndexFile),
206    /// An asset of a knowledge store.
207    Asset(usize, &'a Asset),
208}
209
210impl Model {
211    /// `history` returns the history of git of the repository, which it
212    /// opens on the first call of the run.
213    pub(crate) fn history(&self) -> &crate::history::History {
214        self.history
215            .get_or_init(|| crate::history::History::open(&self.tree.root))
216    }
217
218    /// `watch` records every later read against `reader`.
219    pub fn watch(&self, reader: &RepoPath) {
220        self.reads.borrow_mut().watch(reader);
221    }
222
223    /// `unwatch` stops recording reads against any reader.
224    pub fn unwatch(&self) {
225        self.reads.borrow_mut().unwatch();
226    }
227
228    /// `note` records `query` against the watched reader.
229    pub fn note(&self, query: Query) {
230        self.reads.borrow_mut().note(query);
231    }
232
233    /// `reads_of` returns the queries that `reader` made.
234    pub fn reads_of(&self, reader: &RepoPath) -> BTreeSet<Query> {
235        self.reads.borrow().of(reader)
236    }
237
238    /// `reads` returns the queries of every reader.
239    pub fn reads(&self) -> BTreeMap<RepoPath, BTreeSet<Query>> {
240        self.reads.borrow().all().clone()
241    }
242
243    /// `document` returns the document with `id` in `knowledge`, when the run
244    /// has loaded it. Before the checks run, the run loads every document
245    /// that a check looks up. If only the cache knows a document, the run
246    /// failed to load it, so a debug build stops with an assertion failure.
247    pub fn document(&self, knowledge: usize, id: &str) -> Option<&Document> {
248        self.note(Query::Doc {
249            knowledge,
250            id: id.to_string(),
251        });
252        let found = self.knowledges.get(knowledge)?.document(id);
253        debug_assert!(
254            found.is_some() || self.ids(knowledge, id).len() != 1 || cfg!(not(debug_assertions)),
255            "the run has not loaded the document `{id}` of knowledge store {knowledge}, and only the cache knows it"
256        );
257        found
258    }
259
260    /// `ids` returns the path of every document and schema of `knowledge`
261    /// that has `id`. It takes the paths from the documents that the run has
262    /// loaded. It then adds each path that the cache knows, unless the run
263    /// has loaded it.
264    pub fn ids(&self, knowledge: usize, id: &str) -> Vec<RepoPath> {
265        self.note(Query::Doc {
266            knowledge,
267            id: id.to_string(),
268        });
269        let mut paths: Vec<RepoPath> = self
270            .knowledges
271            .get(knowledge)
272            .map(|k| k.ids(id).into_iter().cloned().collect())
273            .unwrap_or_default();
274        if let Some(fallback) = &self.fallback {
275            for p in fallback.ids(knowledge, id) {
276                if !self.holds(&p) && !paths.contains(&p) {
277                    paths.push(p);
278                }
279            }
280            paths.sort();
281        }
282        paths
283    }
284
285    /// `documents_of` returns the documents of type `type_name` in
286    /// `knowledge` that the run has loaded.
287    pub fn documents_of(&self, knowledge: usize, type_name: &str) -> Vec<&Document> {
288        self.note(Query::Type {
289            knowledge,
290            type_name: type_name.to_string(),
291        });
292        self.knowledges
293            .get(knowledge)
294            .map(|k| k.documents_of(type_name).collect())
295            .unwrap_or_default()
296    }
297
298    /// `ids_of_type` returns the path and id of every document of type
299    /// `type_name` in `knowledge`. It takes them from the documents that the
300    /// run has loaded. For the paths that the run has not loaded, it adds the
301    /// cache's rows.
302    pub fn ids_of_type(&self, knowledge: usize, type_name: &str) -> Vec<(RepoPath, String)> {
303        let mut out: Vec<(RepoPath, String)> = self
304            .documents_of(knowledge, type_name)
305            .into_iter()
306            .filter_map(|d| d.id().map(|id| (d.path.clone(), id.to_string())))
307            .collect();
308        if let Some(fallback) = &self.fallback {
309            for (p, id) in fallback.ids_of_type(knowledge, type_name) {
310                if !self.holds(&p) {
311                    out.push((p, id));
312                }
313            }
314            out.sort();
315        }
316        out
317    }
318
319    /// `path_of_id` returns the path of the document or schema with `id` in
320    /// `knowledge`, when exactly one document or schema has it. It counts the
321    /// documents that the run has loaded and the ones that the cache knows
322    /// (CACHE-1_AC-21).
323    pub fn path_of_id(&self, knowledge: usize, id: &str) -> Option<RepoPath> {
324        match self.ids(knowledge, id).as_slice() {
325            [one] => Some(one.clone()),
326            _ => None,
327        }
328    }
329
330    /// `id_of` returns the knowledge store and id of the document or schema
331    /// at `path`. It takes them from the document when the run has loaded
332    /// it, and from the cache's row for the path otherwise.
333    pub fn id_of(&self, path: &RepoPath) -> Option<(usize, String)> {
334        self.note(Query::Path(path.clone()));
335        if let Some(found) = self.id_at(path) {
336            return Some(found);
337        }
338        let k = self.knowledge_of(path)?;
339        let id = self.fallback.as_ref()?.fields(path)?.id?;
340        Some((k, id))
341    }
342
343    /// `broken_in` returns the paths of the documents of `knowledge` whose
344    /// frontmatter doesn't parse. It takes them from the documents that the
345    /// run has loaded. For the documents that the run has not loaded, it adds
346    /// the paths that the cache lists as broken.
347    pub fn broken_in(&self, knowledge: usize) -> Vec<RepoPath> {
348        let mut out: Vec<RepoPath> = self
349            .knowledges
350            .get(knowledge)
351            .map(|k| {
352                k.documents
353                    .iter()
354                    .filter(|d| !d.core.present)
355                    .map(|d| d.path.clone())
356                    .collect()
357            })
358            .unwrap_or_default();
359        if let Some(fallback) = &self.fallback {
360            for p in fallback.broken_in(knowledge) {
361                if !self.holds(&p) {
362                    out.push(p);
363                }
364            }
365        }
366        out.sort();
367        out
368    }
369
370    /// `holds` reports whether the run has loaded a document or schema at
371    /// `path`.
372    pub fn holds(&self, path: &RepoPath) -> bool {
373        self.knowledges.iter().any(|k| k.is_document(path))
374    }
375
376    /// `is_document` reports whether `path` is a document of any knowledge
377    /// store, whether the run has loaded it or only the cache knows it.
378    pub fn is_document(&self, path: &RepoPath) -> bool {
379        self.holds(path) || self.fallback.as_ref().is_some_and(|f| f.is_document(path))
380    }
381
382    /// `admit` adds to the model a document that the build did not load. The
383    /// run has since read the document in full. Such a document is one that the
384    /// run checks, or one that a check looks up.
385    pub fn admit(&mut self, knowledge: usize, doc: Document) {
386        let Some(k) = self.knowledges.get_mut(knowledge) else {
387            return;
388        };
389        if k.by_path.contains_key(&doc.path) {
390            return;
391        }
392        k.insert_document(doc);
393    }
394
395    /// `admit_schema` replaces the cache's summary of a schema with the
396    /// schema read in full. It keeps the same index, so every reference to
397    /// the schema stays valid (CACHE-1_AC-25).
398    pub fn admit_schema(&mut self, knowledge: usize, schema: SchemaDocument) {
399        let Some(k) = self.knowledges.get_mut(knowledge) else {
400            return;
401        };
402        if let Some(slot) = k.schemas.iter_mut().find(|s| s.doc.path == schema.doc.path) {
403            *slot = schema;
404        }
405    }
406
407    /// `admit_index` adds to the model an index file that the build did not
408    /// load. The run reads the index file of a directory when a change
409    /// touches the directory, so that the check of the directory can compare
410    /// it with the expected index (CACHE-1_AC-18).
411    pub fn admit_index(&mut self, knowledge: usize, index: IndexFile) {
412        let Some(k) = self.knowledges.get_mut(knowledge) else {
413            return;
414        };
415        if k.indexes.iter().any(|i| i.path == index.path) {
416            return;
417        }
418        k.indexes.push(index);
419    }
420
421    /// `exists` reports whether `path` is a file or a directory of the
422    /// repository, and records the question as a query (CACHE-1_AC-26).
423    pub fn exists(&self, path: &RepoPath) -> bool {
424        self.note(Query::Exists(path.clone()));
425        self.tree.exists(path)
426    }
427
428    /// `is_dir` reports whether `path` is a directory of the repository, and
429    /// records the question as the query of `exists`.
430    pub fn is_dir(&self, path: &RepoPath) -> bool {
431        self.note(Query::Exists(path.clone()));
432        self.tree.is_dir(path)
433    }
434
435    /// `loaded_document` returns the knowledge and the document at `path`,
436    /// when `path` is a document or a schema that the run loaded.
437    pub(crate) fn loaded_document(&self, path: &RepoPath) -> Option<(usize, &Document)> {
438        match self.by_path(path)? {
439            Located::Document(k, doc) => Some((k, doc)),
440            Located::Schema(k, s) if s.loaded => Some((k, &s.doc)),
441            _ => None,
442        }
443    }
444
445    /// `by_path` returns what `path` is in the model.
446    pub fn by_path(&self, path: &RepoPath) -> Option<Located<'_>> {
447        self.note(Query::Path(path.clone()));
448        for (k, knowledge) in self.knowledges.iter().enumerate() {
449            if let Some(&i) = knowledge.by_path.get(path) {
450                return Some(Located::Document(k, &knowledge.documents[i]));
451            }
452            if let Some(s) = knowledge.schemas.iter().find(|s| &s.doc.path == path) {
453                return Some(Located::Schema(k, s));
454            }
455            if let Some(i) = knowledge.indexes.iter().find(|i| &i.path == path) {
456                return Some(Located::Index(k, i));
457            }
458            if let Some(a) = knowledge.asset_at(path) {
459                return Some(Located::Asset(k, a));
460            }
461        }
462        self.additional
463            .iter()
464            .find(|a| &a.path == path)
465            .map(Located::Additional)
466    }
467
468    /// `is_document_of` reports whether `path` is a document of `knowledge`.
469    pub fn is_document_of(&self, knowledge: usize, path: &RepoPath) -> bool {
470        self.note(Query::Path(path.clone()));
471        self.knowledges
472            .get(knowledge)
473            .is_some_and(|k| k.is_document(path))
474            || (self.knowledge_of(path) == Some(knowledge)
475                && self.fallback.as_ref().is_some_and(|f| f.is_document(path)))
476    }
477
478    /// `is_materialized` reports whether `path` is a document of any
479    /// knowledge store or an additional file. An include block that refers to
480    /// a file by path can't include such a file.
481    pub fn is_materialized(&self, path: &RepoPath) -> bool {
482        self.note(Query::Path(path.clone()));
483        self.is_document(path) || self.dispatch.contains_key(path)
484    }
485
486    /// `is_additional` reports whether a schema's globs match `path` as an
487    /// additional file, whether the run has loaded it or not.
488    pub fn is_additional(&self, path: &RepoPath) -> bool {
489        self.dispatch.contains_key(path)
490    }
491
492    /// `admit_additional` adds to the model an additional file that the
493    /// build did not load. The run has since read the file in full, because a
494    /// check needs it (CACHE-1_AC-20).
495    pub fn admit_additional(&mut self, file: AdditionalFile) {
496        if self.additional.iter().any(|a| a.path == file.path) {
497            return;
498        }
499        self.additional.push(file);
500    }
501
502    /// `is_materialized_in` reports whether `path` is a document of
503    /// `knowledge` or an additional file that its schemas match. An include
504    /// block in a document of `knowledge` can't include such a file by path
505    /// (`SOKF_FORMAT_89`). `is_materialized_in` treats an additional file of
506    /// another knowledge store as an ordinary repository file, which such an
507    /// include block can include. With no knowledge store given, the files of
508    /// every knowledge store count. To reject an include block that refers by
509    /// path to a document or an asset of any knowledge store, a caller checks
510    /// the path separately, through `id_at` and `asset_at`.
511    // sokf-implements: SOKF_FORMAT_89
512    pub fn is_materialized_in(&self, knowledge: Option<usize>, path: &RepoPath) -> bool {
513        match knowledge {
514            None => self.is_materialized(path),
515            Some(k) => {
516                self.is_document_of(k, path)
517                    || self
518                        .dispatch
519                        .get(path)
520                        .is_some_and(|s| s.is_some_and(|s| s.knowledge == k))
521            }
522        }
523    }
524
525    /// `asset_of` returns the asset that the document at `sidecar`
526    /// describes, with its knowledge store.
527    pub fn asset_of(&self, sidecar: &RepoPath) -> Option<(usize, &Asset)> {
528        self.note(Query::Path(sidecar.clone()));
529        self.knowledges
530            .iter()
531            .enumerate()
532            .find_map(|(k, kn)| kn.asset_of(sidecar).map(|a| (k, a)))
533    }
534
535    /// `asset_at` returns the asset at `path`, with its knowledge store.
536    pub fn asset_at(&self, path: &RepoPath) -> Option<(usize, &Asset)> {
537        self.note(Query::Path(path.clone()));
538        self.knowledges
539            .iter()
540            .enumerate()
541            .find_map(|(k, kn)| kn.asset_at(path).map(|a| (k, a)))
542    }
543
544    /// `content_path` returns the path that the id of a document refers to
545    /// (FORMAT-2_AC-1): the path of the asset for a sidecar, and the path of
546    /// the document otherwise. The resolution of an id doesn't change: an id
547    /// still resolves to its document. Only code that needs the content calls
548    /// `content_path`. For example, the code that builds the definition of a
549    /// label without a fragment calls it.
550    pub fn content_path(&self, document: &RepoPath) -> RepoPath {
551        self.asset_of(document)
552            .map_or_else(|| document.clone(), |(_, a)| a.path.clone())
553    }
554
555    /// `schema` returns the schema at `r`.
556    pub fn schema(&self, r: SchemaRef) -> &SchemaDocument {
557        &self.knowledges[r.knowledge].schemas[r.index]
558    }
559
560    /// `schema_query` returns the query that stands for a read of the schema
561    /// at `r`. The query uses the key that `schema_key` returns. The key is
562    /// the value of the schema's `type` const, or, for a schema that
563    /// dispatches only by its globs, the schema's path (CACHE-1_AC-15).
564    pub fn schema_query(&self, r: SchemaRef) -> Query {
565        Query::Schema {
566            knowledge: r.knowledge,
567            key: self.knowledges[r.knowledge].schema_key(r.index),
568        }
569    }
570
571    /// `knowledge_of` returns the knowledge store whose root contains `path`,
572    /// the innermost one when roots nest.
573    pub fn knowledge_of(&self, path: &RepoPath) -> Option<usize> {
574        crate::walk::innermost(self.knowledges.iter().map(|k| &k.root), path)
575    }
576
577    /// `is_unit` reports whether `path` is a unit. A unit is a file that a
578    /// check produces output for: a document, a schema document, or an
579    /// additional file matched by a schema's globs (CACHE-1_AC-24). It searches the
580    /// walk's sorted list, so it does not build a set of all paths.
581    pub fn is_unit(&self, path: &RepoPath) -> bool {
582        self.tree
583            .file(path)
584            .is_some_and(|f| matches!(f.kind, FileKind::Document | FileKind::Schema))
585            || self.dispatch.contains_key(path)
586    }
587
588    /// `is_marker_file` reports whether `path` is a file that the run reads
589    /// for markers: a file of the walk outside every knowledge root, when the
590    /// run checks markers (`SOKF_VALIDATION_50`).
591    pub fn is_marker_file(&self, path: &RepoPath) -> bool {
592        self.marker_check != crate::MarkerCheck::Off
593            && self
594                .tree
595                .file(path)
596                .is_some_and(|f| f.root.is_none() && f.kind == FileKind::Candidate)
597    }
598
599    /// `document_paths` returns the path of every document and schema
600    /// document of every knowledge store that the walk lists, whether the run
601    /// has loaded it or not. These are the files that a full run reads.
602    pub fn document_paths(&self) -> BTreeSet<RepoPath> {
603        self.tree
604            .files
605            .iter()
606            .filter(|f| matches!(f.kind, FileKind::Document | FileKind::Schema))
607            .map(|f| f.path.clone())
608            .collect()
609    }
610
611    /// `documents` returns every document of every knowledge store, with the
612    /// index of its knowledge store.
613    pub fn documents(&self) -> impl Iterator<Item = (usize, &Document)> {
614        self.knowledges
615            .iter()
616            .enumerate()
617            .flat_map(|(k, kn)| kn.documents.iter().map(move |d| (k, d)))
618    }
619
620    /// `documents_and_schemas` returns every document and every schema
621    /// document of every knowledge store, with the index of its knowledge
622    /// store.
623    pub fn documents_and_schemas(&self) -> impl Iterator<Item = (usize, &Document)> {
624        self.knowledges.iter().enumerate().flat_map(|(k, kn)| {
625            kn.documents
626                .iter()
627                .chain(kn.schemas.iter().map(|s| &s.doc))
628                .map(move |d| (k, d))
629        })
630    }
631}