arity 0.11.0

A language server, formatter, and linter for R
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
//! Lint rule trait, registry, and per-file dispatch.
//!
//! Rules are run over a file in a single shared CST traversal: each rule
//! declares the [`SyntaxKind`]s it cares about via [`Rule::interests`], and
//! [`run_rules`] walks the tree once, calling [`Rule::check`] on every element
//! whose kind a rule subscribed to. Rules that work off the whole file rather
//! than node shape (semantic-model queries, comment directives) leave
//! `interests` empty and override [`Rule::check_file`], which runs once per file
//! after the walk.
//!
//! New rules:
//! 1. Create a module under `src/linter/rules/<category>/<id>.rs`.
//! 2. Define a unit `pub struct` that implements [`Rule`] — subscribe to node
//!    kinds via `interests` + `check`, or do a whole-file pass via `check_file`.
//! 3. Add it to [`all_rules`] below — the single source of truth. The set of
//!    valid rule IDs ([`all_rule_ids`]) is derived from it, so there is no
//!    second list to keep in sync.

use std::collections::HashMap;
use std::path::Path;

use rowan::ast::AstNode as _;

use crate::ast::{BinaryExpr, CallExpr};
use crate::project::{ExternalResolution, FileScope};
use crate::rindex::provider::CompositeProvider;
use crate::semantic::{PackageOrigin, SemanticModel, SymbolProvider};
use crate::syntax::{SyntaxElement, SyntaxKind, SyntaxNode};

use super::diagnostic::{Diagnostic, Severity};

pub mod correctness;
pub mod documentation;
pub mod matchers;
pub mod performance;
pub mod readability;
pub mod roxygen;
pub mod suspicious;

/// All rules currently shipped.
pub fn all_rules() -> Vec<Box<dyn Rule>> {
    vec![
        Box::new(correctness::UndefinedSymbol),
        Box::new(correctness::UnusedBinding),
        Box::new(correctness::DuplicateFormal),
        Box::new(correctness::DuplicatedArguments),
        Box::new(correctness::EqualsNa),
        Box::new(correctness::VectorLogic),
        Box::new(correctness::UnreachableCode),
        Box::new(suspicious::AssignmentInCondition),
        Box::new(suspicious::ShadowedBuiltin),
        Box::new(suspicious::RedundantEquals),
        Box::new(suspicious::RedundantIfelse),
        Box::new(suspicious::Repeat),
        Box::new(readability::TrueFalseSymbol),
        Box::new(readability::ComparisonNegation),
        Box::new(readability::OuterNegation),
        Box::new(readability::StringBoundary),
        Box::new(performance::AnyIsNa),
        Box::new(performance::AnyDuplicated),
        Box::new(performance::Crossprod),
        Box::new(performance::FixedRegex),
        Box::new(documentation::RoxygenUnknownTag),
        Box::new(documentation::RoxygenTitle),
        Box::new(documentation::RoxygenReturn),
        Box::new(documentation::RoxygenParam),
        Box::new(documentation::RoxygenExamples),
    ]
}

/// Every shipped rule's ID, derived from [`all_rules`] so the two never drift.
/// Used to validate `LintConfig::select` / `ignore`.
pub fn all_rule_ids() -> Vec<&'static str> {
    all_rules().iter().map(|r| r.id()).collect()
}

/// A documented example for a rule: a snippet of R that triggers the rule.
///
/// The rule reference is generated by running the real linter on `source`, so
/// the "after" state of an autofix is *derived* (by applying the rule's safe
/// fixes) rather than stored — the snippet stays the single source of truth.
pub struct Example {
    /// One-line caption rendered above the snippet (markdown). May be empty.
    pub caption: &'static str,
    /// R source that triggers the rule. Should end with a trailing newline.
    pub source: &'static str,
}

pub trait Rule: Send + Sync {
    fn id(&self) -> &'static str;
    fn default_severity(&self) -> Severity {
        Severity::Warning
    }
    fn default_enabled(&self) -> bool {
        true
    }

