lintspec 0.12.2

A blazingly fast linter for NatSpec comments in Solidity code
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
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
//! Check the `NatSpec` documentation of a source file
//!
//! The [`lint`] function parsers the source file and contained items, validates them according to the configured
//! rules and emits a list of diagnostics, grouped by source item.
use std::{
    fs::File,
    io,
    path::{Path, PathBuf},
};

use serde::Serialize;

use crate::{
    config::{Config, ContractRules, FunctionConfig, Req, VariableConfig, WithParamsRules},
    definitions::{Identifier, ItemType, Parent},
    error::{Error, Result},
    natspec::{NatSpec, NatSpecKind},
    parser::{DocumentId, Parse, ParsedDocument},
    textindex::TextRange,
};

/// Diagnostics for a single Solidity file
#[derive(Debug, Clone, Serialize, thiserror::Error)]
#[error("Error")]
pub struct FileDiagnostics {
    /// Path to the file
    pub path: PathBuf,

    /// A unique ID for the document given by the parser
    ///
    /// Can be used to retrieve the document contents after parsing (via [`Parse::get_sources`]).
    #[serde(skip_serializing)]
    pub document_id: DocumentId,

    /// Diagnostics, grouped by source item (function, struct, etc.)
    pub items: Vec<ItemDiagnostics>,
}

/// Diagnostics for a single source item (function, struct, etc.)
#[derive(Debug, Clone, Serialize, bon::Builder)]
#[non_exhaustive]
#[builder(on(String, into))]
pub struct ItemDiagnostics {
    /// The parent contract, interface or library's name, if any
    pub parent: Option<Parent>,

    /// The type of this source item (function, struct, etc.)
    pub item_type: ItemType,

    /// The name of the item
    pub name: String,

    /// The span of the item (for function-like items, only the declaration without the body)
    pub span: TextRange,

    /// The diagnostics related to this item
    pub diags: Vec<Diagnostic>,
}

impl ItemDiagnostics {
    /// Print the diagnostics for a single source item in a compact format
    ///
    /// The writer `f` can be stderr or a file handle, for example. The path to the file containing this source item
    /// should be provided, as well as the current working directory where the command was launched from. This last
    /// information is used to compute the relative path when possible.
    pub fn print_compact(
        &self,
        f: &mut impl io::Write,
        path: impl AsRef<Path>,
        root_dir: impl AsRef<Path>,
    ) -> std::result::Result<(), io::Error> {
        fn inner(
            this: &ItemDiagnostics,
            f: &mut impl io::Write,
            path: &Path,
            root_dir: &Path,
        ) -> std::result::Result<(), io::Error> {
            let source_name = match path.strip_prefix(root_dir) {
                Ok(relative_path) => relative_path.to_string_lossy(),
                Err(_) => path.to_string_lossy(),
            };
            writeln!(f, "{source_name}:{}", this.span.start)?;
            if let Some(parent) = &this.parent {
                writeln!(f, "{} {}.{}", this.item_type, parent, this.name)?;
            } else {
                writeln!(f, "{} {}", this.item_type, this.name)?;
            }
            for diag in &this.diags {
                writeln!(f, "  {}", diag.message)?;
            }
            writeln!(f)?;
            Ok(())
        }
        inner(self, f, path.as_ref(), root_dir.as_ref())
    }
}

/// A single diagnostic related to `NatSpec`.
#[derive(Debug, Clone, Serialize)]
pub struct Diagnostic {
    /// The span (text range) related to the diagnostic
    ///
    /// If related to the item's `NatSpec` as a whole, this is the same as the item's span.
    /// For a missing param or return `NatSpec`, this is the span of the param or return item.
    pub span: TextRange,
    pub message: String,
}

