omnicoach 0.3.0

Lightweight, high-signal static analysis and command linter for Python and Rust
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
//! Rule options: each rule declares its options once, as a typed `const` value; the config
//! loader validates every `[rules.<name>]` table against that declaration once, at load; and
//! the rule receives the values resolved for each file, typed by the declaration.

use std::collections::{HashMap, HashSet};

use strum::{EnumIter, IntoEnumIterator as _, IntoStaticStr, VariantArray as _};

use super::closest_match;
use crate::diagnostic::Language;

/// Compile-time static descriptor for default filter lists (both allowlists and denylists).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FilterListDefaults {
    /// Base items active across all supported languages.
    pub base: &'static [&'static str],
    /// Language-specific items added to the base defaults.
    pub extend: &'static [(Language, &'static [&'static str])],
    /// Language-specific items removed from the base defaults.
    pub remove: &'static [(Language, &'static [&'static str])],
}

impl FilterListDefaults {
    /// Resolves the default set of strings for a specific language.
    #[must_use]
    pub fn resolve_default_for_lang(&self, lang: Language) -> HashSet<String> {
        let mut set: HashSet<String> = self.base.iter().map(|&item| item.to_string()).collect();
        for &(target_lang, items) in self.extend {
            if target_lang == lang {
                set.extend(items.iter().map(|&item| item.to_string()));
            }
        }
        for &(target_lang, items) in self.remove {
            if target_lang == lang {
                for &item in items {
                    set.remove(item);
                }
            }
        }
        set
    }
}

/// Compile-time static descriptor for scalar or structured default configuration values
/// with optional per-language overrides.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LanguageDefaults<T: Copy + 'static> {
    /// Default value active across all supported languages unless overridden.
    pub base: T,
    /// Language-specific default values that override `base`.
    pub overrides: &'static [(Language, T)],
}

impl<T: Copy + 'static> LanguageDefaults<T> {
    /// Creates a new static language-aware default descriptor.
    #[must_use]
    pub const fn new(base: T, overrides: &'static [(Language, T)]) -> Self {
        Self { base, overrides }
    }

    /// Resolves the compile-time default value for a specific language.
    #[must_use]
    pub fn resolve_default_for_lang(&self, lang: Language) -> T {
        language_override(self.overrides, lang).unwrap_or(self.base)
    }
}

/// Enforcement mode for rules targeting sensitive language constructs
/// (e.g. `cast`, `suppress`, `getattr`, `except Exception`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumIter, IntoStaticStr)]
#[strum(serialize_all = "kebab-case")]
pub enum EnforcementMode {
    /// Completely bans the construct from targeted files (only suppressible via `# omni:ignore`).
    Ban,
    /// Permits the construct only if accompanied by an explanatory comment.
    RequireExplanation,
}

impl EnforcementMode {
    /// The key setting a code rule's enforcement mode under `[rules.<name>]`.
    pub const KEY: &'static str = "enforcement-mode";

    /// What each mode does, for `--explain`.
    pub const DOC: &'static str = "`ban` flags every occurrence; `require-explanation` accepts \
                                   an occurrence explained by a comment at the end of its line \
                                   or in the comment lines directly above it. A comment at the \
                                   end of any header line of the enclosing statement, or directly \
                                   above that header (above the first decorator, if any), also \
                                   counts and excuses every finding on that header, from any rule \
                                   in this mode; the body of a block statement is not part of its \
                                   header. The comment needs at least three words; docstrings, \
                                   Rust doc comments (`///`, `//!`, `/** */`, `/*! */`), and bare \
                                   tool directives such as `noqa` or `type: ignore` do not count, \
                                   but a reason written after a directive does.";

    /// How to excuse a finding in `require-explanation` mode, shown with each finding.
    pub const EXPLANATION_HINT: &'static str =
        "Explain why in a comment at the end of the flagged line or directly above it.";
}

