fatou 0.22.0

A language server, formatter, and linter for Julia
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
//! The linting pipeline: parse each file, run the enabled rules, and report a
//! status. Parse diagnostics block the rules for a file (they need a clean
//! tree) but are still reported, under the [`PARSE_ERROR_RULE`] pseudo-rule.

use std::path::{Path, PathBuf};

use rayon::prelude::*;

use std::collections::BTreeMap;
use std::sync::{Arc, OnceLock};

use crate::config::LintConfig;
use crate::file_discovery::{ExcludeFilter, FileDiscoveryError, collect_julia_files};
use crate::index::{DeclaredDeps, PackageIndex, build_system_index};
use crate::julia_version::VersionRange;
use rowan::TextRange;

use crate::linter::diagnostic::{Diagnostic, Severity, ViolationData};
use crate::linter::include_graph::{IncludeProblem, include_problems};
use crate::linter::rules::{ResolutionContext, ResolvedRules, RuleContext};
use crate::linter::suppression::SuppressionMap;
use crate::parser::parse;
use crate::semantic::SemanticModel;
use crate::syntax::SyntaxNode;

/// The pseudo-rule id under which parse diagnostics are reported.
pub const PARSE_ERROR_RULE: &str = "parse-error";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LintStatus {
    Clean,
    Findings { count: usize },
    ParseDiagnostics { count: usize },
}

#[derive(Debug, Clone)]
pub struct LintFileReport {
    pub path: Option<PathBuf>,
    pub status: LintStatus,
    pub diagnostics: Vec<Diagnostic>,
}

#[derive(Debug, Clone)]
pub struct LintResult {
    pub checked_files: usize,
    pub total_findings: usize,
    pub reports: Vec<LintFileReport>,
    /// `select`/`ignore` entries that name no shipped rule (likely typos).
    pub unknown_rules: Vec<String>,
}

#[derive(Debug)]
pub enum LintError {
    Discovery(FileDiscoveryError),
    Io { path: PathBuf, message: String },
}

impl std::fmt::Display for LintError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LintError::Discovery(err) => write!(f, "{err}"),
            LintError::Io { path, message } => {
                write!(f, "failed to read {}: {message}", path.display())
            }
        }
    }
}

impl std::error::Error for LintError {}

/// What the linter resolves free reads against. `SystemOnly` is the built-in
/// Base/Core snapshot with no workspace (single-file mode: `undefined-name`
/// stays opt-in and file-local). `Harvested` carries a project's harvested
/// library and derives each file's workspace membership, so cross-file names —
/// a sibling file's `using`/`import`, a same-module global — resolve exactly as
/// they do in the language server.
#[derive(Clone, Copy)]
pub enum ProjectContext<'a> {
    SystemOnly,
    Harvested(&'a crate::index::HarvestedLibrary),
    /// Explicit script programs, with the environment's library when available.
    Scripts {
        library: Option<&'a crate::index::HarvestedLibrary>,
        scripts: &'a crate::project::scripts::ScriptAnalysis,
    },
    /// The built-in snapshot plus a declared dependency set, as if the file were
    /// a source file of a package whose `Project.toml` `[deps]` list those
    /// names. The docs generator's stand-in for a real project, so
    /// `unresolved-import`'s examples render (see
    /// [`Rule::example_declared_deps`](crate::linter::rules::Rule::example_declared_deps));
    /// no discovery path produces it.
    SystemInProject(&'a DeclaredDeps),
}

impl<'a> ProjectContext<'a> {
    /// The [`ResolutionContext`] for the file at `path`, if any.
    ///
    /// The declared dependency set rides along only for a *package source
    /// file*: a file the harvest placed inside a workspace package, whose
    /// `using`/`import` clauses really do load against that package's own
    /// project. Everything else — a script, a `test/` file, a loose buffer —
    /// gets `None` and leaves `unresolved-import` silent.
    fn resolution_for(self, path: Option<&Path>) -> Option<ResolutionContext<'a>> {
        match self {
            ProjectContext::Scripts { library, scripts } => {
                let mut resolution = match library {
                    Some(lib) => ProjectContext::Harvested(lib).resolution_for(path)?,
                    None => ProjectContext::SystemOnly.resolution_for(path)?,
                };
                if path.is_some_and(|path| scripts.applies(path)) {
                    resolution.workspace = None;
                    resolution.declared_deps = None;
                }
                Some(resolution)
            }
            ProjectContext::SystemOnly => Some(ResolutionContext {
                packages: system_snapshot(),
                workspace: None,
                declared_deps: None,
            }),
            ProjectContext::SystemInProject(deps) => Some(ResolutionContext {
                packages: system_snapshot(),
                workspace: None,
                declared_deps: Some(Arc::new(deps.clone())),
            }),
            ProjectContext::Harvested(lib) => {
                let workspace = path.and_then(|p| lib.workspace_member(p));
                let declared_deps = workspace
                    .as_ref()
                    .and_then(|(pkg, _)| lib.declared_deps.get(&pkg.name).cloned());
                Some(ResolutionContext {
                    packages: &lib.packages,
                    workspace,
                    declared_deps,
                })
            }
        }
    }
}