/// Lint a file by identifying `NatSpec` problems.
///
/// This is the main business logic entrypoint related to using this library. The path to the Solidity file should be
/// provided, and a compatible Solidity version will be inferred from the first version pragma statement (if any) to
/// inform the parsing. [`ValidationOptions`] can be provided to control whether some of the lints get reported.
/// The `keep_contents` parameter controls if the returned [`FileDiagnostics`] contains the original source code.
pub fn lint(
    mut parser: impl Parse,
    path: impl AsRef<Path>,
    options: &ValidationOptions,
    keep_contents: bool,
) -> Result<Option<FileDiagnostics>> {
    fn inner(
        path: &Path,
        document: ParsedDocument,
        options: &ValidationOptions,
    ) -> Option<FileDiagnostics> {
        let mut items: Vec<_> = document
            .definitions
            .into_iter()
            .filter_map(|item| {
                let mut item_diags = item.validate(options);
                if item_diags.diags.is_empty() {
                    None
                } else {
                    item_diags.diags.sort_unstable_by_key(|d| d.span.start);
                    Some(item_diags)
                }
            })
            .collect();
        if items.is_empty() {
            return None;
        }
        items.sort_unstable_by_key(|i| i.span.start);
        Some(FileDiagnostics {
            path: path.to_path_buf(),
            document_id: document.id,
            items,
        })
    }
    let file = File::open(&path).map_err(|err| Error::IOError {
        path: path.as_ref().to_path_buf(),
        err,
    })?;
    let document = parser.parse_document(file, Some(&path), keep_contents)?;
    Ok(inner(path.as_ref(), document, options))
}

/// Validation options to control which lints generate a diagnostic
#[derive(Debug, Clone, PartialEq, Eq, bon::Builder)]
#[non_exhaustive]
pub struct ValidationOptions {
    /// Whether public and external functions should have an `@inheritdoc`
    #[builder(default = true)]
    pub inheritdoc: bool,

    /// Whether `override` internal functions and modifiers should have an `@inheritdoc`
    #[builder(default = false)]
    pub inheritdoc_override: bool,

    /// Whether to enforce either `@notice` or `@dev` if either or both are required
    #[builder(default)]
    pub notice_or_dev: bool,

    /// Validation options for contracts
    #[builder(default)]
    pub contracts: ContractRules,

    /// Validation options for interfaces
    #[builder(default)]
    pub interfaces: ContractRules,

    /// Validation options for libraries
    #[builder(default)]
    pub libraries: ContractRules,

    /// Validation options for constructors
    #[builder(default = WithParamsRules::default_constructor())]
    pub constructors: WithParamsRules,

    /// Validation options for enums
    #[builder(default)]
    pub enums: WithParamsRules,

    /// Validation options for errors
    #[builder(default = WithParamsRules::required())]
    pub errors: WithParamsRules,

    /// Validation options for events
    #[builder(default = WithParamsRules::required())]
    pub events: WithParamsRules,

    /// Validation options for functions
    #[builder(default)]
    pub functions: FunctionConfig,

    /// Validation options for modifiers
    #[builder(default = WithParamsRules::required())]
    pub modifiers: WithParamsRules,

    /// Validation options for structs
    #[builder(default)]
    pub structs: WithParamsRules,

    /// Validation options for state variables
    #[builder(default)]
    pub variables: VariableConfig,
}

impl Default for ValidationOptions {
    /// Get default validation options
    ///
    /// It's important that these defaults match the default values in the builder and in the [`Config`] struct
    /// (there is a test for this).
    fn default() -> Self {
        Self {
            inheritdoc: true,
            inheritdoc_override: false,
            notice_or_dev: false,
            contracts: ContractRules::default(),
            interfaces: ContractRules::default(),
            libraries: ContractRules::default(),
            constructors: WithParamsRules::default_constructor(),
            enums: WithParamsRules::default(),
            errors: WithParamsRules::required(),
            events: WithParamsRules::required(),
            functions: FunctionConfig::default(),
            modifiers: WithParamsRules::required(),
            structs: WithParamsRules::default(),
            variables: VariableConfig::default(),
        }
    }
}

/// Create a [`ValidationOptions`] from a [`Config`]
impl From<Config> for ValidationOptions {
    fn from(value: Config) -> Self {
        Self {
            inheritdoc: value.lintspec.inheritdoc,
            inheritdoc_override: value.lintspec.inheritdoc_override,
            notice_or_dev: value.lintspec.notice_or_dev,
            contracts: value.contracts,
            interfaces: value.interfaces,
            libraries: value.libraries,
            constructors: value.constructors,
            enums: value.enums,
            errors: value.errors,
            events: value.events,
            functions: value.functions,
            modifiers: value.modifiers,
            structs: value.structs,
            variables: value.variables,
        }
    }
}