/// The options a rule declares, as a typed value: nothing (`()`), one [`CountOption`], one
/// [`ListOption`], or a pair of declarations.
///
/// The declaration fixes the type of the values the rule receives, so a rule can only read
/// the options it declares.
pub trait OptionsDeclaration: Copy + 'static {
    /// The owned values resolved for one file.
    type Resolved;

    /// What a check function receives: by value for `()` and `usize`, by reference for a
    /// `HashSet<String>`, or a pair of those.
    type Param<'a>;

    /// Borrows or copies `resolved` into the check function's parameter.
    fn as_param(resolved: &Self::Resolved) -> Self::Param<'_>;

    /// Every declared option, in declaration order, for validation and `--explain`.
    fn specs(self) -> Vec<OptionSpec>;

    /// The values for a file in `language`, resolved across the declared default for
    /// `language`, the rule table, and the language table.
    fn resolve(self, language: Language, overrides: Option<&RuleOverrides>) -> Self::Resolved;
}

impl OptionsDeclaration for () {
    type Resolved = ();
    type Param<'a> = ();

    fn as_param(&(): &()) {}

    fn specs(self) -> Vec<OptionSpec> {
        Vec::new()
    }

    fn resolve(self, _language: Language, _overrides: Option<&RuleOverrides>) {}
}

/// A non-negative integer option, such as the maximum number of assertions in one test.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CountOption {
    /// The TOML key, naming what is counted (`max-assertions`, not `max`).
    pub key: &'static str,
    /// One sentence saying what the value bounds.
    pub doc: &'static str,
    /// The default value, per language.
    pub default: LanguageDefaults<usize>,
}

impl OptionsDeclaration for CountOption {
    type Resolved = usize;
    type Param<'a> = usize;

    fn as_param(&count: &usize) -> usize {
        count
    }

    fn specs(self) -> Vec<OptionSpec> {
        vec![OptionSpec::Count(self)]
    }

    fn resolve(self, language: Language, overrides: Option<&RuleOverrides>) -> usize {
        layers(overrides, language)
            .find_map(|values| values.counts.get(self.key).copied())
            .unwrap_or_else(|| self.default.resolve_default_for_lang(language))
    }
}

/// Whether a list option holds the items a rule flags or the items it accepts. The kind
/// fixes the option's three keys, so a rule declares at most one list option.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ListKind {
    /// Items the rule flags: `banned`, `extend-banned` and `remove-banned`.
    Deny,
    /// Items the rule accepts: `allowed`, `extend-allowed` and `remove-allowed`.
    Allow,
}

impl ListKind {
    /// The key whose items replace the inherited set.
    #[must_use]
    pub const fn replace_key(self) -> &'static str {
        match self {
            Self::Deny => "banned",
            Self::Allow => "allowed",
        }
    }

    /// The key whose items are added to the inherited set.
    #[must_use]
    pub const fn extend_key(self) -> &'static str {
        match self {
            Self::Deny => "extend-banned",
            Self::Allow => "extend-allowed",
        }
    }

    /// The key whose items are removed from the inherited set.
    #[must_use]
    pub const fn remove_key(self) -> &'static str {
        match self {
            Self::Deny => "remove-banned",
            Self::Allow => "remove-allowed",
        }
    }
}

/// A list-of-strings option, such as the abbreviations a rule bans.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ListOption {
    /// Whether the items are flagged or accepted; fixes the option's keys.
    pub kind: ListKind,
    /// One sentence saying what the items are.
    pub doc: &'static str,
    /// The default items, per language.
    pub default: FilterListDefaults,
}

impl OptionsDeclaration for ListOption {
    type Resolved = HashSet<String>;
    type Param<'a> = &'a HashSet<String>;

    fn as_param(items: &HashSet<String>) -> &HashSet<String> {
        items
    }

    fn specs(self) -> Vec<OptionSpec> {
        vec![OptionSpec::List(self)]
    }

    /// Starts with the declared default for `language`, then applies the rule table and the
    /// language table in order (`replace`, then `extend`, then `remove` within each table).
    fn resolve(self, language: Language, overrides: Option<&RuleOverrides>) -> HashSet<String> {
        let mut items = self.default.resolve_default_for_lang(language);
        if let Some(overrides) = overrides {
            overrides.global.list.apply_to(&mut items);
            if let Some(language_values) = overrides.for_language(language) {
                language_values.list.apply_to(&mut items);
            }
        }
        items
    }
}

impl<First: OptionsDeclaration, Second: OptionsDeclaration> OptionsDeclaration for (First, Second) {
    type Resolved = (First::Resolved, Second::Resolved);
    type Param<'a> = (First::Param<'a>, Second::Param<'a>);