/// Lint every `.jl` file under `paths` with default configuration.
pub fn check_paths(paths: &[PathBuf]) -> Result<LintResult, LintError> {
    check_paths_with_config(
        paths,
        &LintConfig::default(),
        &ExcludeFilter::none(),
        None,
        ProjectContext::SystemOnly,
    )
}

/// Lint every `.jl` file under `paths`, honoring `config` and `exclude`.
/// `julia_target` is the project's declared Julia support range (for the
/// `julia-version-compat` rule); `None` leaves version-gated rules silent.
pub fn check_paths_with_config(
    paths: &[PathBuf],
    config: &LintConfig,
    exclude: &ExcludeFilter,
    julia_target: Option<VersionRange>,
    project: ProjectContext<'_>,
) -> Result<LintResult, LintError> {
    let files = collect_julia_files(paths, exclude).map_err(LintError::Discovery)?;
    let (rules, unknown_rules) = ResolvedRules::resolve(config);
    let rules = rules.with_julia_target(julia_target);
    let script_rules = match project {
        ProjectContext::Scripts { .. } => Some(
            ResolvedRules::resolve_for_scripts(config)
                .0
                .with_julia_target(julia_target),
        ),
        _ => None,
    };

    // Read and parse every file up front (in parallel): the include-graph
    // pre-pass wants all trees before the per-file rule runs, so a file's
    // include edges are answered from the lint set instead of re-parsed from
    // disk. Only the green trees cross the thread boundary (`SyntaxNode` is
    // `Rc`-based and not `Send`); each consumer rebuilds its red tree, which
    // is cheap. `collect` keeps the sorted discovery order for deterministic
    // reporting.
    let parsed = files
        .par_iter()
        .map(|path| {
            let text = std::fs::read_to_string(path).map_err(|err| LintError::Io {
                path: path.clone(),
                message: err.to_string(),
            })?;
            let out = parse(&text);
            Ok((path.clone(), out.cst.green().to_owned(), out.diagnostics))
        })
        .collect::<Result<Vec<_>, LintError>>()?;

    let seeds: Vec<(PathBuf, SyntaxNode)> = parsed
        .iter()
        .map(|(path, green, _)| (path.clone(), SyntaxNode::new_root(green.clone())))
        .collect();
    let include_problems = include_problems(&seeds);

    let reports: Vec<LintFileReport> = parsed
        .par_iter()
        .map(|(path, green, diagnostics)| {
            let root = SyntaxNode::new_root(green.clone());
            let includes = include_problems
                .get(path)
                .map(Vec::as_slice)
                .unwrap_or_default();
            let rules = match (project, &script_rules) {
                (ProjectContext::Scripts { scripts, .. }, Some(rules)) if scripts.applies(path) => {
                    rules
                }
                _ => &rules,
            };
            check_parsed(Some(path), &root, diagnostics, rules, includes, project)
        })
        .collect();

    let total_findings = reports
        .iter()
        .filter_map(|report| match report.status {
            LintStatus::Findings { count } => Some(count),
            _ => None,
        })
        .sum();

    Ok(LintResult {
        checked_files: files.len(),
        total_findings,
        reports,
        unknown_rules,
    })
}

