sirno 0.0.5

Sirno gives project design a semantic intermediate representation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! Structural checks for Sirno entries.
//!
//! Sirno checks the shape of entries and structural targets.
//! It does not decide whether prose is true or whether code satisfies a claim.

use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};

use crate::entry::Entry;
use crate::identifier::EntryAddress;
use crate::structural::StructuralSettings;

const CATEGORY_FIELD: &str = "category";

/// Boundary at which Sirno checks structure.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CheckMode {
    /// Editing checks keep local movement fast.
    Edit,
    /// Review checks treat dangling structural references as errors.
    Review,
}

impl CheckMode {
    /// Diagnostic severity used by this check boundary.
    pub fn severity(self) -> CheckSeverity {
        match self {
            | Self::Edit => CheckSeverity::Warning,
            | Self::Review => CheckSeverity::Error,
        }
    }

    // sirno:witness:structural-check:begin
    /// Check structural metadata targets for a set of entries.
    ///
    /// Parsing already enforces required fields, accepted field shapes, and valid path syntax.
    /// This pass checks configured structural field entries and entry addresses named by those fields.
    pub fn check_entries<'a>(
        self, entries: impl IntoIterator<Item = &'a Entry>, structural: &StructuralSettings,
    ) -> CheckReport {
        self.check_entries_with_structural_inhabitance(entries, structural, true)
    }

    /// Check structural metadata targets, with explicit structural-inhabitance policy.
    ///
    /// Structural inhabitance requires each configured structural field to name an existing entry.
    pub fn check_entries_with_structural_inhabitance<'a>(
        self, entries: impl IntoIterator<Item = &'a Entry>, structural: &StructuralSettings,
        structural_inhabitance: bool,
    ) -> CheckReport {
        let entries = entries.into_iter().collect::<Vec<_>>();
        let entries_by_id =
            entries.iter().map(|entry| (entry.id.clone(), *entry)).collect::<BTreeMap<_, _>>();
        let severity = self.severity();

        let mut report = CheckReport::new();
        if structural_inhabitance {
            for (field, _) in structural.fields() {
                if !entries_by_id.keys().any(|id| id.as_str() == field) {
                    report.push(CheckDiagnostic {
                        severity,
                        kind: CheckDiagnosticKind::MissingStructuralFieldEntry,
                        entry: None,
                        field: field.to_owned(),
                        target: None,
                    });
                }
            }
        }
        for entry in &entries {
            for (field, targets) in entry.metadata.structural_fields() {
                if !structural.contains_field(field) {
                    report.push(CheckDiagnostic {
                        severity: CheckSeverity::Warning,
                        kind: CheckDiagnosticKind::UnconfiguredStructuralField,
                        entry: Some(entry.id.clone()),
                        field: field.to_owned(),
                        target: None,
                    });
                    continue;
                }
                for target in targets {
                    if !entries_by_id.contains_key(target) {
                        report.push(CheckDiagnostic {
                            severity,
                            kind: CheckDiagnosticKind::MissingTarget,
                            entry: Some(entry.id.clone()),
                            field: field.to_owned(),
                            target: Some(target.clone()),
                        });
                    }
                }
            }
        }
        self.check_category_targets(&entries_by_id, structural, &mut report);
        report
    }

    fn check_category_targets(
        self, entries_by_id: &BTreeMap<EntryAddress, &Entry>, structural: &StructuralSettings,
        report: &mut CheckReport,
    ) {
        let category_id =
            EntryAddress::new(CATEGORY_FIELD).expect("built-in category entry address is valid");
        let category_targets = entries_by_id
            .values()
            .flat_map(|entry| entry.metadata.structural_targets_for(CATEGORY_FIELD))
            .cloned()
            .collect::<BTreeSet<_>>();
        if category_targets.is_empty() && !structural.contains_field(CATEGORY_FIELD) {
            return;
        }
        if !entries_by_id.contains_key(&category_id) {
            report.push(CheckDiagnostic {
                severity: CheckSeverity::Warning,
                kind: CheckDiagnosticKind::MissingCategoryEntry,
                entry: None,
                field: CATEGORY_FIELD.to_owned(),
                target: Some(category_id.clone()),
            });
        }
        for target in category_targets {
            let Some(target_entry) = entries_by_id.get(&target) else {
                continue;
            };
            let has_category_marker = target_entry
                .metadata
                .structural_targets_for(CATEGORY_FIELD)
                .iter()
                .any(|id| id == &category_id);
            if !has_category_marker {
                report.push(CheckDiagnostic {
                    severity: self.severity(),
                    kind: CheckDiagnosticKind::CategoryTargetMissingCategoryMarker,
                    entry: Some(target.clone()),
                    field: CATEGORY_FIELD.to_owned(),
                    target: Some(category_id.clone()),
                });
            }
        }
    }
    // sirno:witness:structural-check:end
}

/// Severity of one structural diagnostic.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CheckSeverity {
    /// A condition worth showing during editing.
    Warning,
    /// A structural violation at the selected boundary.
    Error,
}