/// Create a [`ValidationOptions`] from a [`Config`] reference
impl From<&Config> for ValidationOptions {
    fn from(value: &Config) -> Self {
        Self {
            inheritdoc: value.lintspec.inheritdoc,
            inheritdoc_override: value.lintspec.inheritdoc_override,
            notice_or_dev: value.lintspec.notice_or_dev,
            contracts: value.contracts.clone(),
            interfaces: value.interfaces.clone(),
            libraries: value.libraries.clone(),
            constructors: value.constructors.clone(),
            enums: value.enums.clone(),
            errors: value.errors.clone(),
            events: value.events.clone(),
            functions: value.functions.clone(),
            modifiers: value.modifiers.clone(),
            structs: value.structs.clone(),
            variables: value.variables.clone(),
        }
    }
}

/// A trait implemented by [`Definition`][crate::definitions::Definition] to validate the related `NatSpec`
pub trait Validate {
    /// Validate the definition and extract the relevant diagnostics
    fn validate(&self, options: &ValidationOptions) -> ItemDiagnostics;
}

/// Params NatSpec checker.
#[derive(Debug, Clone, bon::Builder)]
pub struct CheckParams<'a> {
    /// The parsed [`NatSpec`], if any
    natspec: &'a Option<NatSpec>,
    /// The rule to apply for `@param`
    rule: Req,
    /// The list of actual params/members
    params: &'a [Identifier],
    /// The span of the source item, used for diagnostics which don't refer to a specific param
    default_span: TextRange,
}

impl CheckParams<'_> {
    /// Check a list of params to see if they are documented with a corresponding item in the [`NatSpec`], and generate
    /// a diagnostic for each missing one or if there are more than 1 entry per param.
    ///
    /// If the rule is [`Req::Forbidden`], it checks if `@param` is present in the [`NatSpec`] and generates a
    /// diagnostic if it is.
    #[must_use]
    pub fn check(&self) -> Vec<Diagnostic> {
        let mut res = match self.rule {
            Req::Ignored => return Vec::new(),
            Req::Required => self.check_required(),
            Req::Forbidden => self.check_forbidden(),
        };
        res.sort_unstable_by_key(|d| d.span.start.utf8);
        res
    }

    /// Check params in case the rule is [`Req::Required`]
    fn check_required(&self) -> Vec<Diagnostic> {
        let Some(natspec) = self.natspec else {
            return self.missing_diags().collect();
        };
        self.extra_diags()
            .chain(self.count_diags(natspec))
            .collect()
    }

    /// Check params in case the rule is [`Req::Forbidden`]
    fn check_forbidden(&self) -> Vec<Diagnostic> {
        if let Some(natspec) = self.natspec
            && natspec.has_param()
        {
            vec![Diagnostic {
                span: self.default_span.clone(),
                message: "@param is forbidden".to_string(),
            }]
        } else {
            Vec::new()
        }
    }

    /// Generate missing param diags if `@param` is required
    fn missing_diags(&self) -> impl Iterator<Item = Diagnostic> {
        self.params.iter().filter_map(|p| {
            p.name.as_ref().map(|name| Diagnostic {
                span: p.span.clone(),
                message: format!("@param {name} is missing"),
            })
        })
    }

    /// Generate extra param diags if `@param` is required
    fn extra_diags(&self) -> impl Iterator<Item = Diagnostic> {
        // a HashMap is significantly slower than linear search here (few elements)
        self.natspec
            .as_ref()
            .map(|n| {
                n.items.iter().filter_map(|item| {
                    let NatSpecKind::Param { name } = &item.kind else {
                        return None;
                    };
                    if self
                        .params
                        .iter()
                        .any(|p| matches!(p.name.as_ref(), Some(param_name) if param_name == name))
                    {
                        None
                    } else {
                        // the item's span is relative to the comment's start offset
                        let span_start = self.default_span.start + item.span.start;
                        let span_end = self.default_span.start + item.span.end;
                        Some(Diagnostic {
                            span: span_start..span_end,
                            message: format!("extra @param {name}"),
                        })
                    }
                })
            })
            .into_iter()
            .flatten()
    }

    /// Generate diagnostics for wrong number of `@param` comments (missing or more than one)
    fn count_diags(&self, natspec: &NatSpec) -> impl Iterator<Item = Diagnostic> {
        self.counts(natspec).filter_map(|(param, count)| {
            let name = param.name.as_ref().map_or("unnamed_param", String::as_str);
            match count {
                0 => Some(Diagnostic {
                    span: param.span.clone(),
                    message: format!("@param {name} is missing"),
                }),
                1 => None,
                2.. => Some(Diagnostic {
                    span: param.span.clone(),
                    message: format!("@param {name} is present more than once"),
                }),
            }
        })
    }

    /// Count how many times each parameter is documented
    fn counts(&self, natspec: &NatSpec) -> impl Iterator<Item = (&Identifier, usize)> {
        // a HashMap is significantly slower than linear search here (few elements)
        self.params.iter().map(|p: &Identifier| {
            let param_name = p.name.as_ref().map_or("", String::as_str);
            (
                p,
                natspec
                    .items
                    .iter()
                    .filter(
                        |n| matches!(&n.kind, NatSpecKind::Param { name } if name == param_name),
                    )
                    .count(),
            )
        })
    }
}

