pedant 0.14.0

An opinionated Rust linter, with special focus on AI-generated code
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
//! CLI interface for the pedant linter and capability analyzer.

mod config;
mod reporter;

use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io::{self, Read, Write};
use std::path::Path;
use std::process::ExitCode;
#[cfg(feature = "semantic")]
use std::time::Instant;
use std::time::SystemTime;

use clap::Parser;
use pedant_core::AnalysisResult;
use pedant_core::SemanticContext;
use pedant_core::check_config::{CheckConfig, ConfigFile, find_config_file, load_config_file};
use pedant_core::checks::ALL_CHECKS;
use pedant_core::gate::{GateSeverity, evaluate_gate_rules};
use pedant_core::hash::compute_source_hash;
use pedant_core::lint::{analyze, analyze_build_script, discover_build_script};
use pedant_core::violation::{Violation, lookup_rationale};
use pedant_types::{
    AnalysisTier, AttestationContent, CapabilityDiff, CapabilityFinding, CapabilityProfile,
};

use crate::config::Cli;
use crate::reporter::Reporter;

#[derive(Debug, thiserror::Error)]
enum ProcessError {
    #[error("failed to read stdin: {0}")]
    StdinRead(#[source] std::io::Error),
    #[error("parse error: {0}")]
    Parse(#[from] pedant_core::ParseError),
    #[error("failed to read diff input {path}: {source}")]
    DiffRead {
        path: Box<str>,
        #[source]
        source: std::io::Error,
    },
    #[error("failed to parse diff input {path}: {source}")]
    DiffParse {
        path: Box<str>,
        #[source]
        source: serde_json::Error,
    },
}

struct AnalysisContext<'a> {
    base_config: &'a CheckConfig,
    file_config: Option<&'a ConfigFile>,
    semantic: Option<&'a SemanticContext>,
}

struct AnalysisAccumulator {
    violations: Vec<Violation>,
    findings: Vec<CapabilityFinding>,
    had_error: bool,
}

fn report_error(stderr: &mut impl Write, msg: std::fmt::Arguments<'_>) {
    match writeln!(stderr, "{msg}") {
        Ok(()) | Err(_) => {}
    }
}

impl AnalysisAccumulator {
    fn with_capacity(file_count: usize) -> Self {
        Self {
            violations: Vec::with_capacity(file_count),
            findings: Vec::with_capacity(file_count),
            had_error: false,
        }
    }

    fn handle(
        &mut self,
        result: Result<AnalysisResult, ProcessError>,
        context: &str,
        stderr: &mut impl Write,
    ) {
        match result {
            Ok(r) => {
                self.violations.extend(r.violations);
                self.findings.extend(r.capabilities.findings);
            }
            Err(e) => {
                report_error(stderr, format_args!("{context}: {e}"));
                self.had_error = true;
            }
        }
    }
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    let mut stderr = io::stderr().lock();

    if cli.list_checks {
        return run_print_checks_list(&mut stderr);
    }

    if let Some(ref code) = cli.explain {
        return print_explain(code, &mut stderr);
    }

    if let [old_path, new_path] = cli.diff.as_slice() {
        return run_diff(old_path, new_path, &mut stderr);
    }

    let file_config = match load_file_config(&cli, &mut stderr) {
        Ok(cfg) => cfg,
        Err(exit) => return exit,
    };
    let base_config = cli.to_check_config(file_config.as_ref());
    let mut acc = AnalysisAccumulator::with_capacity(cli.files.len());

    let semantic = load_semantic_if_requested(&cli, &mut stderr);
    let analysis_tier = match semantic.is_some() {
        true => AnalysisTier::Semantic,
        false => AnalysisTier::Syntactic,
    };

    let ctx = AnalysisContext {
        base_config: &base_config,
        file_config: file_config.as_ref(),
        semantic: semantic.as_ref(),
    };

    let source_hash = run_analysis(&cli, &ctx, &mut acc, &mut stderr);

    let reporter = Reporter::new(cli.format, cli.quiet);
    let mut stdout = io::stdout().lock();
    if let Err(e) = reporter.report(&acc.violations, &mut stdout) {
        report_error(&mut stderr, format_args!("error writing output: {e}"));
        return ExitCode::from(2);
    }