    fn as_param((first, second): &Self::Resolved) -> Self::Param<'_> {
        (First::as_param(first), Second::as_param(second))
    }

    fn specs(self) -> Vec<OptionSpec> {
        let (first, second) = self;
        let mut specs = first.specs();
        specs.extend(second.specs());
        specs
    }

    fn resolve(self, language: Language, overrides: Option<&RuleOverrides>) -> Self::Resolved {
        let (first, second) = self;
        (
            first.resolve(language, overrides),
            second.resolve(language, overrides),
        )
    }
}

/// One declared option of a rule.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OptionSpec {
    /// A count, under one key.
    Count(CountOption),
    /// A list, under the three keys of its kind.
    List(ListOption),
}

impl OptionSpec {
    /// The TOML keys the option accepts.
    #[must_use]
    pub fn keys(self) -> Vec<&'static str> {
        match self {
            Self::Count(option) => vec![option.key],
            Self::List(option) => vec![
                option.kind.replace_key(),
                option.kind.extend_key(),
                option.kind.remove_key(),
            ],
        }
    }
}

/// Everything a rule accepts under `[rules.<name>]` and `[rules.<name>.<language>]`.
/// A key that is not declared here is rejected at load.
///
/// A code rule declares its [`CountOption`] / [`ListOption`] consts next to its declaration
/// and passes them to [`Self::code_rule`]; its check function then receives the values as
/// [`OptionsDeclaration::Param`]. `--explain` renders every key, doc and default from this
/// declaration, so the rule's prose never repeats them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RuleOptions<Options: OptionsDeclaration> {
    /// The default `enforcement-mode`, or `None` if the rule rejects the key because its
    /// runner always reports every finding.
    pub enforcement_mode: Option<LanguageDefaults<EnforcementMode>>,
    /// The rule's own options.
    pub options: Options,
}

impl<Options: OptionsDeclaration> RuleOptions<Options> {
    /// A code rule with `options` and an `enforcement-mode` defaulting to `ban`.
    #[must_use]
    pub const fn code_rule(options: Options) -> Self {
        Self {
            enforcement_mode: Some(LanguageDefaults::new(EnforcementMode::Ban, &[])),
            options,
        }
    }

    /// The declaration with its options listed rather than typed, for validation and
    /// `--explain`.
    #[must_use]
    pub fn declared(&self) -> DeclaredOptions {
        DeclaredOptions {
            enforcement_mode: self.enforcement_mode,
            options: self.options.specs(),
        }
    }

    /// The enforcement mode for a file in `language`; `ban` for a rule that declares none.
    #[must_use]
    pub fn enforcement_mode(
        &self,
        language: Language,
        overrides: Option<&RuleOverrides>,
    ) -> EnforcementMode {
        resolve_enforcement_mode(self.enforcement_mode, language, overrides)
    }
}

impl RuleOptions<()> {
    /// A rule that accepts no options, not even `enforcement-mode`.
    #[must_use]
    pub const fn none() -> Self {
        Self {
            enforcement_mode: None,
            options: (),
        }
    }
}

/// A rule's options listed rather than typed: what the config loader validates against and
/// what `--explain` documents.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeclaredOptions {
    /// The default `enforcement-mode`, or `None` if the rule rejects the key.
    pub enforcement_mode: Option<LanguageDefaults<EnforcementMode>>,
    /// The rule's own options, in declaration order.
    pub options: Vec<OptionSpec>,
}