impl CheckSeverity {
    /// Lowercase label used in human-readable diagnostic output.
    pub fn label(self) -> &'static str {
        match self {
            | Self::Warning => "warning",
            | Self::Error => "error",
        }
    }
}

/// Reason for one structural diagnostic.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CheckDiagnosticKind {
    /// A configured structural field does not name an existing entry.
    MissingStructuralFieldEntry,
    /// An entry uses a structural metadata field not configured in `Sirno.toml`.
    UnconfiguredStructuralField,
    /// A structural target id does not name an entry.
    MissingTarget,
    /// Category metadata is present but the `category` entry is missing.
    MissingCategoryEntry,
    /// An entry used as a category target is not itself marked as a category.
    CategoryTargetMissingCategoryMarker,
}

/// One structural diagnostic.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CheckDiagnostic {
    /// Diagnostic severity.
    pub severity: CheckSeverity,
    /// Structural problem detected by the check.
    pub kind: CheckDiagnosticKind,
    /// Entry whose metadata produced the diagnostic.
    pub entry: Option<EntryAddress>,
    /// Metadata field that produced the diagnostic.
    pub field: String,
    /// Referenced path that produced the diagnostic.
    pub target: Option<EntryAddress>,
}

impl CheckDiagnostic {
    /// Human-readable diagnostic message.
    pub fn message(&self) -> String {
        match self.kind {
            | CheckDiagnosticKind::MissingStructuralFieldEntry => format!(
                "`Sirno.toml` configures structural field `{}`, but entry `{}` does not exist",
                self.field, self.field
            ),
            | CheckDiagnosticKind::UnconfiguredStructuralField => format!(
                "`{}` uses structural field `{}` that is not configured in `Sirno.toml`",
                self.entry.as_ref().expect("unconfigured field diagnostic has entry"),
                self.field
            ),
            | CheckDiagnosticKind::MissingTarget => format!(
                "`{}` references missing entry `{}` through `{}`",
                self.entry.as_ref().expect("missing target diagnostic has entry"),
                self.target.as_ref().expect("missing target diagnostic has target"),
                self.field
            ),
            | CheckDiagnosticKind::MissingCategoryEntry => {
                "`category` metadata needs entry `category`; add it with `sirno util entry`"
                    .to_owned()
            }
            | CheckDiagnosticKind::CategoryTargetMissingCategoryMarker => format!(
                "`{}` is used as a category target, but it is not categorized by `{}`",
                self.entry.as_ref().expect("category target diagnostic has entry"),
                self.target.as_ref().expect("category target diagnostic has target")
            ),
        }
    }
}

/// Result of checking a set of entries.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CheckReport {
    diagnostics: Vec<CheckDiagnostic>,
}

impl CheckReport {
    /// Construct an empty report.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add one diagnostic to the report.
    pub fn push(&mut self, diagnostic: CheckDiagnostic) {
        self.diagnostics.push(diagnostic);
    }

    /// All diagnostics in deterministic check order.
    pub fn diagnostics(&self) -> &[CheckDiagnostic] {
        &self.diagnostics
    }

    /// Returns true when the report contains no diagnostics.
    pub fn is_clean(&self) -> bool {
        self.diagnostics.is_empty()
    }

