fatou 0.8.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
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
use std::io::{IsTerminal, Read};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::Parser;
use rayon::prelude::*;

use fatou::cli::{
    Cli, ColorChoice, Commands, DebugChecksArg, DebugCommand, LintOutput, ParseFormat,
};
use fatou::config::Config;
use fatou::debug::{
    CheckKind, DebugArtifacts, DebugFailure, build_debug_report, checks_label,
    run_debug_checks_for_file, sanitize_path_for_filename, write_debug_artifacts,
};
use fatou::file_discovery::ExcludeFilter;
use fatou::formatter::{self, FormatStyle};
use fatou::linter::{self, LintStatus, OutputMode};
use fatou::parser::{parse, reconstruct, to_juliasyntax_sexpr};

fn main() -> ExitCode {
    env_logger::init();
    let cli = Cli::parse();

    match run(cli) {
        Ok(code) => code,
        Err(message) => {
            eprintln!("error: {message}");
            ExitCode::FAILURE
        }
    }
}

fn run(cli: Cli) -> Result<ExitCode, String> {
    match cli.command {
        Commands::Parse {
            file,
            quiet,
            verify,
            to,
        } => run_parse(file, quiet, verify, to),
        Commands::Format {
            paths,
            check,
            line_width,
            indent_width,
            exclude,
            force_exclude,
        } => {
            let (config, config_path) = load_config(&cli.config, cli.no_config)?;
            let style = style_with_overrides(&config, line_width, indent_width);
            let filter =
                resolve_exclude_filter(&config, config_path.as_deref(), &exclude, force_exclude)?;
            run_format(paths, check, style, &filter)
        }
        Commands::Lint {
            paths,
            fix,
            unsafe_fixes,
            exclude,
            force_exclude,
            output,
        } => {
            let (config, config_path) = load_config(&cli.config, cli.no_config)?;
            let filter =
                resolve_exclude_filter(&config, config_path.as_deref(), &exclude, force_exclude)?;
            run_lint(
                paths,
                output,
                fix,
                unsafe_fixes,
                cli.color,
                &config,
                &filter,
            )
        }
        Commands::Lsp => fatou::lsp::run()
            .map(|()| ExitCode::SUCCESS)
            .map_err(|err| err.to_string()),
        Commands::Debug { command } => match command {
            DebugCommand::Format {
                paths,
                checks,
                report,
                dump_dir,
                dump_passes,
                exclude,
                force_exclude,
            } => {
                let (config, config_path) = load_config(&cli.config, cli.no_config)?;
                let style = style_with_overrides(&config, None, None);
                let filter = resolve_exclude_filter(
                    &config,
                    config_path.as_deref(),
                    &exclude,
                    force_exclude,
                )?;
                run_debug_format(
                    &paths,
                    checks,
                    report,
                    dump_dir.as_deref(),
                    dump_passes,
                    style,
                    &filter,
                )
            }
        },
    }
}

/// `fatou debug format`: check invariants over the discovered files, writing
/// nothing back. Exit 0 when everything passes, 1 on any failure or unreadable
/// file (config and discovery errors keep their usual codes upstream).
fn run_debug_format(
    paths: &[PathBuf],
    checks: DebugChecksArg,
    report: bool,
    dump_dir: Option<&Path>,
    dump_passes: bool,
    style: FormatStyle,
    exclude: &ExcludeFilter,
) -> Result<ExitCode, String> {
    if paths.is_empty() {
        eprintln!("fatou: debug format requires at least one file or directory");
        return Ok(ExitCode::from(2));
    }
    let files =
        fatou::file_discovery::collect_julia_files(paths, exclude).map_err(|e| e.to_string())?;
    if files.is_empty() {
        if exclude.force() {
            return Ok(ExitCode::SUCCESS);
        }
        return Err("no .jl files found under the provided input paths".to_string());
    }

    // Checks are pure functions of the file content, so they parallelize like
    // `run_format`; the order-preserving collect keeps output and report
    // numbering deterministic.
    let outcomes: Vec<(String, Result<DebugArtifacts, String>)> = files
        .par_iter()
        .map(|path| {
            let label = path.display().to_string();
            let outcome = match std::fs::read_to_string(path) {
                Ok(content) => Ok(run_debug_checks_for_file(&content, style, checks)),
                Err(err) => Err(format!("fatou: cannot read {label}: {err}")),
            };
            (label, outcome)
        })
        .collect();

    let mut files_checked = 0usize;
    let mut io_failed = false;
    let mut collected: Vec<(String, DebugFailure)> = Vec::new();
    for (label, outcome) in outcomes {
        match outcome {
            Err(msg) => {
                eprintln!("{msg}");
                io_failed = true;
            }
            Ok(artifacts) => {
                files_checked += 1;
                if let Some(dir) = dump_dir {
                    let stem = sanitize_path_for_filename(&label);
                    if let Err(err) = write_debug_artifacts(dir, &stem, &artifacts, dump_passes) {
                        eprintln!(
                            "fatou: cannot write debug artifacts to {}: {err}",
                            dir.display()
                        );
                        io_failed = true;
                    }
                }
                for failure in artifacts.failures {
                    if !report {
                        eprintln!("Debug check failed ({}) in {label}", failure.kind.label());
                        if failure.kind == CheckKind::FormatError {
                            eprintln!("  {}", failure.left);
                        }
                    }
                    collected.push((label.clone(), failure));
                }
            }
        }
    }

    if report {
        print!("{}", build_debug_report(checks, files_checked, &collected));
    } else if collected.is_empty() && !io_failed {
        println!(
            "All checks passed (checks: {}, files: {files_checked})",
            checks_label(checks)
        );
    }
    Ok(if collected.is_empty() && !io_failed {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    })
}