impl DeclaredOptions {
    /// Every key accepted in a rule or language table, in declaration order.
    #[must_use]
    pub fn keys(&self) -> Vec<&'static str> {
        self.enforcement_mode
            .map(|_| EnforcementMode::KEY)
            .into_iter()
            .chain(self.options.iter().flat_map(|option| option.keys()))
            .collect()
    }

    /// The enforcement mode for a file in `language`; `ban` for a rule that declares none.
    #[must_use]
    pub fn enforcement_mode(
        &self,
        language: Language,
        overrides: Option<&RuleOverrides>,
    ) -> EnforcementMode {
        resolve_enforcement_mode(self.enforcement_mode, language, overrides)
    }

    /// Serializes a `[rules.<rule_name>]` TOML snippet expressing the rule's default options,
    /// or `None` when the rule accepts no options.
    #[must_use]
    pub fn default_toml(
        &self,
        rule_name: crate::diagnostic::RuleName,
        languages: &[Language],
    ) -> Option<String> {
        let mut rule_table = toml::Table::new();
        if let Some(default) = self.enforcement_mode {
            rule_table.insert(
                EnforcementMode::KEY.into(),
                <&str>::from(default.base).into(),
            );
        }
        for option in &self.options {
            match option {
                OptionSpec::Count(count) => {
                    rule_table.insert(count.key.into(), toml_count(count.default.base));
                }
                OptionSpec::List(list) => {
                    rule_table.insert(
                        list.kind.replace_key().into(),
                        list.default.base.to_vec().into(),
                    );
                }
            }
        }
        if rule_table.is_empty() {
            return None;
        }
        for &language in languages {
            let mut lang_table = toml::Table::new();
            if let Some(default) = self.enforcement_mode
                && let Some(mode) = language_override(default.overrides, language)
            {
                lang_table.insert(EnforcementMode::KEY.into(), <&str>::from(mode).into());
            }
            for option in &self.options {
                match option {
                    OptionSpec::Count(count) => {
                        if let Some(value) = language_override(count.default.overrides, language) {
                            lang_table.insert(count.key.into(), toml_count(value));
                        }
                    }
                    OptionSpec::List(list) => {
                        for (key, entries) in [
                            (list.kind.extend_key(), list.default.extend),
                            (list.kind.remove_key(), list.default.remove),
                        ] {
                            if let Some(items) = language_override(entries, language) {
                                lang_table.insert(key.into(), items.to_vec().into());
                            }
                        }
                    }
                }
            }
            if !lang_table.is_empty() {
                rule_table.insert(language.as_str().into(), toml::Value::Table(lang_table));
            }
        }
        let rules = toml::Table::from_iter([(rule_name.0.into(), toml::Value::Table(rule_table))]);
        let root = toml::Table::from_iter([("rules".into(), toml::Value::Table(rules))]);
        toml::to_string(&root).ok()
    }
}

/// A rule's validated configuration: its `[rules.<name>]` values and its language tables.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RuleOverrides {
    global: OptionValues,
    per_language: Vec<(Language, OptionValues)>,
}

/// What is wrong with a `[rules]` entry.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum OptionProblem {
    /// A key the rule does not declare.
    #[error("unknown key; {}", match (suggestion, expected.as_slice()) {
        (Some(known), _) => format!("did you mean `{known}`?"),
        (None, []) => "this rule takes no options".to_owned(),
        (None, keys) => format!("expected one of `{}`", keys.join("`, `")),
    })]
    UnknownKey {
        /// The closest accepted key, if it looks like a typo.
        suggestion: Option<&'static str>,
        /// Every accepted key.
        expected: Vec<&'static str>,
    },
    /// A value of the wrong type.
    #[error("expected {expected}, found {found}")]
    WrongType {
        /// What the key accepts.
        expected: String,
        /// The value as written, or its type.
        found: String,
    },
    /// A table for a language the rule does not analyze.
    #[error("this rule does not analyze this language; it analyzes {analyzed}")]
    UnsupportedLanguage {
        /// The languages the rule analyzes, comma-separated.
        analyzed: String,
    },
    /// `enforcement-mode` on a rule whose runner always reports every finding.
    #[error("this rule has no enforcement mode; it always reports every finding")]
    EnforcementModeRejected,
}

/// A rejected `[rules]` entry: the key path as written, and what is wrong with it.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("`{key_path}`: {problem}")]
pub struct RuleOptionsError {
    /// The dotted path to the entry, e.g. `rules.too-many-assertions.rust.max-assertions`.
    pub key_path: String,
    /// What is wrong with it.
    pub problem: OptionProblem,
}