    /// One-paragraph (markdown) description of what the rule flags and why,
    /// used to generate the rule reference. Empty means "not yet documented".
    fn description(&self) -> &'static str {
        ""
    }

    /// Worked examples for the rule reference. Each `source` is linted live and
    /// rendered with its diagnostics (and autofix before/after). The default is
    /// empty — a rule with no examples is skipped by the docs generator.
    fn examples(&self) -> &'static [Example] {
        &[]
    }

    /// The `SyntaxKind`s this rule subscribes to. During [`run_rules`]' single
    /// shared traversal, [`Rule::check`] is invoked once for every element whose
    /// kind appears here. The default (`&[]`) opts out of node dispatch entirely
    /// — appropriate for rules that work off the whole file via
    /// [`Rule::check_file`].
    fn interests(&self) -> &'static [SyntaxKind] {
        &[]
    }

    /// Per-element callback, invoked for each CST element (node *or* token) whose
    /// kind is in [`Rule::interests`]. Node-shape rules unwrap `el.as_node()`;
    /// token rules unwrap `el.as_token()`. Push findings onto `sink`.
    fn check(&self, el: &SyntaxElement, ctx: &RuleContext<'_>, sink: &mut Vec<Diagnostic>) {
        let _ = (el, ctx, sink);
    }

    /// Whole-file pass, run once after the shared traversal. For rules driven by
    /// the semantic model, cross-file scope, or comment directives rather than
    /// node shape. The default is a no-op.
    fn check_file(&self, ctx: &RuleContext<'_>, sink: &mut Vec<Diagnostic>) {
        let _ = (ctx, sink);
    }
}

pub struct RuleContext<'a> {
    pub path: &'a Path,
    pub root: &'a SyntaxNode,
    pub model: &'a SemanticModel,
    pub symbols: &'a dyn SymbolProvider,
    /// Cross-file visibility for this file, when linting a multi-file project.
    /// `None` for single-file runs (the LSP per-document path, one-shot checks).
    pub project: Option<&'a FileScope<'a>>,
    /// Salsa-resolved external-symbol verdict for this file, when available (the
    /// cross-file lint path). Carries the backdated set of free-read names that
    /// resolve to no attached package, so `undefined-symbol` consumes a memoized
    /// result instead of re-running masking on every keystroke. `None` on the
    /// single-file paths, where the rule falls back to [`RuleContext::symbols`].
    pub resolution: Option<&'a ExternalResolution>,
}

impl RuleContext<'_> {
    /// Whether `call`'s callee is confirmed to invoke a base-R function: a
    /// simple name that is (a) exported by one of R's default packages, (b) not
    /// shadowed by a local binding, and (c) not masked by an attached
    /// non-default package. Computed/qualified callees (`pkg::f(...)`,
    /// `x$f(...)`, `(g())(...)`) and anything we can't confirm return `false`,
    /// keeping callers conservative — no rewrite when unsure (Tenets 3/5).
    ///
    /// This is the Phase 2 namespace-confirmation gate: a call-rewrite rule
    /// matches the shape, then asks this before rewriting a bare name.
    pub fn resolves_to_base(&self, call: &CallExpr) -> bool {
        let Some(name) = matchers::callee_name(call) else {
            return false;
        };
        if !self.symbols.is_base(&name) {
            return false;
        }
        // A namespace-qualified callee (`pkg::f(...)`) is not a bare-name base
        // call: `callee_token` unwraps `pkg::f(...)` to the bare `f`, so guard
        // against it explicitly.
        if is_namespace_qualified(call) {
            return false;
        }
        // The callee read sits in `idents` at the callee token's range; if it
        // resolves to a local binding, the base name is shadowed locally. This
        // is the same `resolve_local` pairing `shadowed-builtin` uses, keyed off
        // the call we already hold.
        if let Some(callee) = call.callee_token() {
            let range = callee.text_range();
            let shadowed = self
                .model
                .idents()
                .iter()
                .any(|i| i.range == range && self.model.resolve_local(i).is_some());
            if shadowed {
                return false;
            }
        }
        // Not masked by an attached non-default package.
        origin_is_default(self.symbols.origin(&name, self.model.loaded_packages()))
    }
}

/// Whether `call` is the call form of a namespace access (`pkg::f(...)` /
/// `pkg:::f(...)`) — i.e. its `CALL_EXPR` is the RHS of a `::`/`:::` operator.
fn is_namespace_qualified(call: &CallExpr) -> bool {
    let Some(callee) = call.callee_token() else {
        return false;
    };
    call.syntax()
        .parent()
        .and_then(BinaryExpr::cast)
        .and_then(|bin| bin.namespace_access())
        .is_some_and(|ns| ns.name_token.text_range() == callee.text_range())
}

/// Whether a resolved origin's effective package (the last/masking one under R's
/// lookup rules) is one of R's default packages.
fn origin_is_default(origin: PackageOrigin) -> bool {
    let pkg = match &origin {
        PackageOrigin::Resolved(pkg) => Some(pkg.as_str()),
        PackageOrigin::Ambiguous(pkgs) => pkgs.last().map(|p| p.as_str()),
        PackageOrigin::Unknown => None,
    };
    pkg.is_some_and(|p| crate::semantic::symbols::default_packages().contains(&p))
}

