loftspec 2.0.1

The Loft Specification Format: document model, identity, canonical bytes, hashing and conversion
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
//! The lint configuration in the repository (F-23, ADR-11): `spec/lint.yaml` disables rules, sets
//! severities, edits lexicons, sets thresholds and records suppressions. Without the file the
//! defaults apply (AC-426). A rule, severity or field the Format does not define is an error at
//! its file, line and column, and no finding is reported then (RQ-174).

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

use super::defaults::{self, Kind, OPTIONS};
use super::lexicon::{self, Edits, Lexicon};
use super::{RuleId, Severity};
use crate::codec::{LINT, Problem, ReadError, SpecPath};
use crate::identity::Key;
use crate::yaml::{self, Entry, Node, Position, Value};

/// LQ-008's comparison: names of at least `min_tokens` tokens are near-duplicates when their
/// similarity reaches `threshold` millionths.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Similarity {
    pub min_tokens: usize,
    pub threshold: u32,
}

/// The value of a rule's option, of the [`Kind`] the option takes.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Setting {
    Lexicon(Lexicon),
    Count(usize),
    Millionths(u32),
    Names(Vec<String>),
}

impl Setting {
    fn default_of(kind: &Kind) -> Self {
        match kind {
            Kind::Lexicon(terms) => {
                Self::Lexicon(lexicon::effective(terms, None).expect("a valid default"))
            }
            Kind::Count { default, .. } => Self::Count(*default),
            Kind::Millionths(default) => Self::Millionths(*default),
            Kind::Names => Self::Names(Vec::new()),
        }
    }
}

/// An effective lint configuration: every rule's switch and severity, every option, and the
/// suppressions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LintConfig {
    rules: BTreeMap<RuleId, (bool, Severity)>,
    options: BTreeMap<(RuleId, &'static str), Setting>,
    suppressions: BTreeSet<(RuleId, Key)>,
}

impl Default for LintConfig {
    fn default() -> Self {
        Self {
            rules: RuleId::ALL
                .iter()
                .map(|rule| (*rule, (rule.enabled_by_default(), rule.default_severity())))
                .collect(),
            options: OPTIONS
                .iter()
                .map(|(rule, key, kind)| ((*rule, *key), Setting::default_of(kind)))
                .collect(),
            suppressions: BTreeSet::new(),
        }
    }
}

impl LintConfig {
    /// Reads `spec/lint.yaml`; no file means the defaults.
    ///
    /// # Errors
    ///
    /// Every rule, severity, field or value the file states that the Format does not define,
    /// each at its line and column.
    pub fn read(bytes: Option<&[u8]>) -> Result<Self, Vec<ReadError>> {
        let path = SpecPath::new(LINT);
        let mut config = Self::default();
        let Some(bytes) = bytes else {
            return Ok(config);
        };
        let root = yaml::read(bytes).map_err(|error| vec![ReadError::yaml(&path, error)])?;
        let mut reader = Reader {
            path,
            errors: Vec::new(),
        };
        if let Some(root) = root {
            reader.file(&root, &mut config);
        }
        if reader.errors.is_empty() {
            Ok(config)
        } else {
            Err(reader.errors)
        }
    }

    #[must_use]
    pub fn enabled(&self, rule: RuleId) -> bool {
        self.rules[&rule].0
    }

    #[must_use]
    pub fn severity(&self, rule: RuleId) -> Severity {
        self.rules[&rule].1
    }

    /// Whether a suppression names `rule` and one of `keys` (AC-675).
    #[must_use]
    pub fn suppresses(&self, rule: RuleId, keys: &[Key]) -> bool {
        keys.iter()
            .any(|key| self.suppressions.contains(&(rule, *key)))
    }

    /// The lexicon of a rule that takes one: `LQ-001`..`LQ-004` and `V2-007`.
    #[must_use]
    pub fn lexicon(&self, rule: RuleId) -> &Lexicon {
        self.lexicon_at(rule, "lexicon")
    }

    #[must_use]
    pub fn modals(&self) -> &Lexicon {
        self.lexicon_at(RuleId::Lq005, "modalLexicon")
    }

    #[must_use]
    pub fn conjunctions(&self) -> &Lexicon {
        self.lexicon_at(RuleId::Lq005, "conjunctionLexicon")
    }

    #[must_use]
    pub fn conjunction_threshold(&self) -> usize {
        self.count(RuleId::Lq005, "conjunctionThreshold")
    }

    #[must_use]
    pub fn similarity(&self) -> Similarity {
        let Setting::Millionths(threshold) = self.options[&(RuleId::Lq008, "threshold")] else {
            unreachable!("`threshold` is a decimal");
        };
        Similarity {
            min_tokens: self.count(RuleId::Lq008, "minTokens"),
            threshold,
        }
    }