impl RuleOverrides {
    /// Validates the `[rules.<rule_name>]` value against the rule's declaration.
    ///
    /// # Errors
    ///
    /// Returns [`RuleOptionsError`] on an undeclared key, a value of the wrong type, a table
    /// for a language the rule does not analyze, or `enforcement-mode` on a rule that
    /// rejects it.
    pub fn parse(
        rule_name: &str,
        declaration: &DeclaredOptions,
        supported_languages: &[Language],
        value: &toml::Value,
    ) -> Result<Self, RuleOptionsError> {
        let rule_path = format!("rules.{rule_name}");
        let mut overrides = Self::default();
        for (key, value) in expect_table(value, &rule_path)? {
            let key_path = format!("{rule_path}.{key}");
            match language_named(key) {
                Some(language) if supported_languages.contains(&language) => {
                    let mut values = OptionValues::default();
                    for (key, value) in expect_table(value, &key_path)? {
                        values.set(declaration, &[], &key_path, key, value)?;
                    }
                    overrides.per_language.push((language, values));
                }
                Some(_) => {
                    let analyzed: Vec<_> = supported_languages
                        .iter()
                        .map(|&language| language.as_str())
                        .collect();
                    return Err(RuleOptionsError {
                        key_path,
                        problem: OptionProblem::UnsupportedLanguage {
                            analyzed: analyzed.join(", "),
                        },
                    });
                }
                None => {
                    overrides.global.set(
                        declaration,
                        supported_languages,
                        &rule_path,
                        key,
                        value,
                    )?;
                }
            }
        }
        Ok(overrides)
    }

    fn for_language(&self, language: Language) -> Option<&OptionValues> {
        self.per_language
            .iter()
            .find_map(|(candidate, values)| (*candidate == language).then_some(values))
    }
}

fn toml_count(count: usize) -> toml::Value {
    toml::Value::Integer(i64::try_from(count).unwrap_or(i64::MAX))
}

fn resolve_enforcement_mode(
    default: Option<LanguageDefaults<EnforcementMode>>,
    language: Language,
    overrides: Option<&RuleOverrides>,
) -> EnforcementMode {
    layers(overrides, language)
        .find_map(|values| values.enforcement_mode)
        .unwrap_or_else(|| {
            default.map_or(EnforcementMode::Ban, |default| {
                default.resolve_default_for_lang(language)
            })
        })
}

fn language_override<T: Copy>(entries: &[(Language, T)], language: Language) -> Option<T> {
    entries
        .iter()
        .find_map(|&(target_lang, value)| (target_lang == language).then_some(value))
}

/// The validated values of one `[rules.<name>]` table or one of its language tables.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct OptionValues {
    enforcement_mode: Option<EnforcementMode>,
    /// Counts keyed by their declared [`CountOption::key`].
    counts: HashMap<&'static str, usize>,
    list: ListOverride,
}

impl OptionValues {
    /// Validates the entry `key = value` of the table at `table_path` and stores it.
    /// `languages` are the language tables also accepted in that table.
    fn set(
        &mut self,
        declaration: &DeclaredOptions,
        languages: &[Language],
        table_path: &str,
        key: &str,
        value: &toml::Value,
    ) -> Result<(), RuleOptionsError> {
        let key_path = format!("{table_path}.{key}");
        let error = |problem| RuleOptionsError {
            key_path: key_path.clone(),
            problem,
        };
        if key == EnforcementMode::KEY {
            if declaration.enforcement_mode.is_none() {
                return Err(error(OptionProblem::EnforcementModeRejected));
            }
            self.enforcement_mode = Some(parse_enforcement_mode(value).map_err(error)?);
            return Ok(());
        }
        for &option in &declaration.options {
            match option {
                OptionSpec::Count(count) if key == count.key => {
                    self.counts
                        .insert(count.key, parse_count(value).map_err(error)?);
                    return Ok(());
                }
                OptionSpec::List(list) if key == list.kind.replace_key() => {
                    self.list.replace = Some(parse_items(value).map_err(error)?);
                    return Ok(());
                }
                OptionSpec::List(list) if key == list.kind.extend_key() => {
                    self.list.extend = parse_items(value).map_err(error)?;
                    return Ok(());
                }
                OptionSpec::List(list) if key == list.kind.remove_key() => {
                    self.list.remove = parse_items(value).map_err(error)?;
                    return Ok(());
                }
                OptionSpec::Count(_) | OptionSpec::List(_) => {}
            }
        }
        let mut expected = declaration.keys();
        expected.extend(languages.iter().map(|&language| language.as_str()));
        Err(error(OptionProblem::UnknownKey {
            suggestion: closest_match(key, expected.iter().copied()),
            expected,
        }))
    }
}

