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
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

//! Lint engine.
//!
//! The overall design is generally inspired by
//! [Arcanist](https://secure.phabricator.com/book/phabricator/article/arcanist_lint)'s lint engine.

pub mod content;
pub mod file_path;
pub mod package;
pub mod project;
pub mod runner;

use camino::Utf8Path;
use guppy::PackageId;
use std::{borrow::Cow, fmt};

/// Represents a linter.
pub trait Linter: Send + Sync + fmt::Debug {
    /// Returns the name of the linter.
    fn name(&self) -> &'static str;
}

/// Represents common functionality among various `Context` instances.
trait LintContext<'l> {
    /// Returns the kind of this lint context.
    fn kind(&self) -> LintKind<'l>;

    /// Returns a `LintSource` for this lint context.
    fn source(&self, name: &'static str) -> LintSource<'l> {
        LintSource::new(name, self.kind())
    }
}

/// A lint formatter.
///
/// Lints write `LintMessage` instances to this.
pub struct LintFormatter<'l, 'a> {
    source: LintSource<'l>,
    messages: &'a mut Vec<(LintSource<'l>, LintMessage)>,
}

impl<'l, 'a> LintFormatter<'l, 'a> {
    pub fn new(
        source: LintSource<'l>,
        messages: &'a mut Vec<(LintSource<'l>, LintMessage)>,
    ) -> Self {
        Self { source, messages }
    }

    /// Writes a new lint message to this formatter.
    pub fn write(&mut self, level: LintLevel, message: impl Into<Cow<'static, str>>) {
        self.messages
            .push((self.source, LintMessage::new(level, message)));
    }

    /// Writes a new lint message to this formatter with a custom kind.
    pub fn write_kind(
        &mut self,
        kind: LintKind<'l>,
        level: LintLevel,
        message: impl Into<Cow<'static, str>>,
    ) {
        self.messages.push((
            LintSource::new(self.source.name(), kind),
            LintMessage::new(level, message),
        ));
    }
}

/// The run status of a lint.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RunStatus<'l> {
    /// This lint run was successful, with messages possibly written into the `LintFormatter`.
    Executed,
    /// This lint was skipped.
    Skipped(SkipReason<'l>),
}

/// The reason for why this lint was skipped.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum SkipReason<'l> {
    /// This file's content was not valid UTF-8.
    NonUtf8Content,
    /// This extension was unsupported.
    UnsupportedExtension(Option<&'l str>),
    /// The given file was unsupported by this linter.
    UnsupportedFile(&'l Utf8Path),
    /// The given package was unsupported by this linter.
    UnsupportedPackage(&'l PackageId),
    /// The given file was excepted by a glob rule
    GlobExemption(&'l str),
    // TODO: Add more reasons.
}

/// A message raised by a lint.
#[derive(Debug)]
pub struct LintMessage {
    level: LintLevel,
    message: Cow<'static, str>,
}

impl LintMessage {
    pub fn new(level: LintLevel, message: impl Into<Cow<'static, str>>) -> Self {
        Self {
            level,
            message: message.into(),
        }
    }

    pub fn level(&self) -> LintLevel {
        self.level
    }

    pub fn message(&self) -> &str {
        &self.message
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[allow(dead_code)]
#[non_exhaustive]
pub enum LintLevel {
    Error,
    Warning,
    // TODO: add more levels?
}

impl fmt::Display for LintLevel {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            LintLevel::Error => write!(f, "ERROR"),
            LintLevel::Warning => write!(f, "WARNING"),
        }
    }
}

/// Message source for lints.
#[derive(Copy, Clone, Debug)]
pub struct LintSource<'l> {
    name: &'static str,
    kind: LintKind<'l>,
}

impl<'l> LintSource<'l> {
    fn new(name: &'static str, kind: LintKind<'l>) -> Self {
        Self { name, kind }
    }

    pub fn name(&self) -> &'static str {
        self.name
    }

    pub fn kind(&self) -> LintKind<'l> {
        self.kind
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum LintKind<'l> {
    Project,
    Package {
        name: &'l str,
        workspace_path: &'l Utf8Path,
    },
    FilePath(&'l Utf8Path),
    Content(&'l Utf8Path),
}

impl<'l> fmt::Display for LintKind<'l> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            LintKind::Project => write!(f, "project"),
            LintKind::Package {
                name,
                workspace_path,
            } => write!(f, "package '{}' (at {})", name, workspace_path),
            LintKind::FilePath(path) => write!(f, "file path {}", path),
            LintKind::Content(path) => write!(f, "content {}", path),
        }
    }
}

pub mod prelude {
    pub use super::{
        content::{ContentContext, ContentLinter},
        file_path::{FilePathContext, FilePathLinter},
        package::{PackageContext, PackageLinter},
        project::{ProjectContext, ProjectLinter},
        runner::{LintEngine, LintEngineConfig, LintResults},
        LintFormatter, LintKind, LintLevel, LintMessage, LintSource, Linter, RunStatus, SkipReason,
    };
    pub use x_core::{Result, SystemError};
}