/// Returns NatSpec checker.
#[derive(Debug, Clone, bon::Builder)]
pub struct CheckReturns<'a> {
    /// The parsed [`NatSpec`], if any
    natspec: &'a Option<NatSpec>,
    /// The rule to apply for `@return`
    rule: Req,
    /// The list of actual return values
    returns: &'a [Identifier],
    /// The span of the source item, used for diagnostics which don't refer to a specific return
    default_span: TextRange,
    /// Whether this is a state variable (affects diagnostic messages)
    is_var: bool,
}

impl CheckReturns<'_> {
    /// Check a list of returns to see if they are documented with a corresponding item in the [`NatSpec`], and generate
    /// a diagnostic for each missing one or if there are more than 1 entry per param.
    ///
    /// If the rule is [`Req::Forbidden`], it checks if `@return` is present in the [`NatSpec`] and generates a
    /// diagnostic if it is.
    #[must_use]
    pub fn check(&self) -> Vec<Diagnostic> {
        match self.rule {
            Req::Ignored => Vec::new(),
            Req::Required => self.check_required(),
            Req::Forbidden => self.check_forbidden(),
        }
    }

    /// Check returns in case the rule is [`Req::Required`]
    fn check_required(&self) -> Vec<Diagnostic> {
        let Some(natspec) = self.natspec else {
            return self.missing_diags().collect();
        };
        self.return_diags(natspec)
            .chain(self.extra_unnamed_diags(natspec))
            .collect()
    }

    /// Check returns in case the rule is [`Req::Forbidden`]
    fn check_forbidden(&self) -> Vec<Diagnostic> {
        if let Some(natspec) = self.natspec
            && natspec.has_return()
        {
            vec![Diagnostic {
                span: self.default_span.clone(),
                message: "@return is forbidden".to_string(),
            }]
        } else {
            Vec::new()
        }
    }

    /// Generate missing return diags if `@return` is required and there's no natspec
    fn missing_diags(&self) -> impl Iterator<Item = Diagnostic> {
        self.returns.iter().enumerate().map(|(idx, r)| {
            let message = if let Some(name) = &r.name {
                format!("@return {name} is missing")
            } else if self.is_var {
                "@return is missing".to_string()
            } else {
                format!("@return missing for unnamed return #{}", idx + 1)
            };
            Diagnostic {
                span: r.span.clone(),
                message,
            }
        })
    }

    /// Check a named return's NatSpec count
    fn named_count_diag(natspec: &NatSpec, ret: &Identifier, name: &str) -> Option<Diagnostic> {
        match natspec.count_return(ret) {
            0 => Some(Diagnostic {
                span: ret.span.clone(),
                message: format!("@return {name} is missing"),
            }),
            1 => None,
            2.. => Some(Diagnostic {
                span: ret.span.clone(),
                message: format!("@return {name} is present more than once"),
            }),
        }
    }

    /// Check an unnamed return's NatSpec
    fn unnamed_diag(
        &self,
        returns_count: usize,
        idx: usize,
        ret: &Identifier,
    ) -> Option<Diagnostic> {
        if idx + 1 > returns_count {
            let message = if self.is_var {
                "@return is missing".to_string()
            } else {
                format!("@return missing for unnamed return #{}", idx + 1)
            };
            Some(Diagnostic {
                span: ret.span.clone(),
                message,
            })
        } else {
            None
        }
    }

    /// Generate diagnostics for all returns (both named and unnamed) in order
    fn return_diags(&self, natspec: &NatSpec) -> impl Iterator<Item = Diagnostic> {
        let returns_count = natspec.count_all_returns();
        self.returns
            .iter()
            .enumerate()
            .filter_map(move |(idx, ret)| {
                if let Some(name) = &ret.name {
                    // Handle named returns
                    Self::named_count_diag(natspec, ret, name)
                } else {
                    // Handle unnamed returns
                    self.unnamed_diag(returns_count, idx, ret)
                }
            })
    }

    /// Generate diagnostic for too many unnamed returns in natspec
    fn extra_unnamed_diags(&self, natspec: &NatSpec) -> impl Iterator<Item = Diagnostic> {
        let unnamed_returns = self.returns.iter().filter(|r| r.name.is_none()).count();
        if natspec.count_unnamed_returns() > unnamed_returns {
            Some(Diagnostic {
                span: self
                    .returns
                    .last()
                    .cloned()
                    .map_or(self.default_span.clone(), |r| r.span),
                message: "too many unnamed returns".to_string(),
            })
        } else {
            None
        }
        .into_iter()
    }
}