/// Lint an in-memory document with no path (e.g. stdin).
pub fn check_document(text: &str) -> LintFileReport {
    let (rules, _) = ResolvedRules::resolve(&LintConfig::default());
    check_text(None, text, &rules, ProjectContext::SystemOnly)
}

/// Lint `text` under `config`, attributing findings to `path`. Used by the docs
/// generator (`crate::linter::docs`) to render each example's real diagnostics.
pub fn check_source(path: Option<&Path>, text: &str, config: &LintConfig) -> LintFileReport {
    check_source_with_target(path, text, config, None)
}

/// Like [`check_source`], but with a Julia target range for version-gated rules
/// (`julia-version-compat`). The docs generator and version-compat tests use
/// this to make the target-dependent examples fire.
pub fn check_source_with_target(
    path: Option<&Path>,
    text: &str,
    config: &LintConfig,
    julia_target: Option<VersionRange>,
) -> LintFileReport {
    check_source_in_project(path, text, config, julia_target, None)
}

/// Like [`check_source_with_target`], but linting `text` as a source file of a
/// package whose `Project.toml` `[deps]` are `declared_deps`. `None` keeps the
/// loose-file reading of [`check_source_with_target`]. The docs generator uses
/// this to render the examples of the project-gated rules
/// (`unresolved-import`), which have no findings outside a project.
pub fn check_source_in_project(
    path: Option<&Path>,
    text: &str,
    config: &LintConfig,
    julia_target: Option<VersionRange>,
    declared_deps: Option<&[&str]>,
) -> LintFileReport {
    let (rules, _) = ResolvedRules::resolve(config);
    let rules = rules.with_julia_target(julia_target);
    let deps: Option<DeclaredDeps> =
        declared_deps.map(|names| names.iter().map(|n| (*n).to_string()).collect());
    let project = match &deps {
        Some(deps) => ProjectContext::SystemInProject(deps),
        None => ProjectContext::SystemOnly,
    };
    check_text(path, text, &rules, project)
}

/// Single-file entry: parse, follow the file's own include chains (no lint-set
/// siblings to seed — used for stdin, docs examples, and tests), then lint.
pub fn check_text(
    path: Option<&Path>,
    text: &str,
    rules: &ResolvedRules,
    project: ProjectContext<'_>,
) -> LintFileReport {
    let parsed = parse(text);
    let include_problems = match path {
        // A pathless document has no base directory to resolve includes
        // against; the include-graph rules stay silent.
        Some(path) => {
            let seeds = [(path.to_path_buf(), parsed.cst.clone())];
            include_problems(&seeds).remove(path).unwrap_or_default()
        }
        None => Vec::new(),
    };
    check_parsed(
        path,
        &parsed.cst,
        &parsed.diagnostics,
        rules,
        &include_problems,
        project,
    )
}

