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
//! The core runner for RSLint responsible for the bulk of the linter's work.
//!
//! The crate is not RSLint-specific and can be used from any project. The runner is responsible
//! for taking a list of rules, and source code and running the linter on it. It is important to decouple
//! the CLI work and the low level linting work from eachother to be able to reuse the linter facilities.
//! Therefore, the core runner should never do anything `rslint_cli`-specific.
//!
//! The structure at the core of the crate is the [`CstRule`] and [`Rule`] traits.
//! CST rules run on a single file and its concrete syntax tree produced by [`rslint_parser`].
//! The rules have a couple of restrictions for clarity and speed, these include:
//! - all cst rules must be [`Send`](std::marker::Send) and [`Sync`](std::marker::Sync) so they can be run in parallel
//! - rules may never rely on the results of other rules, this is impossible because rules are run in parallel
//! - rules should never make any network or file requests
//!
//! ## Using the runner
//!
//! To run the runner you must first create a [`CstRuleStore`], which is the structure used for storing what rules
//! to run. Then you can use [`lint_file`].
//!
//! ## Running a single rule
//!
//! To run a single rule you can find the rule you want in the `groups` module and submodules within. Then
//! to run a rule in full on a syntax tree you can use [`run_rule`].
//!
//! Rules can also be run on individual nodes using the functions on [`CstRule`].
//! ⚠️ note however that many rules rely on checking tokens or the root and running on single nodes
//! may yield incorrect results, you should only do this if you know about the rule's implementation.

mod rule;
mod store;
mod testing;

pub mod autofix;
pub mod directives;
pub mod groups;
pub mod rule_prelude;
pub mod util;

pub use self::{
    rule::{CstRule, Outcome, Rule, RuleCtx, RuleLevel, RuleResult},
    store::CstRuleStore,
};
pub use rslint_errors::{Diagnostic, Severity, Span};

use crate::directives::skip_node;
#[doc(inline)]
pub use crate::directives::{apply_top_level_directives, Directive, DirectiveParser};
use dyn_clone::clone_box;
use rayon::prelude::*;
use rslint_parser::{parse_module, parse_text, util::SyntaxNodeExt, SyntaxKind, SyntaxNode};
use std::collections::HashMap;
use std::sync::Arc;

/// The result of linting a file.
// TODO: A lot of this stuff can be shoved behind a "linter options" struct
#[derive(Debug, Clone)]
pub struct LintResult<'s> {
    /// Any diagnostics (errors, warnings, etc) emitted from the parser
    pub parser_diagnostics: Vec<Diagnostic>,
    /// The store used for the lint run
    pub store: &'s CstRuleStore,
    /// The diagnostics emitted by each rule run
    pub rule_results: HashMap<&'static str, RuleResult>,
    /// Any warnings or errors emitted by the directive parser
    pub directive_diagnostics: Vec<Diagnostic>,
    pub parsed: SyntaxNode,
    pub file_id: usize,
    pub verbose: bool,
    pub fixed_code: Option<String>,
}

impl LintResult<'_> {
    /// Get all of the diagnostics thrown during linting, in the order of parser diagnostics, then
    /// the diagnostics of each rule sequentially.
    pub fn diagnostics(&self) -> impl Iterator<Item = &Diagnostic> {
        self.parser_diagnostics
            .iter()
            .chain(
                self.rule_results
                    .values()
                    .map(|x| x.diagnostics.iter())
                    .flatten(),
            )
            .chain(self.directive_diagnostics.iter())
    }

    /// The overall outcome of linting this file (failure, warning, success, etc)
    pub fn outcome(&self) -> Outcome {
        self.diagnostics().into()
    }

    /// Attempt to automatically fix any fixable issues and return the fixed code.
    ///
    /// This will not run if there are syntax errors unless `dirty` is set to true.
    pub fn fix(&mut self, dirty: bool) -> Option<String> {
        if self
            .parser_diagnostics
            .iter()
            .any(|x| x.severity == Severity::Error)
            && !dirty
        {
            None
        } else {
            Some(autofix::recursively_apply_fixes(self))
        }
    }
}