    // Evaluate gate rules before findings are consumed by attestation/capabilities output.
    let default_gate = pedant_core::GateConfig::default();
    let gate_verdicts = match cli.gate {
        true => {
            let gate_config = file_config.as_ref().map_or(&default_gate, |fc| &fc.gate);
            evaluate_gate_rules(&acc.findings, gate_config)
        }
        false => Box::new([]),
    };

    if let Err(exit) = dispatch_output(
        &cli,
        source_hash,
        acc.findings,
        analysis_tier,
        &mut stdout,
        &mut stderr,
    ) {
        return exit;
    }

    if let (true, Err(e)) = (cli.gate, reporter.report_gate(&gate_verdicts, &mut stdout)) {
        report_error(&mut stderr, format_args!("error writing gate output: {e}"));
        return ExitCode::from(2);
    }

    compute_exit_code(acc.had_error, acc.violations.is_empty(), &gate_verdicts)
}

/// Select the input source (stdin vs files) and run analysis, returning a source
/// hash when attestation mode requires one.
fn run_analysis(
    cli: &Cli,
    ctx: &AnalysisContext<'_>,
    acc: &mut AnalysisAccumulator,
    stderr: &mut impl Write,
) -> Option<Box<str>> {
    match (cli.attestation, cli.stdin) {
        (true, true) => attest_stdin(ctx.base_config, acc, stderr),
        (true, false) => Some(attest_files(cli, ctx, acc, stderr)),
        (false, true) => {
            acc.handle(process_stdin(ctx.base_config), "error", stderr);
            None
        }
        (false, false) => {
            analyze_file_list(cli, ctx, None, acc, stderr);
            None
        }
    }
}

/// Dispatch output based on mode: attestation JSON, capabilities JSON, or nothing.
fn dispatch_output(
    cli: &Cli,
    source_hash: Option<Box<str>>,
    findings: Vec<CapabilityFinding>,
    analysis_tier: AnalysisTier,
    stdout: &mut impl Write,
    stderr: &mut impl Write,
) -> Result<(), ExitCode> {
    match (cli.attestation, cli.capabilities) {
        (true, _) => {
            let Some(hash) = source_hash else {
                return Err(ExitCode::from(2));
            };
            let Some(crate_name) = cli.crate_name.as_deref() else {
                report_error(
                    stderr,
                    format_args!("error: --crate-name required for attestation"),
                );
                return Err(ExitCode::from(2));
            };
            let Some(crate_version) = cli.crate_version.as_deref() else {
                report_error(
                    stderr,
                    format_args!("error: --crate-version required for attestation"),
                );
                return Err(ExitCode::from(2));
            };
            write_attestation(
                stdout,
                stderr,
                findings,
                hash,
                Box::from(crate_name),
                Box::from(crate_version),
                analysis_tier,
            )
        }
        (false, true) => write_capabilities(stdout, stderr, findings),
        (false, false) => Ok(()),
    }
}

/// Compute the process exit code from error state, violations, and gate verdicts.
fn compute_exit_code(
    had_error: bool,
    violations_empty: bool,
    gate_verdicts: &[pedant_core::gate::GateVerdict],
) -> ExitCode {
    let has_deny = gate_verdicts
        .iter()
        .any(|v| v.severity == GateSeverity::Deny);

    match (had_error, violations_empty, has_deny) {
        (true, _, _) => ExitCode::from(2),
        (_, false, _) | (_, _, true) => ExitCode::from(1),
        (false, true, false) => ExitCode::from(0),
    }
}

fn attest_stdin(
    config: &CheckConfig,
    acc: &mut AnalysisAccumulator,
    stderr: &mut impl Write,
) -> Option<Box<str>> {
    let source = match read_stdin_source() {
        Ok(s) => s,
        Err(e) => {
            report_error(stderr, format_args!("error: {e}"));
            acc.had_error = true;
            return None;
        }
    };
    acc.handle(
        analyze("<stdin>", &source, config, None).map_err(ProcessError::from),
        "error",
        stderr,
    );
    let mut sources = BTreeMap::new();
    sources.insert(Box::<str>::from("<stdin>"), source);
    Some(compute_source_hash(&sources))
}

fn attest_files(
    cli: &Cli,
    ctx: &AnalysisContext<'_>,
    acc: &mut AnalysisAccumulator,
    stderr: &mut impl Write,
) -> Box<str> {
    let mut sources = BTreeMap::new();
    analyze_file_list(cli, ctx, Some(&mut sources), acc, stderr);
    compute_source_hash(&sources)
}

fn analyze_file_list(
    cli: &Cli,
    ctx: &AnalysisContext<'_>,
    mut sources: Option<&mut BTreeMap<Box<str>, String>>,
    acc: &mut AnalysisAccumulator,
    stderr: &mut impl Write,
) {
    let mut seen_build_roots: BTreeSet<Box<Path>> = BTreeSet::new();
    for file_path in &cli.files {
        let Some(cfg) = ctx.base_config.resolve_for_path(file_path, ctx.file_config) else {
            continue;
        };
        analyze_single_file(
            file_path,
            analyze,
            &cfg,
            ctx.semantic,
            sources.as_deref_mut(),
            acc,
            stderr,
        );
        discover_and_analyze_build_script(
            file_path,
            &cfg,
            sources.as_deref_mut(),
            &mut seen_build_roots,
            acc,
            stderr,
        );
    }
}

/// Find the crate root by walking up from a file path to locate `Cargo.toml`.
fn find_crate_root(file_path: &str) -> Option<&Path> {
    let mut dir = Path::new(file_path).parent()?;
    loop {
        match dir.join("Cargo.toml").is_file() {
            true => return Some(dir),
            false => dir = dir.parent()?,
        }
    }
}

#[cfg(feature = "semantic")]
/// Find the workspace root by walking up from the first file argument.
///
/// Looks for a `Cargo.toml` containing `[workspace]`, or falls back to the
/// nearest `Cargo.toml` with `[package]`.
fn find_workspace_root(files: &[String]) -> Option<Box<Path>> {
    let first = files.first()?;
    let mut dir = Path::new(first.as_str()).parent()?;
    let mut fallback: Option<&Path> = None;
    loop {
        // Some(true) = workspace, Some(false) = package, None = absent
        match (is_cargo_workspace(dir), fallback) {
            (Some(true), _) => return Some(Box::from(dir)),
            (Some(false), None) => fallback = Some(dir),
            (Some(false), Some(_)) | (None, _) => {}
        }
        match dir.parent() {
            Some(parent) => dir = parent,
            None => return fallback.map(Box::from),
        }
    }
}

#[cfg(feature = "semantic")]
/// Check whether a directory contains a Cargo workspace, package, or neither.
///
/// Returns `Some(true)` for `[workspace]`, `Some(false)` for `[package]`-only,
/// `None` if no readable `Cargo.toml`.
fn is_cargo_workspace(dir: &Path) -> Option<bool> {
    use io::BufRead;
    let file = fs::File::open(dir.join("Cargo.toml")).ok()?;
    let reader = io::BufReader::new(file);
    for line in reader.lines() {
        let line = line.ok()?;
        if line.trim_start().starts_with("[workspace]") {
            return Some(true);
        }
    }
    Some(false)
}

/// Load `SemanticContext` when `--semantic` is requested.
///
/// Returns `None` (with a stderr warning) if loading fails or the flag is absent.
#[cfg(feature = "semantic")]
fn load_semantic_if_requested(cli: &Cli, stderr: &mut impl Write) -> Option<SemanticContext> {
    if !cli.semantic {
        return None;
    }

    let Some(root) = find_workspace_root(&cli.files) else {
        report_error(
            stderr,
            format_args!(
                "warning: --semantic: no Cargo.toml found, falling back to syntactic analysis"
            ),
        );
        return None;
    };

    let start = Instant::now();
    let ctx = SemanticContext::load(&root);
    let elapsed = start.elapsed();

    match ctx {
        Some(c) => {
            report_error(
                stderr,
                format_args!(
                    "semantic: loaded workspace in {:.1}s",
                    elapsed.as_secs_f64()
                ),
            );
            Some(c)
        }
        None => {
            report_error(
                stderr,
                format_args!(
                    "warning: --semantic: failed to load workspace at {}, falling back to syntactic analysis",
                    root.display()
                ),
            );
            None
        }
    }
}

/// Stub when the `semantic` feature is disabled — always returns `None`.
#[cfg(not(feature = "semantic"))]
fn load_semantic_if_requested(_cli: &Cli, _stderr: &mut impl Write) -> Option<SemanticContext> {
    None
}

fn discover_and_analyze_build_script(
    file_path: &str,
    config: &CheckConfig,
    sources: Option<&mut BTreeMap<Box<str>, String>>,
    seen_roots: &mut BTreeSet<Box<Path>>,
    acc: &mut AnalysisAccumulator,
    stderr: &mut impl Write,
) {
    let Some(crate_root) = find_crate_root(file_path) else {
        return;
    };
    if seen_roots.contains(crate_root) {
        return;
    }
    seen_roots.insert(Box::from(crate_root));
    let build_path = match discover_build_script(crate_root) {
        Ok(Some(path)) => path,
        Ok(None) => return,
        Err(e) => {
            report_error(stderr, format_args!("build script discovery: {e}"));
            return;
        }
    };
    let Some(build_path_str) = build_path.to_str() else {
        report_error(
            stderr,
            format_args!(
                "build script path is not valid UTF-8: {}",
                build_path.display()
            ),
        );
        return;
    };
    analyze_single_file(
        build_path_str,
        analyze_build_script,
        config,
        None,
        sources,
        acc,
        stderr,
    );
}

fn analyze_single_file(
    file_path: &str,
    analyze_fn: fn(
        &str,
        &str,
        &CheckConfig,
        Option<&SemanticContext>,
    ) -> Result<AnalysisResult, pedant_core::ParseError>,
    config: &CheckConfig,
    semantic: Option<&SemanticContext>,
    sources: Option<&mut BTreeMap<Box<str>, String>>,
    acc: &mut AnalysisAccumulator,
    stderr: &mut impl Write,
) {
    let source = match fs::read_to_string(file_path) {
        Ok(s) => s,
        Err(e) => {
            report_error(stderr, format_args!("{file_path}: {e}"));
            acc.had_error = true;
            return;
        }
    };
    acc.handle(
        analyze_fn(file_path, &source, config, semantic).map_err(ProcessError::from),
        file_path,
        stderr,
    );
    if let Some(sources) = sources {
        sources.insert(Box::from(file_path), source);
    }
}

fn load_file_config(cli: &Cli, stderr: &mut impl Write) -> Result<Option<ConfigFile>, ExitCode> {
    let explicit = cli.config.is_some();
    let config_path = cli
        .config
        .as_deref()
        .map(std::path::PathBuf::from)
        .or_else(find_config_file);

    let Some(config_path) = config_path else {
        return Ok(None);
    };

    match (load_config_file(&config_path), explicit) {
        (Ok(cfg), _) => Ok(Some(cfg)),
        (Err(e), true) => {
            report_error(stderr, format_args!("error: {e}"));
            Err(ExitCode::from(2))
        }
        (Err(e), false) => {
            report_error(stderr, format_args!("warning: {e}"));
            Ok(None)
        }
    }
}

fn read_stdin_source() -> Result<String, ProcessError> {
    let mut source = String::new();
    io::stdin()
        .read_to_string(&mut source)
        .map_err(ProcessError::StdinRead)?;
    Ok(source)
}

fn process_stdin(config: &CheckConfig) -> Result<AnalysisResult, ProcessError> {
    let source = read_stdin_source()?;
    Ok(analyze("<stdin>", &source, config, None)?)
}

const SPEC_VERSION: &str = "0.1.0";

/// Returns seconds since Unix epoch. Falls back to 0 if the system clock
/// is before 1970, which cannot happen on any supported platform.
fn current_timestamp() -> u64 {
    SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

fn write_json(
    stdout: &mut impl Write,
    stderr: &mut impl Write,
    payload: &impl serde::Serialize,
    context: &str,
) -> Result<(), ExitCode> {
    if let Err(e) = serde_json::to_writer_pretty(&mut *stdout, payload) {
        report_error(stderr, format_args!("error writing {context}: {e}"));
        return Err(ExitCode::from(2));
    }
    if let Err(e) = writeln!(stdout) {
        report_error(
            stderr,
            format_args!("error writing trailing newline for {context}: {e}"),
        );
        return Err(ExitCode::from(2));
    }
    Ok(())
}

fn write_attestation(
    stdout: &mut impl Write,
    stderr: &mut impl Write,
    findings: Vec<CapabilityFinding>,
    source_hash: Box<str>,
    crate_name: Box<str>,
    crate_version: Box<str>,
    analysis_tier: AnalysisTier,
) -> Result<(), ExitCode> {
    let attestation = AttestationContent {
        spec_version: Box::from(SPEC_VERSION),
        source_hash,
        crate_name,
        crate_version,
        analysis_tier,
        timestamp: current_timestamp(),
        profile: CapabilityProfile {
            findings: findings.into_boxed_slice(),
        },
    };
    write_json(stdout, stderr, &attestation, "attestation")
}

fn write_capabilities(
    stdout: &mut impl Write,
    stderr: &mut impl Write,
    findings: Vec<CapabilityFinding>,
) -> Result<(), ExitCode> {
    let profile = CapabilityProfile {
        findings: findings.into_boxed_slice(),
    };
    write_json(stdout, stderr, &profile, "capabilities")
}

fn run_print_checks_list(stderr: &mut impl Write) -> ExitCode {
    match print_checks_list() {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            report_error(stderr, format_args!("error writing output: {e}"));
            ExitCode::from(2)
        }
    }
}

fn print_checks_list() -> io::Result<()> {
    let mut stdout = io::stdout().lock();
    writeln!(stdout, "Available checks:\n")?;
    writeln!(stdout, "{:<20} {:<8} DESCRIPTION", "CODE", "LLM?")?;
    writeln!(stdout, "{:-<20} {:-<8} {:-<30}", "", "", "")?;

    for check in ALL_CHECKS {
        let llm_marker = match check.llm_specific {
            true => "yes",
            false => "",
        };
        writeln!(
            stdout,
            "{:<20} {:<8} {}",
            check.code, llm_marker, check.description
        )?;
    }

    writeln!(stdout)?;
    writeln!(stdout, "Use --explain <CODE> for detailed rationale.")
}

fn print_explain(code: &str, stderr: &mut impl Write) -> ExitCode {
    let Some(rationale) = lookup_rationale(code) else {
        report_error(stderr, format_args!("Unknown check: {code}"));
        report_error(
            stderr,
            format_args!("Use --list-checks to see available checks."),
        );
        return ExitCode::from(1);
    };

    let result = write_explain(code, &rationale);
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            report_error(stderr, format_args!("error writing output: {e}"));
            ExitCode::from(2)
        }
    }
}