/// Core per-file pass over an already-parsed file: run rules on a clean tree
/// (suppressed findings are dropped inside the rules runner). Parse-error
/// pseudo-diagnostics short-circuit before rules or suppression run, so
/// `parse-error` is not suppressible — by design.
fn check_parsed(
    path: Option<&Path>,
    root: &SyntaxNode,
    parse_diagnostics: &[crate::parser::ParseDiagnostic],
    rules: &ResolvedRules,
    includes: &[IncludeProblem],
    project: ProjectContext<'_>,
) -> LintFileReport {
    if !parse_diagnostics.is_empty() {
        let diagnostics = parse_diagnostics
            .iter()
            .map(|diag| Diagnostic {
                rule: PARSE_ERROR_RULE,
                severity: Severity::Error,
                path: path.map(Path::to_path_buf),
                range: TextRange::new((diag.start as u32).into(), (diag.end as u32).into()),
                message: ViolationData::new(PARSE_ERROR_RULE, diag.message.clone()),
                fixes: Vec::new(),
            })
            .collect();
        return LintFileReport {
            path: path.map(Path::to_path_buf),
            status: LintStatus::ParseDiagnostics {
                count: parse_diagnostics.len(),
            },
            diagnostics,
        };
    }

    let model = SemanticModel::build(root);
    // The resolution the caller chose: the built-in Base/Core snapshot with no
    // workspace (single-file mode — deterministic and cheap, and why
    // `undefined-name` is opt-in there), or a harvested project library plus
    // this file's workspace membership, which resolves cross-file names.
    let resolution = project.resolution_for(path);
    let scripts = match project {
        ProjectContext::Scripts { scripts, .. } => Some(scripts),
        _ => None,
    };
    let diagnostics =
        lint_parsed_with_scripts(path, root, &model, rules, resolution, includes, scripts);

    let status = if diagnostics.is_empty() {
        LintStatus::Clean
    } else {
        LintStatus::Findings {
            count: diagnostics.len(),
        }
    };

    LintFileReport {
        path: path.map(Path::to_path_buf),
        status,
        diagnostics,
    }
}

/// The built-in Base/Core export snapshot, built once per process. The
/// resolution floor for CLI lint runs (and docs generation), where locating
/// and harvesting a real Julia install would be slow and nondeterministic.
pub(crate) fn system_snapshot() -> &'static BTreeMap<String, Arc<PackageIndex>> {
    static SNAPSHOT: OnceLock<BTreeMap<String, Arc<PackageIndex>>> = OnceLock::new();
    SNAPSHOT.get_or_init(|| build_system_index(None))
}

/// Run `rules` against an already-parsed *clean* tree (rules need one; the
/// caller is responsible for gating on parse diagnostics). The file's
/// `# fatou-ignore` directives are parsed off the CST here; the suppressed
/// findings are dropped inside [`ResolvedRules::run`], which needs the
/// directive list on the [`RuleContext`] anyway. Shared by [`check_text`] and
/// the language server, whose warm path lints off the salsa-cached tree and
/// model instead of re-parsing (and passes its own harvested library as the
/// `resolution` context).
pub fn lint_parsed(
    path: Option<&Path>,
    root: &SyntaxNode,
    model: &SemanticModel,
    rules: &ResolvedRules,
    resolution: Option<ResolutionContext<'_>>,
    includes: &[IncludeProblem],
) -> Vec<Diagnostic> {
    lint_parsed_with_scripts(path, root, model, rules, resolution, includes, None)
}

/// Project-aware linting without adding another rule traversal or suppression pass.
#[allow(clippy::too_many_arguments)]
pub fn lint_parsed_with_scripts(
    path: Option<&Path>,
    root: &SyntaxNode,
    model: &SemanticModel,
    rules: &ResolvedRules,
    resolution: Option<ResolutionContext<'_>>,
    includes: &[IncludeProblem],
    scripts: Option<&crate::project::scripts::ScriptAnalysis>,
) -> Vec<Diagnostic> {
    let suppressions = SuppressionMap::build(root);
    let ctx = RuleContext::new(path, root, model)
        .with_resolution(resolution)
        .with_scripts(scripts)
        .with_includes(includes)
        .with_julia_target(rules.julia_target())
        .with_config(rules.rules_config())
        .with_suppressions(&suppressions)
        .with_enabled_rules(rules.enabled());
    rules.run(&ctx)
}

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

    #[test]
    fn clean_file_reports_clean() {
        let report = check_document("x = 1\n");
        assert_eq!(report.status, LintStatus::Clean);
    }

    #[test]
    fn parse_diagnostics_are_surfaced() {
        let report = check_document("f (x)\n");
        assert!(matches!(
            report.status,
            LintStatus::ParseDiagnostics { count } if count > 0
        ));
        assert_eq!(report.diagnostics.len(), 1);
        let diag = &report.diagnostics[0];
        assert_eq!(diag.rule, PARSE_ERROR_RULE);
        assert_eq!(diag.severity, Severity::Error);
        assert!(!diag.message.body.is_empty());
    }
}