Skip to main content

sokf_core/model/
keys.rs

1//! This module indexes the captured keys by scope, and resolves `sokf:`
2//! labels and their fragments as the format specification defines.
3
4use std::collections::{BTreeMap, BTreeSet, HashMap};
5
6use super::{Model, Query};
7use crate::{
8    RepoPath,
9    grammar::KeyScope,
10    markdown::{self, Body, link_headings},
11};
12
13/// A `KeyEntry` is one captured key.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct KeyEntry {
16    /// The key.
17    pub key: String,
18    /// The id of the key's anchor, which a fragment names the key by: the
19    /// engine's `Capture::anchor` of the capture, which every capture of the
20    /// key shares (`SOKF_FORMAT_72`).
21    pub id: String,
22    /// The document that captures it.
23    pub path: RepoPath,
24    /// The line that captures the key.
25    pub line: usize,
26    /// The slug of the heading, when a heading captures the key.
27    pub heading_slug: Option<String>,
28    /// Whether this capture holds the key's anchor: the capture at whose
29    /// spot the engine places the anchor, or a heading whose slug is the id.
30    /// Every capture of the key in one block, such as the lines of one
31    /// fence, shares the block's spot, so each of them holds the anchor,
32    /// until the engine exports which capture it chose.
33    pub holds_anchor: bool,
34    /// The scope that the schema declares for the key.
35    pub scope: KeyScope,
36    /// The knowledge of the document that captures the key.
37    pub knowledge: usize,
38    /// The `rule-id` of the key. It is the nearest `rule-id` around the rule
39    /// that captures the key. `for-each-key-of` and `cited-by` refer
40    /// to this `rule-id`.
41    pub rule_id: Option<String>,
42}
43
44/// A `KeyIndex` holds the keys by the scope in which each key must be
45/// unique (the grammar's `unique`). It stores each key under its slug. The
46/// slug is the id of the key's anchor, and a fragment refers to a key by
47/// that slug (`SOKF_FORMAT_72`).
48#[derive(Debug, Clone, Default)]
49pub struct KeyIndex {
50    /// Every key of every document, by path and by slug.
51    pub document: HashMap<(RepoPath, String), Vec<KeyEntry>>,
52    /// The keys of knowledge scope, by knowledge and by slug.
53    pub knowledge: HashMap<(usize, String), Vec<KeyEntry>>,
54    /// The keys of repository scope, by slug.
55    pub repository: HashMap<String, Vec<KeyEntry>>,
56    /// The slugs of the anchors that the engine keeps for the units that
57    /// break their rules, by path. Such a unit captures no key, but a
58    /// fragment can name its anchor (`SOKF_FORMAT_71`).
59    pub anchors: BTreeMap<RepoPath, BTreeSet<String>>,
60}
61
62impl KeyIndex {
63    /// `add` records a captured key under its document and its scope. The
64    /// scope keeps one entry of each document for a key, the first that it
65    /// is given, because a bare reference resolves to the one document that captures
66    /// the key, however many units of the document capture it.
67    pub fn add(&mut self, entry: KeyEntry) {
68        let s = entry.id.clone();
69        let scoped = match &entry.scope {
70            KeyScope::Host(scope) if scope == "knowledge" => Some(
71                self.knowledge
72                    .entry((entry.knowledge, s.clone()))
73                    .or_default(),
74            ),
75            KeyScope::Host(scope) if scope == "repository" => {
76                Some(self.repository.entry(s.clone()).or_default())
77            }
78            _ => None,
79        };
80        if let Some(entries) = scoped
81            && !entries.iter().any(|e| e.path == entry.path)
82        {
83            entries.push(entry.clone());
84        }
85        self.document
86            .entry((entry.path.clone(), s))
87            .or_default()
88            .push(entry);
89    }
90
91    /// `add_anchor` records an anchor that the engine keeps in `path` for a
92    /// unit that breaks its rule.
93    pub fn add_anchor(&mut self, path: RepoPath, slug: String) {
94        self.anchors.entry(path).or_default().insert(slug);
95    }
96
97    /// `anchors_of` returns the slugs of the anchors that the engine keeps
98    /// in `path`.
99    pub fn anchors_of(&self, path: &RepoPath) -> impl Iterator<Item = &str> {
100        self.anchors
101            .get(path)
102            .into_iter()
103            .flatten()
104            .map(String::as_str)
105    }
106
107    /// `merge` adds the keys and the kept anchors of `other`.
108    pub fn merge(&mut self, other: KeyIndex) {
109        self.extend(other.document.into_values().flatten());
110        for (path, slugs) in other.anchors {
111            self.anchors.entry(path).or_default().extend(slugs);
112        }
113    }
114
115    /// `of_document` returns the keys that `path` captures.
116    pub fn of_document<'a>(&'a self, path: &'a RepoPath) -> impl Iterator<Item = &'a KeyEntry> {
117        self.document
118            .iter()
119            .filter(move |((p, _), _)| p == path)
120            .flat_map(|(_, entries)| entries.iter())
121    }
122}
123
124impl Extend<KeyEntry> for KeyIndex {
125    fn extend<I: IntoIterator<Item = KeyEntry>>(&mut self, entries: I) {
126        for entry in entries {
127            self.add(entry);
128        }
129    }
130}
131
132/// A `Label` holds the three parts of a `sokf:` label: the store
133/// (optional), the id (absent when the label is a bare fragment), and the
134/// fragment.
135#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
136pub struct Label<'a> {
137    /// The store, written as `name` or `scope/name`.
138    pub store: Option<&'a str>,
139    /// The document id.
140    pub id: Option<&'a str>,
141    /// The key or heading slug.
142    pub fragment: Option<&'a str>,
143}
144
145impl<'a> Label<'a> {
146    /// `with_fragment` returns the label with `fragment` in place of its own.
147    #[must_use]
148    pub fn with_fragment(self, fragment: Option<&'a str>) -> Self {
149        Label { fragment, ..self }
150    }
151
152    /// `without_store` returns the label with no store, so that it resolves
153    /// in the store that the caller chooses.
154    #[must_use]
155    pub fn without_store(self) -> Self {
156        Label {
157            store: None,
158            ..self
159        }
160    }
161}
162
163/// A `Resolved` is the target of a `sokf:` label.
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct Resolved {
166    /// The knowledge of the target.
167    pub knowledge: usize,
168    /// The target document.
169    pub path: RepoPath,
170    /// The fragment that the definition block appends to the path as
171    /// `#slug`. It is the slug of the heading or key that the label refers to.
172    pub slug: Option<String>,
173}
174
175/// An `Unresolved` states the reason that a `sokf:` label is a broken edge
176/// (`SOKF_FORMAT_62`).
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub enum Unresolved {
179    /// The store matches no knowledge root, current or former. The variant
180    /// holds the store as written in the label.
181    NoStore(String),
182    /// The id matches no document in the knowledge.
183    NoDocument,
184    /// The id matches more than one document.
185    DuplicateId,
186    /// The fragment matches no key and no heading.
187    NoFragment,
188    /// A bare fragment matches no key at repository or knowledge scope.
189    BareNotFound,
190    /// A bare fragment matches keys in more than one document.
191    BareAmbiguous,
192    /// A bare fragment matches only a key of document scope.
193    BareDocumentScope,
194    /// The fragment is the text of a key or a heading, not its slug. The
195    /// variant holds the slug.
196    KeyForm(String),
197}
198
199impl Unresolved {
200    /// `message` returns the error message for `label`.
201    pub fn message(&self, label: &str) -> String {
202        match self {
203            Unresolved::NoStore(store) => format!(
204                "`[{label}]` refers to the store `{store}`, which is not a knowledge root of this repository"
205            ),
206            Unresolved::NoDocument => format!("`[{label}]` resolves to no document"),
207            Unresolved::DuplicateId => {
208                format!("more than one document has the id in `[{label}]`")
209            }
210            Unresolved::NoFragment => {
211                format!(
212                    "`[{label}]` refers to a fragment that is neither a captured key nor a heading"
213                )
214            }
215            Unresolved::BareNotFound => format!(
216                "`[{label}]` refers to a key that no document of its store captures at repository or knowledge scope"
217            ),
218            Unresolved::BareAmbiguous => {
219                format!("`[{label}]` refers to a key that more than one document captures")
220            }
221            Unresolved::BareDocumentScope => {
222                format!("`[{label}]` refers to a key of document scope only")
223            }
224            Unresolved::KeyForm(slug) => {
225                format!("`[{label}]` gives the fragment as text, not as a slug. Use `#{slug}`")
226            }
227        }
228    }
229}
230
231/// `resolve_in` resolves a fragment against the headings, the keys, and the
232/// kept anchors of one document, by slug (`SOKF_FORMAT_71`). The headings
233/// include each heading inside a quote or a list item, and each heading has
234/// the slug that the host gives it, so no two headings share one
235/// (`SOKF_FORMAT_155`). A kept anchor is one that the engine keeps for a
236/// unit that breaks its rule. It returns the fragment itself, which the
237/// definition block appends. When the fragment matches only by its text,
238/// `resolve_in` returns `Unresolved::KeyForm` with the slug.
239// sokf-implements: SOKF_FORMAT_71
240// sokf-implements: SOKF_FORMAT_72
241// sokf-implements: SOKF_FORMAT_73
242pub fn resolve_in(
243    keys: &KeyIndex,
244    path: &RepoPath,
245    body: &Body,
246    fragment: &str,
247) -> Result<String, Unresolved> {
248    let headings = link_headings(body);
249    let found = |f: &str| {
250        keys.document.contains_key(&(path.clone(), f.to_string()))
251            || keys.anchors.get(path).is_some_and(|a| a.contains(f))
252            || headings.iter().any(|h| h.slug == f)
253    };
254    if found(fragment) {
255        return Ok(fragment.to_string());
256    }
257    match markdown::key_ids(fragment)
258        .into_iter()
259        .find(|s| s != fragment && found(s))
260    {
261        Some(s) => Err(Unresolved::KeyForm(s)),
262        None => Err(Unresolved::NoFragment),
263    }
264}
265
266/// `resolve` resolves a `sokf:` label from a document of `knowledge`: first
267/// the store, then the id in that store, then the fragment. A bare fragment
268/// with no store refers to a key in the store of the document that holds
269/// the label. If no key there matches, but a key of repository scope in
270/// another store does, the label resolves to that key, because that key is
271/// unique. The canonical form of the label then includes that other store
272/// (`SOKF_FORMAT_65`).
273// sokf-implements: SOKF_FORMAT_61
274// sokf-implements: SOKF_FORMAT_63
275// sokf-implements: SOKF_FORMAT_64
276// sokf-implements: SOKF_FORMAT_66
277// sokf-implements: SOKF_FORMAT_70
278// sokf-implements: FORMAT-2_AC-1
279// sokf-implements: FORMAT-2_AC-3
280pub fn resolve(
281    model: &Model,
282    keys: &KeyIndex,
283    knowledge: usize,
284    label: Label<'_>,
285) -> Result<Resolved, Unresolved> {
286    let target = match label.store {
287        None => knowledge,
288        Some(store) => {
289            model
290                .store(knowledge, store)
291                .ok_or_else(|| Unresolved::NoStore(store.to_string()))?
292                .knowledge
293        }
294    };
295    if model.knowledges.get(target).is_none() {
296        return Err(Unresolved::NoDocument);
297    }
298    match (label.id.filter(|i| !i.is_empty()), label.fragment) {
299        // `sokf:#`, with no id and an empty fragment, refers to nothing (SOKF_FORMAT_66).
300        (None, None | Some("")) => Err(Unresolved::NoDocument),
301        (Some(id), fragment) => {
302            let doc = match model.ids(target, id).len() {
303                0 => return Err(Unresolved::NoDocument),
304                1 => model.document(target, id).ok_or(Unresolved::NoDocument)?,
305                _ => return Err(Unresolved::DuplicateId),
306            };
307            // An empty fragment refers to the whole document (FORMAT-2_AC-3).
308            let Some(fragment) = fragment.filter(|f| !f.is_empty()) else {
309                return Ok(Resolved {
310                    knowledge: target,
311                    path: doc.path.clone(),
312                    slug: None,
313                });
314            };
315            resolve_in(keys, &doc.path, &doc.body, fragment).map(|slug| Resolved {
316                knowledge: target,
317                path: doc.path.clone(),
318                slug: Some(slug),
319            })
320        }
321        (None, Some(fragment)) => {
322            let elsewhere = label.store.is_none();
323            match bare(model, keys, target, fragment, elsewhere) {
324                Err(Unresolved::BareNotFound) => {
325                    // The first id that names a key decides, as it does for
326                    // a marker: a key form where it resolves, and no key
327                    // where it names several or one of document scope.
328                    let first = markdown::key_ids(fragment)
329                        .into_iter()
330                        .filter(|s| s != fragment)
331                        .map(|s| {
332                            let found = bare(model, keys, target, &s, elsewhere);
333                            (s, found)
334                        })
335                        .find(|(_, found)| !matches!(found, Err(Unresolved::BareNotFound)));
336                    match first {
337                        Some((s, Ok(_))) => Err(Unresolved::KeyForm(s)),
338                        _ => Err(Unresolved::BareNotFound),
339                    }
340                }
341                other => other,
342            }
343        }
344    }
345}
346
347/// `resolve_slugged` resolves a label as `resolve` does. When the label
348/// gives its fragment as text, not as a slug, `resolve_slugged` resolves
349/// the label again with the fragment's slug, and returns that slug too.
350pub fn resolve_slugged(
351    model: &Model,
352    keys: &KeyIndex,
353    knowledge: usize,
354    label: Label<'_>,
355) -> (Result<Resolved, Unresolved>, Option<String>) {
356    match resolve(model, keys, knowledge, label) {
357        Err(Unresolved::KeyForm(s)) => {
358            let resolved = resolve(model, keys, knowledge, label.with_fragment(Some(&s)));
359            (resolved, Some(s))
360        }
361        other => (other, None),
362    }
363}
364
365/// `bare` resolves a bare fragment, by its slug, to a key of `knowledge`
366/// whose scope is the knowledge or the repository. When no such key exists
367/// and `elsewhere` is set, it
368/// resolves the fragment to a key of repository scope in another store.
369fn bare(
370    model: &Model,
371    keys: &KeyIndex,
372    knowledge: usize,
373    fragment: &str,
374    elsewhere: bool,
375) -> Result<Resolved, Unresolved> {
376    let found = |one: &KeyEntry| Resolved {
377        knowledge: one.knowledge,
378        path: one.path.clone(),
379        slug: Some(fragment.to_string()),
380    };
381    model.note(Query::KeyRepository(fragment.to_string()));
382    model.note(Query::KeyKnowledge {
383        knowledge,
384        slug: fragment.to_string(),
385    });
386    let repo = keys
387        .repository
388        .get(fragment)
389        .map(Vec::as_slice)
390        .unwrap_or_default();
391    let own: Vec<&KeyEntry> = repo.iter().filter(|e| e.knowledge == knowledge).collect();
392    match own.as_slice() {
393        [one] => return Ok(found(one)),
394        [] => {}
395        _ => return Err(Unresolved::BareAmbiguous),
396    }
397    let local = keys
398        .knowledge
399        .get(&(knowledge, fragment.to_string()))
400        .map(Vec::as_slice)
401        .unwrap_or_default();
402    match local {
403        [one] => Ok(found(one)),
404        [] => {
405            if elsewhere {
406                match repo {
407                    [one] => return Ok(found(one)),
408                    [] => {}
409                    _ => return Err(Unresolved::BareAmbiguous),
410                }
411            }
412            model.note(Query::KeyDocument {
413                knowledge,
414                slug: fragment.to_string(),
415            });
416            let document_only = keys
417                .document
418                .keys()
419                .any(|(p, k)| k == fragment && model.knowledge_of(p) == Some(knowledge));
420            if document_only {
421                Err(Unresolved::BareDocumentScope)
422            } else {
423                Err(Unresolved::BareNotFound)
424            }
425        }
426        _ => Err(Unresolved::BareAmbiguous),
427    }
428}
429
430#[cfg(test)]
431mod tests {
432
433    use super::*;
434
435    fn p(s: &str) -> RepoPath {
436        RepoPath::parse(s).unwrap()
437    }
438
439    fn entry(key: &str, path: &str, scope: KeyScope, slug: Option<&str>) -> KeyEntry {
440        KeyEntry {
441            id: crate::markdown::slug(key),
442            key: key.into(),
443            path: p(path),
444            line: 1,
445            heading_slug: slug.map(str::to_string),
446            holds_anchor: true,
447            scope,
448            knowledge: 0,
449            rule_id: None,
450        }
451    }
452
453    #[test]
454    fn indexes_by_scope() {
455        let mut index = KeyIndex::default();
456        index.add(entry("D", "/a.md", KeyScope::Document, None));
457        index.add(entry(
458            "K",
459            "/a.md",
460            KeyScope::Host("knowledge".into()),
461            Some("k-heading"),
462        ));
463        index.add(entry(
464            "R",
465            "/b.md",
466            KeyScope::Host("repository".into()),
467            None,
468        ));
469        assert_eq!(index.document.len(), 3);
470        assert_eq!(index.knowledge.len(), 1);
471        assert_eq!(index.repository.len(), 1);
472        assert_eq!(index.of_document(&p("/a.md")).count(), 2);
473        assert_eq!(index.of_document(&p("/c.md")).count(), 0);
474        for u in [
475            Unresolved::NoStore("s".into()),
476            Unresolved::NoDocument,
477            Unresolved::DuplicateId,
478            Unresolved::NoFragment,
479            Unresolved::BareNotFound,
480            Unresolved::BareAmbiguous,
481            Unresolved::BareDocumentScope,
482            Unresolved::KeyForm("k".into()),
483        ] {
484            assert!(u.message("sokf:x").contains("[sokf:x]"));
485        }
486    }
487
488    // sokf-tests: SOKF_FORMAT_71
489    #[test]
490    fn a_kept_anchor_resolves_a_fragment_of_its_document_and_is_no_key() {
491        let mut index = KeyIndex::default();
492        let mut kept = KeyIndex::default();
493        kept.add_anchor(p("/a.md"), "d-5".into());
494        index.merge(kept);
495        assert_eq!(index.anchors_of(&p("/a.md")).collect::<Vec<_>>(), ["d-5"]);
496        assert_eq!(index.of_document(&p("/a.md")).count(), 0);
497        let body = Body::default();
498        assert_eq!(
499            resolve_in(&index, &p("/a.md"), &body, "d-5"),
500            Ok("d-5".into())
501        );
502        assert_eq!(
503            resolve_in(&index, &p("/a.md"), &body, "D-5"),
504            Err(Unresolved::KeyForm("d-5".into()))
505        );
506        assert_eq!(
507            resolve_in(&index, &p("/b.md"), &body, "d-5"),
508            Err(Unresolved::NoFragment)
509        );
510    }
511}
512
513#[cfg(test)]
514mod fragment_tests {
515    use std::collections::BTreeMap;
516
517    use super::*;
518    use crate::{Config, FsLoader, RepoRoot, collect, config::MarkerCheck};
519
520    // sokf-tests: FORMAT-2_AC-3
521    #[test]
522    fn an_empty_fragment_names_the_whole_document_and_a_bare_one_nothing() {
523        let dir = crate::test_support::fresh_dir("keys-empty");
524        std::fs::create_dir_all(dir.join("knowledge")).unwrap();
525        std::fs::write(
526            dir.join("knowledge/a.md"),
527            "---\ntype: Note\nid: a\n---\n\n# A\n\n## Part\n",
528        )
529        .unwrap();
530        let root = RepoRoot::new(dir.clone());
531        let tree = collect(
532            &root,
533            &Config {
534                roots: vec![RepoPath::parse("/knowledge").unwrap()],
535                registered_count: 0,
536                exclude: vec![],
537                added_exclude: vec![],
538                declined: BTreeMap::default(),
539                markers: MarkerCheck::default(),
540                format: crate::config::FormatConfig::default(),
541            },
542        )
543        .unwrap();
544        let model = crate::model::build(tree, &mut FsLoader::new(&root)).unwrap();
545        let keys = KeyIndex::default();
546        let label = |id, fragment| Label {
547            store: None,
548            id,
549            fragment,
550        };
551        let path = RepoPath::parse("/knowledge/a.md").unwrap();
552        assert_eq!(
553            resolve(&model, &keys, 0, label(Some("a"), Some(""))),
554            Ok(Resolved {
555                knowledge: 0,
556                path: path.clone(),
557                slug: None
558            })
559        );
560        assert_eq!(
561            resolve(&model, &keys, 0, label(Some("a"), Some("part"))),
562            Ok(Resolved {
563                knowledge: 0,
564                path,
565                slug: Some("part".into())
566            })
567        );
568        assert_eq!(
569            resolve(&model, &keys, 0, label(None, Some(""))),
570            Err(Unresolved::NoDocument)
571        );
572        std::fs::remove_dir_all(&dir).unwrap();
573    }
574}