    /// `V2-006`'s limit on a Requirement's criteria.
    #[must_use]
    pub fn max_criteria(&self) -> usize {
        self.count(RuleId::V2006, "maxCriteria")
    }

    /// `V2-006`'s limit on the words of a Requirement's body.
    #[must_use]
    pub fn max_body_words(&self) -> usize {
        self.count(RuleId::V2006, "maxBodyWords")
    }

    /// The proper names `V2-008` reads, each matched whole and in its own case.
    #[must_use]
    pub fn proper_names(&self) -> &[String] {
        let Setting::Names(names) = &self.options[&(RuleId::V2008, "properNames")] else {
            unreachable!("`properNames` is a list of names");
        };
        names
    }

    // Each option holds the setting of its kind: the defaults and the reader both follow
    // `OPTIONS`.
    fn lexicon_at(&self, rule: RuleId, key: &'static str) -> &Lexicon {
        let Setting::Lexicon(lexicon) = &self.options[&(rule, key)] else {
            unreachable!("`{key}` is a lexicon");
        };
        lexicon
    }

    fn count(&self, rule: RuleId, key: &'static str) -> usize {
        let Setting::Count(count) = self.options[&(rule, key)] else {
            unreachable!("`{key}` is a count");
        };
        count
    }
}

/// A threshold in millionths, written as a decimal in (0, 1] with at most six places.
pub(super) fn millionths_text(millionths: u32) -> String {
    let text = format!("{}.{:06}", millionths / 1_000_000, millionths % 1_000_000);
    text.trim_end_matches('0').trim_end_matches('.').to_owned()
}

fn parse_millionths(text: &str) -> Option<u32> {
    let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
    let digits = |part: &str| part.chars().all(|c| c.is_ascii_digit());
    if whole.is_empty() || !digits(whole) || !digits(fraction) || fraction.len() > 6 {
        return None;
    }
    let whole: u32 = whole.parse().ok()?;
    let fraction: u32 = format!("{fraction:0<6}").parse().ok()?;
    let value = whole.checked_mul(1_000_000)?.checked_add(fraction)?;
    (1..=1_000_000).contains(&value).then_some(value)
}

struct Reader {
    path: SpecPath,
    errors: Vec<ReadError>,
}

impl Reader {
    fn fail(&mut self, position: Position, problem: Problem) {
        self.errors
            .push(ReadError::at(&self.path, Some(position), problem));
    }