/// Configured set of rules for a single linting run, plus the derived dispatch
/// state that only depends on the rule set: the node-dispatch table and each
/// rule's stamped severity. Both are computed once here (in [`from_rules`], via
/// [`resolve`]) rather than rebuilt per file in [`run_rules`], so reusing one
/// `ResolvedRules` across many files — the CLI batch pass, and the LSP lint
/// worker, which caches it across keystrokes — pays that cost only once.
///
/// [`from_rules`]: ResolvedRules::from_rules
/// [`resolve`]: ResolvedRules::resolve
pub struct ResolvedRules {
    pub rules: Vec<Box<dyn Rule>>,
    /// Node-dispatch table: `kind as usize` -> indices into `rules` of the rules
    /// that subscribed to that kind via [`Rule::interests`]. `SyntaxKind` is a
    /// contiguous `#[repr(u16)]`, so a flat Vec indexed by kind beats a hash map.
    by_kind: Vec<Vec<usize>>,
    /// Whether any rule subscribed to a node kind at all — lets [`run_rules`]
    /// skip the whole-tree traversal when every rule is `check_file`-only.
    any_node_rules: bool,
    /// Each rule ID's [`Rule::default_severity`], so the severity-stamping pass
    /// is an `O(1)` lookup keyed by the finding's rule ID.
    severities: HashMap<&'static str, Severity>,
}

impl ResolvedRules {
    /// Build the derived dispatch state (`by_kind`, `severities`) for a chosen
    /// rule set. The single place that knows how a rule set maps to dispatch.
    fn from_rules(rules: Vec<Box<dyn Rule>>) -> Self {
        let mut by_kind: Vec<Vec<usize>> = vec![Vec::new(); SyntaxKind::COUNT];
        let mut any_node_rules = false;
        for (i, rule) in rules.iter().enumerate() {
            for kind in rule.interests() {
                by_kind[*kind as usize].push(i);
                any_node_rules = true;
            }
        }
        let severities = rules
            .iter()
            .map(|r| (r.id(), r.default_severity()))
            .collect();
        Self {
            rules,
            by_kind,
            any_node_rules,
            severities,
        }
    }

    /// Build the rule set honoring `select` / `ignore` from `LintConfig`.
    ///
    /// Resolution order:
    /// 1. Start with all rules whose `default_enabled()` is `true`, unless
    ///    `select` is set (then start with the listed rules instead).
    /// 2. Subtract anything in `ignore`.
    /// 3. Unknown rule IDs in `select` or `ignore` are returned via the second
    ///    element of the tuple so the caller can surface them.
    pub fn resolve(select: Option<&[String]>, ignore: &[String]) -> (Self, Vec<String>) {
        // Instantiate the registry once and derive the known-ID set from it —
        // rather than calling `all_rule_ids()` (a second `all_rules()`) — since
        // this runs per file on the CLI batch pass.
        let all = all_rules();
        let mut unknown = Vec::new();
        for id in select.iter().flat_map(|v| v.iter()).chain(ignore.iter()) {
            if !all.iter().any(|r| r.id() == id.as_str()) {
                unknown.push(id.clone());
            }
        }
        let mut chosen: Vec<Box<dyn Rule>> = match select {
            Some(picks) => all
                .into_iter()
                .filter(|r| picks.iter().any(|p| p == r.id()))
                .collect(),
            None => all.into_iter().filter(|r| r.default_enabled()).collect(),
        };
        chosen.retain(|r| !ignore.iter().any(|i| i == r.id()));
        (Self::from_rules(chosen), unknown)
    }

    pub fn default_set() -> Self {
        let (set, _) = Self::resolve(None, &[]);
        set
    }
}

/// Run every configured rule against a single file's CST + model. Diagnostics
/// are stably sorted by `(start, end, rule)` before returning.
///
/// The dispatch table (`resolved.by_kind`) and severity map are precomputed on
/// `resolved`, so this is on the hot path only for the per-file traversal and
/// the rules' own work, not for rebuilding the rule-set-derived state.
pub fn run_rules(
    resolved: &ResolvedRules,
    path: &Path,
    root: &SyntaxNode,
    model: &SemanticModel,
    symbols: &dyn SymbolProvider,
    project: Option<&FileScope<'_>>,
    resolution: Option<&ExternalResolution>,
) -> Vec<Diagnostic> {
    let ctx = RuleContext {
        path,
        root,
        model,
        symbols,
        project,
        resolution,
    };
    let rules = &resolved.rules;
    let mut all = Vec::new();

    // Single shared traversal feeding every node-shape rule. Visits tokens too
    // (`descendants_with_tokens`) so token-level rules can subscribe to e.g.
    // `IDENT` or `COMMENT`.
    if resolved.any_node_rules {
        for el in root.descendants_with_tokens() {
            for &i in &resolved.by_kind[el.kind() as usize] {
                rules[i].check(&el, &ctx, &mut all);
            }
        }
    }

    // Whole-file pass for model-/comment-driven rules.
    for rule in rules {
        rule.check_file(&ctx, &mut all);
    }

    // Stamp each finding's severity from its rule's `default_severity()`. Rules
    // build findings with a placeholder severity (`Default::default()`); the
    // authoritative value lives on the rule, so overriding `default_severity()`
    // actually takes effect here (and is the natural seam for a future per-rule
    // severity config override). Keyed by rule ID against the parallel `rules`
    // /`severities` vecs — a whole-file pass may interleave findings from
    // several rules, so post-hoc lookup is simpler than tracking emit order.
    for d in &mut all {
        if let Some(&sev) = resolved.severities.get(d.rule) {
            d.severity = sev;
        }
    }

    all.sort_by(|a, b| {
        (u32::from(a.range.start()), u32::from(a.range.end()), a.rule).cmp(&(
            u32::from(b.range.start()),
            u32::from(b.range.end()),
            b.rule,
        ))
    });
    all
}