/// Notice NatSpec checker.
#[derive(Debug, Clone, bon::Builder)]
pub struct CheckNotice<'a> {
    /// The parsed [`NatSpec`], if any
    natspec: &'a Option<NatSpec>,
    /// The rule to apply for `@notice`
    rule: Req,
    /// The span of the source item
    span: &'a TextRange,
}

impl CheckNotice<'_> {
    /// Check if the `@notice` presence matches the requirements (`Req::Required` or `Req::Forbidden`) and generate a
    /// diagnostic if it doesn't.
    #[must_use]
    pub fn check(&self) -> Option<Diagnostic> {
        match self.rule {
            Req::Ignored => None,
            Req::Required => self.check_required(),
            Req::Forbidden => self.check_forbidden(),
        }
    }

    /// Check notice in case the rule is [`Req::Required`]
    fn check_required(&self) -> Option<Diagnostic> {
        if let Some(natspec) = self.natspec
            && natspec.has_notice()
        {
            None
        } else {
            Some(Diagnostic {
                span: self.span.clone(),
                message: "@notice is missing".to_string(),
            })
        }
    }

    /// Check notice in case the rule is [`Req::Forbidden`]
    fn check_forbidden(&self) -> Option<Diagnostic> {
        if let Some(natspec) = self.natspec
            && natspec.has_notice()
        {
            Some(Diagnostic {
                span: self.span.clone(),
                message: "@notice is forbidden".to_string(),
            })
        } else {
            None
        }
    }
}

/// Dev NatSpec checker.
#[derive(Debug, Clone, bon::Builder)]
pub struct CheckDev<'a> {
    /// The parsed [`NatSpec`], if any
    natspec: &'a Option<NatSpec>,
    /// The rule to apply for `@dev`
    rule: Req,
    /// The span of the source item
    span: &'a TextRange,
}

impl CheckDev<'_> {
    /// Check if the `@dev` presence matches the requirements (`Req::Required` or `Req::Forbidden`) and generate a
    /// diagnostic if it doesn't.
    #[must_use]
    pub fn check(&self) -> Option<Diagnostic> {
        match self.rule {
            Req::Ignored => None,
            Req::Required => self.check_required(),
            Req::Forbidden => self.check_forbidden(),
        }
    }

    /// Check dev in case the rule is [`Req::Required`]
    fn check_required(&self) -> Option<Diagnostic> {
        if let Some(natspec) = self.natspec
            && natspec.has_dev()
        {
            None
        } else {
            Some(Diagnostic {
                span: self.span.clone(),
                message: "@dev is missing".to_string(),
            })
        }
    }

    /// Check dev in case the rule is [`Req::Forbidden`]
    fn check_forbidden(&self) -> Option<Diagnostic> {
        if let Some(natspec) = self.natspec
            && natspec.has_dev()
        {
            Some(Diagnostic {
                span: self.span.clone(),
                message: "@dev is forbidden".to_string(),
            })
        } else {
            None
        }
    }
}

/// Title NatSpec checker.
#[derive(Debug, Clone, bon::Builder)]
pub struct CheckTitle<'a> {
    /// The parsed [`NatSpec`], if any
    natspec: &'a Option<NatSpec>,
    /// The rule to apply for `@title`
    rule: Req,
    /// The span of the source item
    span: &'a TextRange,
}