/// Lint a file with a specific rule store.
pub fn lint_file(
    file_id: usize,
    file_source: impl AsRef<str>,
    module: bool,
    store: &CstRuleStore,
    verbose: bool,
) -> Result<LintResult, Diagnostic> {
    let (parser_diagnostics, green) = if module {
        let parse = parse_module(file_source.as_ref(), file_id);
        (parse.errors().to_owned(), parse.green())
    } else {
        let parse = parse_text(file_source.as_ref(), file_id);
        (parse.errors().to_owned(), parse.green())
    };
    lint_file_inner(
        SyntaxNode::new_root(green),
        parser_diagnostics,
        file_id,
        store,
        verbose,
    )
}

/// used by lint_file and incrementally_relint to not duplicate code
pub(crate) fn lint_file_inner(
    node: SyntaxNode,
    parser_diagnostics: Vec<Diagnostic>,
    file_id: usize,
    store: &CstRuleStore,
    verbose: bool,
) -> Result<LintResult, Diagnostic> {
    let mut new_store = store.clone();
    let results = DirectiveParser::new(node.clone(), file_id, store).get_file_directives()?;
    let mut directive_diagnostics = vec![];

    let directives = results
        .into_iter()
        .map(|res| {
            directive_diagnostics.extend(res.diagnostics);
            res.directive
        })
        .collect::<Vec<_>>();

    apply_top_level_directives(
        directives.as_slice(),
        &mut new_store,
        &mut directive_diagnostics,
        file_id,
    );

    let src = Arc::new(node.to_string());
    let results = new_store
        .rules
        .par_iter()
        .map(|rule| {
            (
                rule.name(),
                run_rule(
                    &**rule,
                    file_id,
                    node.clone(),
                    verbose,
                    &directives,
                    src.clone(),
                ),
            )
        })
        .collect();

    Ok(LintResult {
        parser_diagnostics,
        store,
        rule_results: results,
        directive_diagnostics,
        parsed: node,
        file_id,
        verbose,
        fixed_code: None,
    })
}

/// Run a single run on an entire parsed file.
///
/// # Panics
/// Panics if `root`'s kind is not `SCRIPT` or `MODULE`
pub fn run_rule(
    rule: &dyn CstRule,
    file_id: usize,
    root: SyntaxNode,
    verbose: bool,
    directives: &[Directive],
    src: Arc<String>,
) -> RuleResult {
    assert!(root.kind() == SyntaxKind::SCRIPT || root.kind() == SyntaxKind::MODULE);
    let mut ctx = RuleCtx {
        file_id,
        verbose,
        diagnostics: vec![],
        fixer: None,
        src,
    };

    rule.check_root(&root, &mut ctx);

    root.descendants_with_tokens_with(&mut |elem| {
        match elem {
            rslint_parser::NodeOrToken::Node(node) => {
                if skip_node(directives, &node, rule) || node.kind() == SyntaxKind::ERROR {
                    return false;
                }
                rule.check_node(&node, &mut ctx);
            }
            rslint_parser::NodeOrToken::Token(tok) => {
                let _ = rule.check_token(&tok, &mut ctx);
            }
        };
        true
    });
    RuleResult::new(ctx.diagnostics, ctx.fixer)
}

/// Get a rule by its kebab-case name.
pub fn get_rule_by_name(name: &str) -> Option<Box<dyn CstRule>> {
    CstRuleStore::new()
        .builtins()
        .rules
        .iter()
        .find(|rule| rule.name() == name)
        .map(|rule| clone_box(&**rule))
}

/// Get a group's rules by the group name.
// TODO: there should be a good way to not have to hardcode all of this
pub fn get_group_rules_by_name(group_name: &str) -> Option<Vec<Box<dyn CstRule>>> {
    use groups::*;

    Some(match group_name {
        "errors" => errors(),
        _ => return None,
    })
}

/// Get a suggestion for an incorrect rule name for things such as "did you mean ...?"
pub fn get_rule_suggestion(incorrect_rule_name: &str) -> Option<&str> {
    let rules = CstRuleStore::new()
        .builtins()
        .rules
        .into_iter()
        .map(|rule| rule.name());
    util::find_best_match_for_name(rules, incorrect_rule_name, None)
}

/// Get a rule and its documentation.
///
/// This will always be `Some` for valid rule names and it will be an empty string
/// if the rule has no docs
pub fn get_rule_docs(rule: &str) -> Option<&'static str> {
    get_rule_by_name(rule).map(|rule| rule.docs())
}