/// Provide a sane default symbol provider: base R only, with no installed-
/// package index. Behaves exactly like the historical `StaticBaseR` for files
/// that don't attach non-default packages.
pub fn default_symbol_provider() -> CompositeProvider {
    CompositeProvider::base_only()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::linter::diagnostic::ViolationData;

    /// A rule that subscribes to every `CALL_EXPR` and emits a finding carrying
    /// the *placeholder* severity (`Default::default()` == `Warning`). Its
    /// `default_severity` is overridden to `Error`, so a run that respects the
    /// override must stamp `Error` — proving `default_severity` is live, not the
    /// dead trait method it used to be.
    struct FakeError;
    impl Rule for FakeError {
        fn id(&self) -> &'static str {
            "fake-error"
        }
        fn default_severity(&self) -> Severity {
            Severity::Error
        }
        fn interests(&self) -> &'static [SyntaxKind] {
            &[SyntaxKind::CALL_EXPR]
        }
        fn check(&self, el: &SyntaxElement, _ctx: &RuleContext<'_>, sink: &mut Vec<Diagnostic>) {
            sink.push(Diagnostic {
                rule: "fake-error",
                severity: Default::default(),
                path: Default::default(),
                range: el.text_range(),
                message: ViolationData::new("fake-error", "boom"),
                fix: None,
            });
        }
    }

    #[test]
    fn run_rules_stamps_default_severity() {
        let root = crate::parser::parse("f(1)").cst;
        let model = SemanticModel::build(&root);
        let symbols = crate::semantic::StaticBaseR::new();
        let resolved = ResolvedRules::from_rules(vec![Box::new(FakeError)]);
        let diags = run_rules(
            &resolved,
            Path::new("test.R"),
            &root,
            &model,
            &symbols,
            None,
            None,
        );
        assert_eq!(diags.len(), 1);
        // Emitted with the `Warning` placeholder; the override stamps `Error`.
        assert_eq!(diags[0].severity, Severity::Error);
    }

    /// `resolves_to_base` for the first `CallExpr` in `src`, over the base-only
    /// `StaticBaseR` provider (the single-file / LSP path).
    fn resolves(src: &str) -> bool {
        let root = crate::parser::parse(src).cst;
        let model = SemanticModel::build(&root);
        let symbols = crate::semantic::StaticBaseR::new();
        let ctx = RuleContext {
            path: Path::new("test.R"),
            root: &root,
            model: &model,
            symbols: &symbols,
            project: None,
            resolution: None,
        };
        let call = root
            .descendants()
            .find_map(CallExpr::cast)
            .expect("a call in the source");
        ctx.resolves_to_base(&call)
    }

    #[test]
    fn confirms_unshadowed_base_call() {
        assert!(resolves("c(1, 2)"));
        assert!(resolves("f <- function() sum(a)"));
    }

    #[test]
    fn rejects_local_value_shadow() {
        // The first call is `c(2, 3)`; the local `c <- 1` shadows base `c`.
        assert!(!resolves("c <- 1\nc(2, 3)"));
    }

    #[test]
    fn rejects_function_redefinition() {
        assert!(!resolves("any <- function(x) x\nany(z)"));
    }

    #[test]
    fn rejects_nested_scope_shadow() {
        assert!(!resolves("f <- function() {\n  sum <- 1\n  sum(a)\n}"));
    }

    #[test]
    fn rejects_non_base_name() {
        assert!(!resolves("frobnicate(1)"));
    }

    #[test]
    fn rejects_qualified_callee() {
        assert!(!resolves("dplyr::filter(x)"));
    }

    #[test]
    fn rejects_computed_callee() {
        assert!(!resolves("(g())(1)"));
    }
}