/// The tables that apply to a file in `language`, most specific first: the language table,
/// then the rule table.
fn layers(
    overrides: Option<&RuleOverrides>,
    language: Language,
) -> impl Iterator<Item = &OptionValues> {
    overrides
        .and_then(move |overrides| overrides.for_language(language))
        .into_iter()
        .chain(overrides.map(|overrides| &overrides.global))
}

/// The items one table puts in place of, adds to, or removes from the inherited list.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct ListOverride {
    replace: Option<HashSet<String>>,
    extend: HashSet<String>,
    remove: HashSet<String>,
}

impl ListOverride {
    fn apply_to(&self, items: &mut HashSet<String>) {
        if let Some(replacement) = &self.replace {
            items.clone_from(replacement);
        }
        items.extend(self.extend.iter().cloned());
        for item in &self.remove {
            items.remove(item);
        }
    }
}

fn language_named(key: &str) -> Option<Language> {
    Language::VARIANTS
        .iter()
        .copied()
        .find(|&language| language.as_str() == key)
}

fn expect_table<'value>(
    value: &'value toml::Value,
    key_path: &str,
) -> Result<&'value toml::Table, RuleOptionsError> {
    value.as_table().ok_or_else(|| RuleOptionsError {
        key_path: key_path.to_owned(),
        problem: wrong_type("a table", value),
    })
}

fn parse_enforcement_mode(value: &toml::Value) -> Result<EnforcementMode, OptionProblem> {
    EnforcementMode::iter()
        .find(|&mode| value.as_str() == Some(mode.into()))
        .ok_or_else(|| {
            let labels: Vec<&str> = EnforcementMode::iter().map(Into::into).collect();
            wrong_type(&format!("`{}`", labels.join("` or `")), value)
        })
}

fn parse_count(value: &toml::Value) -> Result<usize, OptionProblem> {
    value
        .as_integer()
        .and_then(|number| usize::try_from(number).ok())
        .ok_or_else(|| wrong_type("a non-negative integer", value))
}

fn parse_items(value: &toml::Value) -> Result<HashSet<String>, OptionProblem> {
    value
        .as_array()
        .and_then(|items| {
            items
                .iter()
                .map(|item| item.as_str().map(str::to_owned))
                .collect()
        })
        .ok_or_else(|| wrong_type("an array of strings", value))
}