    fn entries<'a>(&mut self, node: &'a Node) -> &'a [Entry] {
        if let Value::Mapping(entries) = &node.value {
            return entries;
        }
        self.fail(node.position, Problem::Expected("a mapping"));
        &[]
    }

    /// A sequence's items; a field written with no value holds none.
    fn items<'a>(&mut self, node: &'a Node) -> &'a [Node] {
        match &node.value {
            Value::Sequence(items) => items,
            Value::Empty => &[],
            _ => {
                self.fail(node.position, Problem::Expected("a sequence"));
                &[]
            }
        }
    }

    fn scalar<'a>(&mut self, node: &'a Node) -> Option<&'a str> {
        if let Value::Scalar(scalar) = &node.value {
            return Some(&scalar.text);
        }
        self.fail(node.position, Problem::Expected("a scalar"));
        None
    }

    fn file(&mut self, root: &Node, config: &mut LintConfig) {
        for entry in self.entries(root) {
            match entry.key.as_str() {
                "rules" => self.rules(&entry.value, config),
                "suppressions" => self.suppressions(&entry.value, config),
                other => self.fail(entry.key_position, Problem::UnknownField(other.to_owned())),
            }
        }
    }

    fn rules(&mut self, node: &Node, config: &mut LintConfig) {
        for item in self.items(node) {
            self.rule(item, config);
        }
    }

    fn suppressions(&mut self, node: &Node, config: &mut LintConfig) {
        for item in self.items(node) {
            self.suppression(item, config);
        }
    }

    /// A rule's entry: `rule`, its id, then the options it sets.
    fn rule(&mut self, item: &Node, config: &mut LintConfig) {
        let entries = self.entries(item);
        let Some(named) = entries.iter().find(|entry| entry.key == "rule") else {
            if !entries.is_empty() {
                self.fail(item.position, Problem::MissingField("rule"));
            }
            return;
        };
        let Some(rule) = self.parsed(&named.value, "a rule the Format defines", RuleId::parse)
        else {
            return;
        };
        for option in entries.iter().filter(|entry| entry.key != "rule") {
            self.option(rule, option, config);
        }
    }

    fn option(&mut self, rule: RuleId, option: &Entry, config: &mut LintConfig) {
        let value = &option.value;
        match option.key.as_str() {
            "enabled" => {
                if let Some(enabled) = self.parsed(value, "`true` or `false`", |text| match text {
                    "true" => Some(true),
                    "false" => Some(false),
                    _ => None,
                }) {
                    config.rules.get_mut(&rule).expect("every rule").0 = enabled;
                }
            }
            "severity" => {
                if let Some(severity) = self.parsed(value, "warning, info or hint", Severity::parse)
                {
                    config.rules.get_mut(&rule).expect("every rule").1 = severity;
                }
            }
            key => {
                let Some((key, kind)) = defaults::option(rule, key) else {
                    let unknown = Problem::UnknownField(key.to_owned());
                    return self.fail(option.key_position, unknown);
                };
                if let Some(setting) = self.setting(value, kind) {
                    config.options.insert((rule, key), setting);
                }
            }
        }
    }

    fn parsed<T>(
        &mut self,
        node: &Node,
        expected: &'static str,
        parse: impl Fn(&str) -> Option<T>,
    ) -> Option<T> {
        let text = self.scalar(node)?;
        let parsed = parse(text);
        if parsed.is_none() {
            let value = text.to_owned();
            self.fail(node.position, Problem::Invalid { value, expected });
        }
        parsed
    }

    /// An option's setting, read as its kind reads.
    fn setting(&mut self, node: &Node, kind: &Kind) -> Option<Setting> {
        match kind {
            Kind::Lexicon(defaults) => self.lexicon(node, defaults).map(Setting::Lexicon),
            Kind::Count {
                least, expected, ..
            } => {
                let count = |text: &str| text.parse().ok().filter(|count| count >= least);
                self.parsed(node, expected, count).map(Setting::Count)
            }
            Kind::Millionths(_) => {
                let expected = "a decimal above 0 and at most 1, with at most six places";
                self.parsed(node, expected, parse_millionths)
                    .map(Setting::Millionths)
            }
            Kind::Names => self.names(node).map(Setting::Names),
        }
    }

    /// A sequence of names, none of them blank; each blank name is an error.
    fn names(&mut self, node: &Node) -> Option<Vec<String>> {
        let errors = self.errors.len();
        let names: Vec<String> = self
            .items(node)
            .iter()
            .filter_map(|item| {
                self.parsed(item, "a name", |text| {
                    (!text.trim().is_empty()).then(|| text.to_owned())
                })
            })
            .collect();
        (self.errors.len() == errors).then_some(names)
    }

    fn lexicon(&mut self, node: &Node, defaults: &[&str]) -> Option<Lexicon> {
        let mut edits = Edits::default();
        for entry in self.entries(node) {
            let mut phrases = Vec::new();
            for item in self.items(&entry.value) {
                phrases.extend(self.scalar(item).map(str::to_owned));
            }
            match entry.key.as_str() {
                "replace" => edits.replace = Some(phrases),
                "extend" => edits.extend = phrases,
                "remove" => edits.remove = phrases,
                other => self.fail(entry.key_position, Problem::UnknownField(other.to_owned())),
            }
        }
        lexicon::effective(defaults, Some(&edits))
            .map_err(|problem| self.fail(node.position, Problem::Shape(problem)))
            .ok()
    }

    fn suppression(&mut self, item: &Node, config: &mut LintConfig) {
        let entries = self.entries(item);
        let field = |name: &str| entries.iter().find(|entry| entry.key == name);
        for entry in entries {
            if !matches!(entry.key.as_str(), "rule" | "key" | "reason") {
                self.fail(entry.key_position, Problem::UnknownField(entry.key.clone()));
            }
        }
        let mut required = |name: &'static str| {
            let found = field(name);
            if found.is_none() {
                self.errors.push(ReadError::at(
                    &self.path,
                    Some(item.position),
                    Problem::MissingField(name),
                ));
            }
            found
        };
        let (rule, key, reason) = (required("rule"), required("key"), required("reason"));
        let rule = rule
            .and_then(|rule| self.parsed(&rule.value, "a rule the Format defines", RuleId::parse));
        let key =
            key.and_then(|key| self.parsed(&key.value, "a key", |text| Key::parse(text).ok()));
        let reason = reason.and_then(|reason| {
            self.parsed(&reason.value, "a reason", |text| {
                (!text.trim().is_empty()).then_some(())
            })
        });
        if let (Some(rule), Some(key), Some(())) = (rule, key, reason) {
            config.suppressions.insert((rule, key));
        }
    }
}