fn run_parse(
    file: Option<PathBuf>,
    quiet: bool,
    verify: bool,
    to: ParseFormat,
) -> Result<ExitCode, String> {
    let text = read_source(file.as_deref())?;
    let output = parse(&text);

    if !quiet {
        match to {
            ParseFormat::Cst => print!("{:#?}", output.cst),
            ParseFormat::Sexpr => {
                println!("{}", to_juliasyntax_sexpr(&output.cst, &output.diagnostics))
            }
        }
        for diag in &output.diagnostics {
            eprintln!(
                "diagnostic [{}..{}]: {}",
                diag.start, diag.end, diag.message
            );
        }
    }

    if verify {
        let reconstructed = reconstruct(&text);
        if reconstructed == text {
            eprintln!("losslessness OK");
        } else {
            eprintln!("losslessness FAILED: reconstruction differs from input");
            return Ok(ExitCode::FAILURE);
        }
    }

    Ok(ExitCode::SUCCESS)
}

fn run_format(
    paths: Vec<PathBuf>,
    check: bool,
    style: FormatStyle,
    exclude: &ExcludeFilter,
) -> Result<ExitCode, String> {
    // No paths: format stdin to stdout.
    if paths.is_empty() {
        let text = read_source(None)?;
        let formatted = formatter::format_with_style(&text, style).map_err(|e| e.to_string())?;
        print!("{formatted}");
        return Ok(ExitCode::SUCCESS);
    }

    if check {
        let result = formatter::check_paths(&paths, style, exclude).map_err(|e| e.to_string())?;
        for changed in &result.changed {
            println!("would reformat {}", changed.path.display());
            print!("{}", changed.diff);
        }
        return Ok(if result.changed.is_empty() {
            ExitCode::SUCCESS
        } else {
            ExitCode::FAILURE
        });
    }

    let files =
        fatou::file_discovery::collect_julia_files(&paths, exclude).map_err(|e| e.to_string())?;
    files.par_iter().try_for_each(|path| {
        let original = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
        let formatted =
            formatter::format_with_style(&original, style).map_err(|e| e.to_string())?;
        if formatted != original {
            std::fs::write(path, formatted).map_err(|e| e.to_string())?;
        }
        Ok::<(), String>(())
    })?;
    Ok(ExitCode::SUCCESS)
}

fn run_lint(
    paths: Vec<PathBuf>,
    output: LintOutput,
    fix: bool,
    unsafe_fixes: bool,
    color: ColorChoice,
    config: &Config,
    exclude: &ExcludeFilter,
) -> Result<ExitCode, String> {
    if paths.is_empty() {
        return Err("lint requires at least one path".to_string());
    }

    let mode = match output {
        LintOutput::Pretty => OutputMode::Pretty,
        LintOutput::Concise => OutputMode::Concise,
        LintOutput::Json => OutputMode::Json,
    };

    if fix || unsafe_fixes {
        return run_lint_fix(paths, mode, unsafe_fixes, color, config, exclude);
    }

    let use_color = color_enabled(color, std::io::stderr().is_terminal());
    let result = linter::check_paths_with_config(&paths, &config.lint, exclude)
        .map_err(|e| e.to_string())?;
    warn_unknown_rules(&result.unknown_rules);

    let diagnostics: Vec<_> = result
        .reports
        .iter()
        .flat_map(|report| report.diagnostics.clone())
        .collect();
    let rendered = linter::render_findings(&diagnostics, mode, use_color, &|path| {
        path.and_then(|p| std::fs::read_to_string(p).ok())
    });
    emit(mode, &rendered);

    let has_parse_errors = result
        .reports
        .iter()
        .any(|report| matches!(report.status, LintStatus::ParseDiagnostics { .. }));
    if result.total_findings > 0 || has_parse_errors {
        Ok(ExitCode::FAILURE)
    } else {
        eprintln!("checked {} file(s): clean", result.checked_files);
        Ok(ExitCode::SUCCESS)
    }
}