fn wrong_type(expected: &str, value: &toml::Value) -> OptionProblem {
    let found = match value {
        toml::Value::String(text) => format!("\"{text}\""),
        toml::Value::Integer(number) => number.to_string(),
        other => other.type_str().to_owned(),
    };
    OptionProblem::WrongType {
        expected: expected.to_owned(),
        found,
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;

    const LIMIT: CountOption = CountOption {
        key: "max-items",
        doc: "Maximum items.",
        default: LanguageDefaults::new(4, &[(Language::Rust, 6)]),
    };

    const DENY: ListOption = ListOption {
        kind: ListKind::Deny,
        doc: "Banned words.",
        default: FilterListDefaults {
            base: &["default_one", "common_ok"],
            extend: &[],
            remove: &[],
        },
    };

    const ALLOW: ListOption = ListOption {
        kind: ListKind::Allow,
        doc: "Allowed words.",
        default: FilterListDefaults {
            base: &["default_base"],
            extend: &[(Language::Rust, &["rust_extra"])],
            remove: &[],
        },
    };

    const WITH_COUNT: RuleOptions<CountOption> = RuleOptions {
        enforcement_mode: Some(LanguageDefaults::new(
            EnforcementMode::Ban,
            &[(Language::Rust, EnforcementMode::RequireExplanation)],
        )),
        options: LIMIT,
    };
    const DENYING_RULE: RuleOptions<ListOption> = RuleOptions::code_rule(DENY);

    const BOTH_LANGUAGES: &[Language] = &[Language::Python, Language::Rust];

    fn parse(
        declaration: &DeclaredOptions,
        languages: &[Language],
        toml_content: &str,
    ) -> Result<RuleOverrides, RuleOptionsError> {
        let value = toml::Value::Table(toml::from_str(toml_content).unwrap());
        RuleOverrides::parse("some-rule", declaration, languages, &value)
    }

    fn words(items: &[&str]) -> HashSet<String> {
        items.iter().map(|&item| item.to_owned()).collect()
    }

    #[test]
    fn test_filter_list_defaults_resolve() {
        const DEFAULTS: FilterListDefaults = FilterListDefaults {
            base: &["common", "shared", "temp"],
            extend: &[(Language::Rust, &["rust_only"])],
            remove: &[(Language::Rust, &["temp"])],
        };

        let python_defaults = DEFAULTS.resolve_default_for_lang(Language::Python);
        let rust_defaults = DEFAULTS.resolve_default_for_lang(Language::Rust);
        assert_eq!(
            python_defaults,
            HashSet::from(["common", "shared", "temp"].map(String::from))
        );
        assert_eq!(
            rust_defaults,
            HashSet::from(["common", "shared", "rust_only"].map(String::from))
        );
    }

    #[rstest]
    #[case::python_default("", Language::Python, 4)]
    #[case::rust_default("", Language::Rust, 6)]
    #[case::rule_table("max-items = 5", Language::Rust, 5)]
    #[case::other_language_table(indoc::indoc! {r"
        max-items = 5
        [rust]
        max-items = 10"}, Language::Python, 5)]
    #[case::language_table(indoc::indoc! {r"
        max-items = 5
        [rust]
        max-items = 10"}, Language::Rust, 10)]
    fn count_prefers_language_then_rule_table_then_default(
        #[case] toml_content: &str,
        #[case] language: Language,
        #[case] expected: usize,
    ) {
        let overrides = parse(&WITH_COUNT.declared(), BOTH_LANGUAGES, toml_content).unwrap();
        assert_eq!(LIMIT.resolve(language, Some(&overrides)), expected);
    }

    #[rstest]
    #[case::python_default("", Language::Python, EnforcementMode::Ban)]
    #[case::rust_default("", Language::Rust, EnforcementMode::RequireExplanation)]
    #[case::rule_table("enforcement-mode = \"ban\"", Language::Rust, EnforcementMode::Ban)]
    #[case::language_table(
        indoc::indoc! {r#"
            enforcement-mode = "ban"
            [python]
            enforcement-mode = "require-explanation""#},
        Language::Python,
        EnforcementMode::RequireExplanation
    )]
    fn enforcement_mode_prefers_language_then_rule_table_then_default(
        #[case] toml_content: &str,
        #[case] language: Language,
        #[case] expected: EnforcementMode,
    ) {
        let overrides = parse(&WITH_COUNT.declared(), BOTH_LANGUAGES, toml_content).unwrap();
        assert_eq!(
            WITH_COUNT.enforcement_mode(language, Some(&overrides)),
            expected
        );
    }

    #[rstest]
    #[case::deny(
        DENY,
        indoc::indoc! {r#"
            extend-banned = ["global_bad", "rust_ok"]
            remove-banned = ["common_ok"]

            [rust]
            extend-banned = ["rust_bad"]
            remove-banned = ["rust_ok"]

            [python]
            banned = ["py_only_bad", "py_dropped"]
            extend-banned = ["py_extra"]
            remove-banned = ["py_dropped"]
        "#},
        &["default_one", "global_bad", "rust_bad"],
        &["py_only_bad", "py_extra"]
    )]
    #[case::allow(
        ALLOW,
        indoc::indoc! {r#"
            extend-allowed = ["global_allowed", "rust_revoked"]
            remove-allowed = ["default_base"]

            [rust]
            extend-allowed = ["rust_allowed", "default_base"]
            remove-allowed = ["rust_revoked"]

            [python]
            allowed = ["py_only_allowed"]
        "#},
        &["default_base", "rust_extra", "global_allowed", "rust_allowed"],
        &["py_only_allowed"]
    )]
    fn list_applies_global_table_then_language_table(
        #[case] option: ListOption,
        #[case] toml_content: &str,
        #[case] rust_expected: &[&str],
        #[case] python_expected: &[&str],
    ) {
        let overrides = parse(
            &RuleOptions::code_rule(option).declared(),
            BOTH_LANGUAGES,
            toml_content,
        )
        .unwrap();

        let rust = option.resolve(Language::Rust, Some(&overrides));
        let python = option.resolve(Language::Python, Some(&overrides));
        assert_eq!(rust, words(rust_expected));
        assert_eq!(python, words(python_expected));
    }

    #[test]
    fn a_pair_resolves_each_member_and_lists_both_specs() {
        let pair = (LIMIT, DENY);
        let overrides = parse(
            &RuleOptions::code_rule(pair).declared(),
            BOTH_LANGUAGES,
            "max-items = 9\nbanned = [\"only\"]",
        )
        .unwrap();
        assert_eq!(
            pair.specs(),
            vec![OptionSpec::Count(LIMIT), OptionSpec::List(DENY)]
        );
        assert_eq!(
            pair.resolve(Language::Python, Some(&overrides)),
            (9, words(&["only"]))
        );
    }

    #[test]
    fn missing_overrides_resolve_to_defaults() {
        assert_eq!(LIMIT.resolve(Language::Rust, None), 6);
        assert_eq!(
            WITH_COUNT.enforcement_mode(Language::Rust, None),
            EnforcementMode::RequireExplanation
        );
    }

    #[rstest]
    #[case::typo(
        WITH_COUNT.declared(),
        BOTH_LANGUAGES,
        "max-itemz = 5",
        "`rules.some-rule.max-itemz`: unknown key; did you mean `max-items`?"
    )]
    #[case::unrelated_key(
        DENYING_RULE.declared(),
        &[Language::Python],
        "colour = 1",
        "`rules.some-rule.colour`: unknown key; expected one of `enforcement-mode`, `banned`, \
         `extend-banned`, `remove-banned`, `python`"
    )]
    #[case::no_options(
        RuleOptions::none().declared(),
        &[],
        "max = 1",
        "`rules.some-rule.max`: unknown key; this rule takes no options"
    )]
    #[case::count_wrong_type(
        WITH_COUNT.declared(),
        BOTH_LANGUAGES,
        "max-items = \"five\"",
        "`rules.some-rule.max-items`: expected a non-negative integer, found \"five\""
    )]
    #[case::negative_count(
        WITH_COUNT.declared(),
        BOTH_LANGUAGES,
        "max-items = -1",
        "`rules.some-rule.max-items`: expected a non-negative integer, found -1"
    )]
    #[case::list_wrong_type(
        DENYING_RULE.declared(),
        BOTH_LANGUAGES,
        "extend-banned = [\"ok\", 3]",
        "`rules.some-rule.extend-banned`: expected an array of strings, found array"
    )]
    #[case::enforcement_mode_wrong_value(
        WITH_COUNT.declared(),
        BOTH_LANGUAGES,
        "enforcement-mode = \"bann\"",
        "`rules.some-rule.enforcement-mode`: expected `ban` or `require-explanation`, \
         found \"bann\""
    )]
    #[case::language_not_a_table(
        WITH_COUNT.declared(),
        BOTH_LANGUAGES,
        "rust = 1",
        "`rules.some-rule.rust`: expected a table, found 1"
    )]
    #[case::unsupported_language(
        WITH_COUNT.declared(),
        &[Language::Python],
        "[rust]\nmax-items = 1",
        "`rules.some-rule.rust`: this rule does not analyze this language; it analyzes python"
    )]
    #[case::enforcement_mode_rejected(
        RuleOptions::none().declared(),
        BOTH_LANGUAGES,
        "enforcement-mode = \"ban\"",
        "`rules.some-rule.enforcement-mode`: this rule has no enforcement mode; it always \
         reports every finding"
    )]
    fn invalid_options_are_rejected_with_their_key_path(
        #[case] declaration: DeclaredOptions,
        #[case] languages: &[Language],
        #[case] toml_content: &str,
        #[case] message: &str,
    ) {
        let error = parse(&declaration, languages, toml_content).unwrap_err();
        assert_eq!(error.to_string(), message);
    }

    #[test]
    fn rule_value_must_be_a_table() {
        let error = RuleOverrides::parse(
            "some-rule",
            &WITH_COUNT.declared(),
            BOTH_LANGUAGES,
            &toml::Value::Boolean(true),
        )
        .unwrap_err();
        assert_eq!(
            error.to_string(),
            "`rules.some-rule`: expected a table, found boolean"
        );
    }
}