    /// Returns true when at least one diagnostic is an error.
    pub fn has_errors(&self) -> bool {
        self.diagnostics.iter().any(|diagnostic| diagnostic.severity == CheckSeverity::Error)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::entry::EntryMetadata;
    use crate::structural::StructuralFieldSettings;

    const FIELD_TOPIC: &str = "topic";
    const FIELD_CATEGORY: &str = "category";

    fn entry(id: &str) -> Entry {
        Entry::new(EntryAddress::new(id).unwrap(), EntryMetadata::new(id, "desc").unwrap(), "")
    }

    fn structural_settings() -> StructuralSettings {
        StructuralSettings::from_fields([(FIELD_TOPIC, StructuralFieldSettings::default())])
    }

    fn category_settings() -> StructuralSettings {
        StructuralSettings::from_fields([(FIELD_CATEGORY, StructuralFieldSettings::default())])
    }

    #[test]
    fn clean_entries_produce_clean_report() {
        let mut concept = entry("concept");
        concept.metadata.push_structural_target(FIELD_TOPIC, EntryAddress::new("meta").unwrap());
        let mut meta = entry("meta");
        meta.metadata.push_structural_target(FIELD_TOPIC, EntryAddress::new("meta").unwrap());
        let topic = entry(FIELD_TOPIC);

        let report =
            CheckMode::Review.check_entries([&concept, &meta, &topic], &structural_settings());
        assert!(report.is_clean());
    }

    #[test]
    fn edit_mode_reports_dangling_reference_as_warning() {
        let mut concept = entry("concept");
        concept.metadata.push_structural_target(FIELD_TOPIC, EntryAddress::new("meta").unwrap());
        let topic = entry(FIELD_TOPIC);

        let report = CheckMode::Edit.check_entries([&concept, &topic], &structural_settings());
        assert_eq!(report.diagnostics()[0].kind, CheckDiagnosticKind::MissingTarget);
        assert_eq!(report.diagnostics()[0].severity, CheckSeverity::Warning);
        assert!(!report.has_errors());
    }

    #[test]
    fn review_mode_reports_dangling_reference_as_error() {
        let mut concept = entry("concept");
        concept.metadata.push_structural_target(FIELD_TOPIC, EntryAddress::new("meta").unwrap());
        let topic = entry(FIELD_TOPIC);

        let report = CheckMode::Review.check_entries([&concept, &topic], &structural_settings());
        assert_eq!(report.diagnostics()[0].kind, CheckDiagnosticKind::MissingTarget);
        assert_eq!(report.diagnostics()[0].severity, CheckSeverity::Error);
        assert!(report.has_errors());
    }

    #[test]
    fn edit_mode_reports_missing_structural_field_entry_as_warning() {
        let concept = entry("concept");

        let report = CheckMode::Edit.check_entries([&concept], &structural_settings());

        assert_eq!(report.diagnostics()[0].kind, CheckDiagnosticKind::MissingStructuralFieldEntry);
        assert_eq!(report.diagnostics()[0].severity, CheckSeverity::Warning);
        assert!(!report.has_errors());
    }

    #[test]
    fn review_mode_reports_missing_structural_field_entry_as_error() {
        let concept = entry("concept");

        let report = CheckMode::Review.check_entries([&concept], &structural_settings());

        assert_eq!(report.diagnostics()[0].kind, CheckDiagnosticKind::MissingStructuralFieldEntry);
        assert_eq!(report.diagnostics()[0].severity, CheckSeverity::Error);
        assert!(report.has_errors());
        assert!(report.diagnostics()[0].message().contains("entry `topic` does not exist"));
    }

    #[test]
    fn structural_inhabitance_can_be_skipped() {
        let concept = entry("concept");

        let report = CheckMode::Review.check_entries_with_structural_inhabitance(
            [&concept],
            &structural_settings(),
            false,
        );

        assert!(report.is_clean());
    }

    #[test]
    fn unconfigured_structural_fields_warn() {
        let mut concept = entry("concept");
        concept.metadata.push_structural_target(FIELD_TOPIC, EntryAddress::new("meta").unwrap());

        let report = CheckMode::Review.check_entries([&concept], &StructuralSettings::default());

        assert_eq!(report.diagnostics()[0].kind, CheckDiagnosticKind::UnconfiguredStructuralField);
        assert_eq!(report.diagnostics()[0].severity, CheckSeverity::Warning);
        assert!(!report.has_errors());
    }

    #[test]
    fn category_metadata_warns_when_category_entry_is_missing() {
        let mut concept = entry("concept");
        concept.metadata.push_structural_target(FIELD_CATEGORY, EntryAddress::new("meta").unwrap());
        let mut meta = entry("meta");
        meta.metadata
            .push_structural_target(FIELD_CATEGORY, EntryAddress::new("category").unwrap());

        let report = CheckMode::Review.check_entries([&concept, &meta], &category_settings());

        assert!(
            report
                .diagnostics()
                .iter()
                .any(|diagnostic| diagnostic.kind == CheckDiagnosticKind::MissingCategoryEntry
                    && diagnostic.severity == CheckSeverity::Warning)
        );
    }

    #[test]
    fn review_mode_reports_category_target_without_category_marker_as_error() {
        let mut concept = entry("concept");
        concept.metadata.push_structural_target(FIELD_CATEGORY, EntryAddress::new("meta").unwrap());
        let meta = entry("meta");
        let mut category = entry("category");
        category
            .metadata
            .push_structural_target(FIELD_CATEGORY, EntryAddress::new("category").unwrap());

        let report =
            CheckMode::Review.check_entries([&concept, &meta, &category], &category_settings());

        let diagnostic = report
            .diagnostics()
            .iter()
            .find(|diagnostic| {
                diagnostic.kind == CheckDiagnosticKind::CategoryTargetMissingCategoryMarker
            })
            .expect("category target marker diagnostic");
        assert_eq!(diagnostic.entry.as_ref().unwrap().as_str(), "meta");
        assert_eq!(diagnostic.severity, CheckSeverity::Error);
        assert!(report.has_errors());
    }

    #[test]
    fn edit_mode_reports_category_target_without_category_marker_as_warning() {
        let mut concept = entry("concept");
        concept.metadata.push_structural_target(FIELD_CATEGORY, EntryAddress::new("meta").unwrap());
        let meta = entry("meta");
        let mut category = entry("category");
        category
            .metadata
            .push_structural_target(FIELD_CATEGORY, EntryAddress::new("category").unwrap());

        let report =
            CheckMode::Edit.check_entries([&concept, &meta, &category], &category_settings());

        let diagnostic = report
            .diagnostics()
            .iter()
            .find(|diagnostic| {
                diagnostic.kind == CheckDiagnosticKind::CategoryTargetMissingCategoryMarker
            })
            .expect("category target marker diagnostic");
        assert_eq!(diagnostic.severity, CheckSeverity::Warning);
        assert!(!report.has_errors());
    }
}