/// Apply fixes across every discovered file, writing changed files back, then
/// report whatever findings remain. Exits non-zero if any remain (Ruff-style).
fn run_lint_fix(
    paths: Vec<PathBuf>,
    mode: OutputMode,
    unsafe_fixes: bool,
    color: ColorChoice,
    config: &Config,
    exclude: &ExcludeFilter,
) -> Result<ExitCode, String> {
    let use_color = color_enabled(color, std::io::stderr().is_terminal());
    let (_, unknown_rules) = linter::ResolvedRules::resolve(&config.lint);
    warn_unknown_rules(&unknown_rules);
    let files =
        fatou::file_discovery::collect_julia_files(&paths, exclude).map_err(|e| e.to_string())?;

    // Fix files in parallel; each writes back to its own path. Per-file results
    // are reduced afterward so counts and the `remaining` list stay stable.
    let outcomes = files
        .par_iter()
        .map(|path| {
            let original = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
            let outcome = linter::fix_source(Some(path), &original, &config.lint, unsafe_fixes);
            let changed = outcome.output != original;
            if changed {
                std::fs::write(path, &outcome.output).map_err(|e| e.to_string())?;
            }
            Ok::<_, String>((outcome.applied, changed, outcome.remaining))
        })
        .collect::<Result<Vec<_>, String>>()?;

    let mut applied = 0usize;
    let mut changed_files = 0usize;
    let mut remaining = Vec::new();
    for (file_applied, changed, file_remaining) in outcomes {
        applied += file_applied;
        if changed {
            changed_files += 1;
        }
        remaining.extend(file_remaining);
    }

    let rendered = linter::render_findings(&remaining, mode, use_color, &|path| {
        path.and_then(|p| std::fs::read_to_string(p).ok())
    });
    emit(mode, &rendered);

    if applied > 0 {
        eprintln!("fixed {applied} issue(s) in {changed_files} file(s)");
    }

    if remaining.is_empty() {
        Ok(ExitCode::SUCCESS)
    } else {
        Ok(ExitCode::FAILURE)
    }
}

/// Warn (once, to stderr) about any `select`/`ignore` entry that names no
/// shipped rule, so a typo'd `--select` doesn't silently select nothing.
fn warn_unknown_rules(unknown: &[String]) {
    for id in unknown {
        eprintln!("warning: unknown rule `{id}` in select/ignore/severity");
    }
}

/// Route rendered lint output: JSON to stdout (machine-readable), human-facing
/// pretty/concise to stderr.
fn emit(mode: OutputMode, rendered: &str) {
    if matches!(mode, OutputMode::Json) {
        print!("{rendered}");
    } else {
        eprint!("{rendered}");
    }
}

fn color_enabled(choice: ColorChoice, is_terminal: bool) -> bool {
    match choice {
        ColorChoice::Always => true,
        ColorChoice::Never => false,
        ColorChoice::Auto => std::env::var_os("NO_COLOR").is_none() && is_terminal,
    }
}

fn style_with_overrides(
    config: &Config,
    line_width: Option<u32>,
    indent_width: Option<u32>,
) -> FormatStyle {
    let mut style = FormatStyle::from(&config.format);
    if let Some(width) = line_width {
        style.line_width = width;
    }
    if let Some(width) = indent_width {
        style.indent_width = width;
    }
    style
}

/// Build the file-discovery exclude filter from the resolved config plus any
/// `--exclude` CLI patterns, applying `--force-exclude`. Patterns resolve
/// relative to the directory holding `fatou.toml` (or the working directory
/// when there is no config file).
fn resolve_exclude_filter(
    config: &Config,
    config_path: Option<&Path>,
    cli_patterns: &[String],
    force: bool,
) -> Result<ExcludeFilter, String> {
    let anchor = std::env::current_dir().map_err(|e| e.to_string())?;
    let filter = config
        .exclude_filter(config_path, &anchor, cli_patterns)
        .map_err(|e| e.to_string())?;
    Ok(filter.with_force_exclude(force))
}

/// Resolve the config, returning it alongside the loaded file's path (if any),
/// needed to root exclude patterns relative to the directory containing
/// `fatou.toml`.
fn load_config(
    explicit_config: &Option<PathBuf>,
    no_config: bool,
) -> Result<(Config, Option<PathBuf>), String> {
    let anchor = std::env::current_dir().map_err(|e| e.to_string())?;
    let (config, path, warnings) = Config::resolve(explicit_config.as_deref(), no_config, &anchor)
        .map_err(|e| e.to_string())?;
    for warning in &warnings {
        eprintln!("warning: {warning}");
    }
    Ok((config, path))
}

fn read_source(path: Option<&Path>) -> Result<String, String> {
    match path {
        Some(path) => std::fs::read_to_string(path).map_err(|e| e.to_string()),
        None => {
            let mut buffer = String::new();
            std::io::stdin()
                .read_to_string(&mut buffer)
                .map_err(|e| e.to_string())?;
            Ok(buffer)
        }
    }
}