fn load_profile(path: &str) -> Result<CapabilityProfile, ProcessError> {
    let raw_json = fs::read_to_string(path).map_err(|e| ProcessError::DiffRead {
        path: path.into(),
        source: e,
    })?;

    // Try as attestation (has spec_version); fall back to bare profile.
    serde_json::from_str::<AttestationContent>(&raw_json)
        .map(|att| att.profile)
        .or_else(|_| serde_json::from_str(&raw_json))
        .map_err(|e| ProcessError::DiffParse {
            path: path.into(),
            source: e,
        })
}

fn load_diff_profiles(
    old_path: &str,
    new_path: &str,
    stderr: &mut impl Write,
) -> Option<(CapabilityProfile, CapabilityProfile)> {
    let old = load_profile(old_path)
        .map_err(|e| report_error(stderr, format_args!("{e}")))
        .ok()?;
    let new = load_profile(new_path)
        .map_err(|e| report_error(stderr, format_args!("{e}")))
        .ok()?;
    Some((old, new))
}

fn run_diff(old_path: &str, new_path: &str, stderr: &mut impl Write) -> ExitCode {
    let Some((old, new)) = load_diff_profiles(old_path, new_path, stderr) else {
        return ExitCode::from(2);
    };

    let diff = CapabilityDiff::compute(&old, &new);
    let mut stdout = io::stdout().lock();

    if let Err(exit) = write_json(&mut stdout, stderr, &diff, "diff") {
        return exit;
    }

    match diff.is_empty() {
        true => ExitCode::from(0),
        false => ExitCode::from(1),
    }
}

fn write_explain(code: &str, rationale: &pedant_core::violation::CheckRationale) -> io::Result<()> {
    let mut stdout = io::stdout().lock();
    writeln!(stdout, "Check: {code}\n")?;
    writeln!(stdout, "{rationale}")
}