impl CheckTitle<'_> {
    /// Check if the `@title` presence matches the requirements (`Req::Required` or `Req::Forbidden`) and generate a
    /// diagnostic if it doesn't.
    #[must_use]
    pub fn check(&self) -> Option<Diagnostic> {
        match self.rule {
            Req::Ignored => None,
            Req::Required => self.check_required(),
            Req::Forbidden => self.check_forbidden(),
        }
    }

    /// Check title in case the rule is [`Req::Required`]
    fn check_required(&self) -> Option<Diagnostic> {
        if let Some(natspec) = self.natspec
            && natspec.has_title()
        {
            None
        } else {
            Some(Diagnostic {
                span: self.span.clone(),
                message: "@title is missing".to_string(),
            })
        }
    }

    /// Check title in case the rule is [`Req::Forbidden`]
    fn check_forbidden(&self) -> Option<Diagnostic> {
        if let Some(natspec) = self.natspec
            && natspec.has_title()
        {
            Some(Diagnostic {
                span: self.span.clone(),
                message: "@title is forbidden".to_string(),
            })
        } else {
            None
        }
    }
}

/// Author NatSpec checker.
#[derive(Debug, Clone, bon::Builder)]
pub struct CheckAuthor<'a> {
    /// The parsed [`NatSpec`], if any
    natspec: &'a Option<NatSpec>,
    /// The rule to apply for `@author`
    rule: Req,
    /// The span of the source item
    span: &'a TextRange,
}

impl CheckAuthor<'_> {
    /// Check if the `@author` presence matches the requirements (`Req::Required` or `Req::Forbidden`) and generate a
    /// diagnostic if it doesn't.
    #[must_use]
    pub fn check(&self) -> Option<Diagnostic> {
        match self.rule {
            Req::Ignored => None,
            Req::Required => self.check_required(),
            Req::Forbidden => self.check_forbidden(),
        }
    }

    /// Check author in case the rule is [`Req::Required`]
    fn check_required(&self) -> Option<Diagnostic> {
        if let Some(natspec) = self.natspec
            && natspec.has_author()
        {
            None
        } else {
            Some(Diagnostic {
                span: self.span.clone(),
                message: "@author is missing".to_string(),
            })
        }
    }

    /// Check author in case the rule is [`Req::Forbidden`]
    fn check_forbidden(&self) -> Option<Diagnostic> {
        if let Some(natspec) = self.natspec
            && natspec.has_author()
        {
            Some(Diagnostic {
                span: self.span.clone(),
                message: "@author is forbidden".to_string(),
            })
        } else {
            None
        }
    }
}

/// Notice and Dev NatSpec checker.
#[derive(Debug, Clone, bon::Builder)]
pub struct CheckNoticeAndDev<'a> {
    /// The parsed [`NatSpec`], if any
    natspec: &'a Option<NatSpec>,
    /// The rule to apply for `@notice`
    notice_rule: Req,
    /// The rule to apply for `@dev`
    dev_rule: Req,
    /// Whether to enforce either `@notice` or `@dev` if either or both are required
    notice_or_dev: bool,
    /// The span of the source item
    span: &'a TextRange,
}

impl CheckNoticeAndDev<'_> {
    /// Check if the `@notice` or `@dev` presence matches the requirements (`Req::Required` or `Req::Forbidden`) and
    /// generate diagnostics if they don't.
    ///
    /// This method honors the `notice_or_dev` option. If this option is enabled and one or both are required, it will
    /// check if either `@notice` or `@dev` is present in the `NatSpec`.
    ///
    /// It will generate a diagnostic if neither is present. If either is forbidden, or the `notice_or_dev` option is
    /// disabled, it will check the `@notice` and `@dev` separately according to their respective rules.
    #[must_use]
    pub fn check(&self) -> Vec<Diagnostic> {
        match (self.notice_or_dev, self.notice_rule, self.dev_rule) {
            (true, Req::Required, Req::Ignored | Req::Required)
            | (true, Req::Ignored, Req::Required) => self.check_notice_or_dev(),
            (true, Req::Forbidden, _) | (true, _, Req::Forbidden) | (false, _, _) => {
                self.check_separately()
            }
            (true, Req::Ignored, Req::Ignored) => Vec::new(),
        }
    }

    /// Check that either `@notice` or `@dev` is present
    fn check_notice_or_dev(&self) -> Vec<Diagnostic> {
        if let Some(natspec) = self.natspec
            && (natspec.has_notice() || natspec.has_dev())
        {
            Vec::new()
        } else {
            vec![Diagnostic {
                span: self.span.clone(),
                message: "@notice or @dev is missing".to_string(),
            }]
        }
    }

    /// Check `@notice` and `@dev` separately according to their respective rules
    fn check_separately(&self) -> Vec<Diagnostic> {
        let mut res = Vec::new();
        res.extend(
            CheckNotice::builder()
                .natspec(self.natspec)
                .rule(self.notice_rule)
                .span(self.span)
                .build()
                .check(),
        );
        res.extend(
            CheckDev::builder()
                .natspec(self.natspec)
                .rule(self.dev_rule)
                .span(self.span)
                .build()
                .check(),
        );
        res
    }
}

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

    use crate::config::{BaseConfig, FunctionRules, NoticeDevRules};

    use super::*;

    #[test]
    fn test_validation_options_default() {
        assert_eq!(
            ValidationOptions::default(),
            ValidationOptions::builder().build()
        );

        let default_config = Config::default();
        let options = ValidationOptions::from(&default_config);
        assert_eq!(ValidationOptions::default(), options);
    }

    #[test]
    fn test_validation_options_conversion() {
        let config = Config::builder().build();
        let options = ValidationOptions::from(&config);
        assert_eq!(config.lintspec.inheritdoc, options.inheritdoc);
        assert_eq!(config.lintspec.notice_or_dev, options.notice_or_dev);
        assert_eq!(config.contracts, options.contracts);
        assert_eq!(config.interfaces, options.interfaces);
        assert_eq!(config.libraries, options.libraries);
        assert_eq!(config.constructors, options.constructors);
        assert_eq!(config.enums, options.enums);
        assert_eq!(config.errors, options.errors);
        assert_eq!(config.events, options.events);
        assert_eq!(config.functions, options.functions);
        assert_eq!(config.modifiers, options.modifiers);
        assert_eq!(config.structs, options.structs);
        assert_eq!(config.variables, options.variables);

        let config = Config::builder()
            .lintspec(
                BaseConfig::builder()
                    .inheritdoc(false)
                    .notice_or_dev(true)
                    .build(),
            )
            .contracts(
                ContractRules::builder()
                    .title(Req::Required)
                    .author(Req::Required)
                    .dev(Req::Required)
                    .notice(Req::Forbidden)
                    .build(),
            )
            .interfaces(
                ContractRules::builder()
                    .title(Req::Ignored)
                    .author(Req::Forbidden)
                    .dev(Req::Forbidden)
                    .notice(Req::Required)
                    .build(),
            )
            .libraries(
                ContractRules::builder()
                    .title(Req::Forbidden)
                    .author(Req::Ignored)
                    .dev(Req::Required)
                    .notice(Req::Ignored)
                    .build(),
            )
            .constructors(WithParamsRules::builder().dev(Req::Required).build())
            .enums(WithParamsRules::builder().param(Req::Required).build())
            .errors(WithParamsRules::builder().notice(Req::Forbidden).build())
            .events(WithParamsRules::builder().param(Req::Forbidden).build())
            .functions(
                FunctionConfig::builder()
                    .private(FunctionRules::builder().dev(Req::Required).build())
                    .build(),
            )
            .modifiers(WithParamsRules::builder().dev(Req::Forbidden).build())
            .structs(WithParamsRules::builder().notice(Req::Ignored).build())
            .variables(
                VariableConfig::builder()
                    .private(NoticeDevRules::builder().dev(Req::Required).build())
                    .build(),
            )
            .build();
        let options = ValidationOptions::from(&config);
        assert_eq!(config.lintspec.inheritdoc, options.inheritdoc);
        assert_eq!(config.lintspec.notice_or_dev, options.notice_or_dev);
        assert_eq!(config.contracts, options.contracts);
        assert_eq!(config.interfaces, options.interfaces);
        assert_eq!(config.libraries, options.libraries);
        assert_eq!(config.constructors, options.constructors);
        assert_eq!(config.enums, options.enums);
        assert_eq!(config.errors, options.errors);
        assert_eq!(config.events, options.events);
        assert_eq!(config.functions, options.functions);
        assert_eq!(config.modifiers, options.modifiers);
        assert_eq!(config.structs, options.structs);
        assert_eq!(config.variables, options.variables);
    }
}