Skip to main content

rust_analyzer/
flycheck.rs

1//! Flycheck provides the functionality needed to run `cargo check` to provide
2//! LSP diagnostics based on the output of the command.
3
4use std::{
5    fmt, io,
6    process::Command,
7    sync::atomic::{AtomicUsize, Ordering},
8    time::Duration,
9};
10
11use cargo_metadata::PackageId;
12use crossbeam_channel::{Receiver, Sender, select_biased, unbounded};
13use ide_db::FxHashSet;
14use itertools::Itertools;
15use paths::{AbsPath, AbsPathBuf, Utf8Path, Utf8PathBuf};
16use project_model::TargetDirectoryConfig;
17use project_model::project_json;
18use rustc_hash::FxHashMap;
19use serde::Deserialize as _;
20use serde_derive::Deserialize;
21
22pub(crate) use cargo_metadata::diagnostic::{
23    Applicability, Diagnostic, DiagnosticCode, DiagnosticLevel, DiagnosticSpan,
24};
25use toolchain::Tool;
26use triomphe::Arc;
27
28use crate::{
29    command::{CommandHandle, JsonLinesParser},
30    diagnostics::DiagnosticsGeneration,
31};
32
33#[derive(Clone, Debug, Default, PartialEq, Eq)]
34pub(crate) enum InvocationStrategy {
35    Once,
36    #[default]
37    PerWorkspace,
38}
39
40/// Data needed to construct a `cargo` command invocation, e.g. for flycheck or running a test.
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub(crate) struct CargoOptions {
43    /// The cargo subcommand to run, e.g. "check" or "clippy"
44    pub(crate) subcommand: String,
45    pub(crate) target_tuples: Vec<String>,
46    pub(crate) all_targets: bool,
47    pub(crate) set_test: bool,
48    pub(crate) no_default_features: bool,
49    pub(crate) all_features: bool,
50    pub(crate) features: Vec<String>,
51    pub(crate) extra_args: Vec<String>,
52    pub(crate) extra_test_bin_args: Vec<String>,
53    pub(crate) extra_env: FxHashMap<String, Option<String>>,
54    pub(crate) config_path: Option<AbsPathBuf>,
55    pub(crate) target_dir_config: TargetDirectoryConfig,
56}
57
58#[derive(Clone, Debug)]
59pub(crate) enum Target {
60    Bin(String),
61    Example(String),
62    Benchmark(String),
63    Test(String),
64}
65
66impl CargoOptions {
67    pub(crate) fn apply_on_command(
68        &self,
69        cmd: &mut Command,
70        ws_target_dir: Option<&Utf8Path>,
71        package_repr: Option<&str>,
72        toolchain_version: Option<&semver::Version>,
73    ) {
74        toolchain::cargo_use_targets(toolchain_version, cmd, &self.target_tuples);
75        if self.all_targets {
76            if self.set_test {
77                cmd.arg("--all-targets");
78            } else {
79                // No --benches unfortunately, as this implies --tests (see https://github.com/rust-lang/cargo/issues/6454),
80                // and users setting `cfg.seTest = false` probably prefer disabling benches than enabling tests.
81                cmd.args(["--lib", "--bins", "--examples"]);
82            }
83        }
84        if self.all_features {
85            cmd.arg("--all-features");
86        } else {
87            if self.no_default_features {
88                cmd.arg("--no-default-features");
89            }
90            if !self.features.is_empty() {
91                // If we are scoped to a particular package, filter any features of the form
92                // `crate/feature` which target other packages.
93                let features = if let Some(name) = package_repr {
94                    let filtered = self
95                        .features
96                        .iter()
97                        .filter(|f| match f.split_once('/') {
98                            Some((c, _)) => c == name,
99                            None => true,
100                        })
101                        .map(|s| s.as_str())
102                        .collect::<Vec<_>>();
103                    filtered.join(" ")
104                } else {
105                    self.features.join(" ")
106                };
107                cmd.arg("--features");
108                cmd.arg(features);
109            }
110        }
111        if let Some(config_path) = &self.config_path {
112            cmd.arg("--config").arg(config_path);
113        }
114        if let Some(target_dir) = self.target_dir_config.target_dir(ws_target_dir) {
115            cmd.arg("--target-dir").arg(target_dir.as_ref());
116        }
117    }
118}
119
120/// The flycheck config from a rust-project.json file or discoverConfig JSON output.
121#[derive(Debug, Default)]
122pub(crate) struct FlycheckConfigJson {
123    /// The template with [project_json::RunnableKind::Flycheck]
124    pub single_template: Option<project_json::Runnable>,
125}
126
127impl FlycheckConfigJson {
128    pub(crate) fn any_configured(&self) -> bool {
129        // self.workspace_template.is_some() ||
130        self.single_template.is_some()
131    }
132}
133
134/// The flycheck config from rust-analyzer's own configuration.
135///
136/// We rely on this when rust-project.json does not specify a flycheck runnable
137///
138#[derive(Clone, Debug, PartialEq, Eq)]
139pub(crate) enum FlycheckConfig {
140    /// Automatically use rust-project.json's flycheck runnable or just use cargo (the common case)
141    ///
142    /// We can't have a variant for ProjectJson because that is configured on the fly during
143    /// discoverConfig. We only know what we can read at config time.
144    Automatic {
145        /// If we do use cargo, how to build the check command
146        cargo_options: CargoOptions,
147        ansi_color_output: bool,
148    },
149    /// check_overrideCommand. This overrides both cargo and rust-project.json's flycheck runnable.
150    CustomCommand {
151        command: String,
152        args: Vec<String>,
153        extra_env: FxHashMap<String, Option<String>>,
154        invocation_strategy: InvocationStrategy,
155    },
156}
157
158impl FlycheckConfig {
159    pub(crate) fn invocation_strategy(&self) -> InvocationStrategy {
160        match self {
161            FlycheckConfig::Automatic { .. } => InvocationStrategy::PerWorkspace,
162            FlycheckConfig::CustomCommand { invocation_strategy, .. } => {
163                invocation_strategy.clone()
164            }
165        }
166    }
167}
168
169impl fmt::Display for FlycheckConfig {
170    /// Show a shortened version of the check command.
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        match self {
173            FlycheckConfig::Automatic { cargo_options, .. } => {
174                write!(f, "cargo {}", cargo_options.subcommand)
175            }
176            FlycheckConfig::CustomCommand { command, args, .. } => {
177                // Don't show `my_custom_check --foo $saved_file` literally to the user, as it
178                // looks like we've forgotten to substitute $saved_file.
179                //
180                // `my_custom_check --foo /home/user/project/src/dir/foo.rs` is too verbose.
181                //
182                // Instead, show `my_custom_check --foo ...`. The
183                // actual path is often too long to be worth showing
184                // in the IDE (e.g. in the VS Code status bar).
185                let display_args = args
186                    .iter()
187                    .map(|arg| {
188                        if (arg == SAVED_FILE_PLACEHOLDER_DOLLAR)
189                            || (arg == SAVED_FILE_INLINE)
190                            || arg.ends_with(".rs")
191                        {
192                            "..."
193                        } else {
194                            arg
195                        }
196                    })
197                    .collect::<Vec<_>>();
198
199                write!(f, "{command} {}", display_args.join(" "))
200            }
201        }
202    }
203}
204
205/// Flycheck wraps the shared state and communication machinery used for
206/// running `cargo check` (or other compatible command) and providing
207/// diagnostics based on the output.
208/// The spawned thread is shut down when this struct is dropped.
209#[derive(Debug)]
210pub(crate) struct FlycheckHandle {
211    // XXX: drop order is significant
212    sender: Sender<StateChange>,
213    _thread: stdx::thread::JoinHandle,
214    id: usize,
215    generation: Arc<AtomicUsize>,
216}
217
218impl FlycheckHandle {
219    pub(crate) fn spawn(
220        id: usize,
221        generation: Arc<AtomicUsize>,
222        sender: Sender<FlycheckMessage>,
223        config: FlycheckConfig,
224        config_json: FlycheckConfigJson,
225        sysroot_root: Option<AbsPathBuf>,
226        workspace_root: AbsPathBuf,
227        manifest_path: Option<AbsPathBuf>,
228        ws_target_dir: Option<Utf8PathBuf>,
229        ws_build_dir: Option<Utf8PathBuf>,
230        toolchain_version: Option<semver::Version>,
231    ) -> FlycheckHandle {
232        let actor = FlycheckActor::new(
233            id,
234            generation.load(Ordering::Relaxed),
235            sender,
236            config,
237            config_json,
238            sysroot_root,
239            workspace_root,
240            manifest_path,
241            ws_target_dir,
242            ws_build_dir,
243            toolchain_version,
244        );
245        let (sender, receiver) = unbounded::<StateChange>();
246        let thread =
247            stdx::thread::Builder::new(stdx::thread::ThreadIntent::Worker, format!("Flycheck{id}"))
248                .spawn(move || actor.run(receiver))
249                .expect("failed to spawn thread");
250        FlycheckHandle { id, generation, sender, _thread: thread }
251    }
252
253    /// Schedule a re-start of the cargo check worker to do a workspace wide check.
254    pub(crate) fn restart_workspace(&self, saved_file: Option<AbsPathBuf>) {
255        let generation = self.generation.fetch_add(1, Ordering::Relaxed) + 1;
256        self.sender
257            .send(StateChange::Restart {
258                generation,
259                scope: FlycheckScope::Workspace,
260                saved_file,
261                target: None,
262            })
263            .unwrap();
264    }
265
266    /// Schedule a re-start of the cargo check worker to do a package wide check.
267    pub(crate) fn restart_for_package(
268        &self,
269        package: PackageSpecifier,
270        target: Option<Target>,
271        workspace_deps: Option<FxHashSet<PackageSpecifier>>,
272        saved_file: Option<AbsPathBuf>,
273    ) {
274        let generation = self.generation.fetch_add(1, Ordering::Relaxed) + 1;
275        self.sender
276            .send(StateChange::Restart {
277                generation,
278                scope: FlycheckScope::Package { package, workspace_deps },
279                saved_file,
280                target,
281            })
282            .unwrap();
283    }
284
285    /// Stop this cargo check worker.
286    pub(crate) fn cancel(&self) {
287        self.sender.send(StateChange::Cancel).unwrap();
288    }
289
290    pub(crate) fn id(&self) -> usize {
291        self.id
292    }
293
294    pub(crate) fn generation(&self) -> DiagnosticsGeneration {
295        self.generation.load(Ordering::Relaxed)
296    }
297}
298
299#[derive(Debug)]
300pub(crate) enum ClearDiagnosticsKind {
301    All(ClearScope),
302    OlderThan(DiagnosticsGeneration, ClearScope),
303}
304
305#[derive(Debug)]
306pub(crate) enum ClearScope {
307    Workspace,
308    Package(PackageSpecifier),
309}
310
311pub(crate) enum FlycheckMessage {
312    /// Request adding a diagnostic with fixes included to a file
313    AddDiagnostic {
314        id: usize,
315        generation: DiagnosticsGeneration,
316        workspace_root: Arc<AbsPathBuf>,
317        diagnostic: Diagnostic,
318        package_id: Option<PackageSpecifier>,
319    },
320
321    /// Request clearing all outdated diagnostics.
322    ClearDiagnostics { id: usize, kind: ClearDiagnosticsKind },
323
324    /// Request check progress notification to client
325    Progress {
326        /// Flycheck instance ID
327        id: usize,
328        progress: Progress,
329    },
330}
331
332impl fmt::Debug for FlycheckMessage {
333    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334        match self {
335            FlycheckMessage::AddDiagnostic {
336                id,
337                generation,
338                workspace_root,
339                diagnostic,
340                package_id,
341            } => f
342                .debug_struct("AddDiagnostic")
343                .field("id", id)
344                .field("generation", generation)
345                .field("workspace_root", workspace_root)
346                .field("package_id", package_id)
347                .field("diagnostic_code", &diagnostic.code.as_ref().map(|it| &it.code))
348                .finish(),
349            FlycheckMessage::ClearDiagnostics { id, kind } => {
350                f.debug_struct("ClearDiagnostics").field("id", id).field("kind", kind).finish()
351            }
352            FlycheckMessage::Progress { id, progress } => {
353                f.debug_struct("Progress").field("id", id).field("progress", progress).finish()
354            }
355        }
356    }
357}
358
359#[derive(Debug)]
360pub(crate) enum Progress {
361    DidStart {
362        /// The user sees this in VSCode, etc. May be a shortened version of the command we actually
363        /// executed, otherwise it is way too long.
364        user_facing_command: String,
365    },
366    DidCheckCrate(String),
367    DidFinish(io::Result<()>),
368    DidCancel,
369    DidFailToRestart(String),
370}
371
372#[derive(Debug, Clone)]
373enum FlycheckScope {
374    Workspace,
375    Package {
376        // Either a cargo package or a $label in rust-project.check.overrideCommand
377        package: PackageSpecifier,
378        workspace_deps: Option<FxHashSet<PackageSpecifier>>,
379    },
380}
381
382#[derive(Debug, Hash, PartialEq, Eq, Clone)]
383pub(crate) enum PackageSpecifier {
384    Cargo {
385        /// The one in Cargo.toml, assumed to work with `cargo check -p {}` etc
386        package_id: Arc<PackageId>,
387    },
388    BuildInfo {
389        /// If a `build` field is present in rust-project.json, its label field
390        label: String,
391    },
392}
393
394impl PackageSpecifier {
395    pub(crate) fn as_str(&self) -> &str {
396        match self {
397            Self::Cargo { package_id } => &package_id.repr,
398            Self::BuildInfo { label } => label,
399        }
400    }
401}
402
403#[derive(Debug)]
404enum FlycheckCommandOrigin {
405    /// Regular cargo invocation
406    Cargo,
407    /// Configured via check_overrideCommand
408    CheckOverrideCommand,
409    /// From a runnable with [project_json::RunnableKind::Flycheck]
410    ProjectJsonRunnable,
411}
412
413#[derive(Debug)]
414enum StateChange {
415    Restart {
416        generation: DiagnosticsGeneration,
417        scope: FlycheckScope,
418        saved_file: Option<AbsPathBuf>,
419        target: Option<Target>,
420    },
421    Cancel,
422}
423
424/// A [`FlycheckActor`] is a single check instance of a workspace.
425struct FlycheckActor {
426    /// The workspace id of this flycheck instance.
427    id: usize,
428
429    generation: DiagnosticsGeneration,
430    sender: Sender<FlycheckMessage>,
431    config: FlycheckConfig,
432    config_json: FlycheckConfigJson,
433
434    manifest_path: Option<AbsPathBuf>,
435    ws_target_dir: Option<Utf8PathBuf>,
436    ws_build_dir: Option<Utf8PathBuf>,
437    /// Either the workspace root of the workspace we are flychecking,
438    /// or the project root of the project.
439    root: Arc<AbsPathBuf>,
440    sysroot_root: Option<AbsPathBuf>,
441    scope: FlycheckScope,
442    /// CargoHandle exists to wrap around the communication needed to be able to
443    /// run `cargo check` without blocking. Currently the Rust standard library
444    /// doesn't provide a way to read sub-process output without blocking, so we
445    /// have to wrap sub-processes output handling in a thread and pass messages
446    /// back over a channel.
447    command_handle: Option<CommandHandle<CheckMessage>>,
448    /// The receiver side of the channel mentioned above.
449    command_receiver: Option<Receiver<CheckMessage>>,
450    diagnostics_cleared_for: FxHashSet<PackageSpecifier>,
451    diagnostics_received: DiagnosticsReceived,
452    toolchain_version: Option<semver::Version>,
453}
454
455#[derive(PartialEq, Debug)]
456enum DiagnosticsReceived {
457    /// We started a flycheck, but we haven't seen any diagnostics yet.
458    NotYet,
459    /// We received a non-zero number of diagnostics from rustc or clippy (via
460    /// cargo or custom check command). This means there were errors or
461    /// warnings.
462    AtLeastOne,
463    /// We received a non-zero number of diagnostics, and the scope is
464    /// workspace, so we've discarded the previous workspace diagnostics.
465    AtLeastOneAndClearedWorkspace,
466}
467
468#[allow(clippy::large_enum_variant)]
469#[derive(Debug)]
470enum Event {
471    RequestStateChange(StateChange),
472    CheckEvent(Option<CheckMessage>),
473}
474
475/// This is stable behaviour. Don't change.
476const SAVED_FILE_PLACEHOLDER_DOLLAR: &str = "$saved_file";
477const LABEL_INLINE: &str = "{label}";
478const SAVED_FILE_INLINE: &str = "{saved_file}";
479
480#[derive(Debug)]
481struct Substitutions<'a> {
482    label: Option<&'a str>,
483    saved_file: Option<&'a str>,
484}
485
486impl<'a> Substitutions<'a> {
487    /// If you have a runnable, and it has {label} in it somewhere, treat it as a template that
488    /// may be unsatisfied if you do not provide a label to substitute into it. Returns None in
489    /// that situation. Otherwise performs the requested substitutions.
490    ///
491    /// Same for {saved_file}.
492    ///
493    #[expect(clippy::disallowed_types, reason = "generic parameter allows for `FxHashMap`")]
494    fn substitute<H>(
495        self,
496        template: &project_json::Runnable,
497        extra_env: &std::collections::HashMap<String, Option<String>, H>,
498    ) -> Option<Command> {
499        let mut cmd = toolchain::command(&template.program, &template.cwd, extra_env);
500        for arg in &template.args {
501            if let Some(ix) = arg.find(LABEL_INLINE) {
502                let label = self.label?;
503                let mut arg = arg.to_string();
504                arg.replace_range(ix..ix + LABEL_INLINE.len(), label);
505                cmd.arg(arg);
506                continue;
507            }
508            if let Some(ix) = arg.find(SAVED_FILE_INLINE) {
509                let saved_file = self.saved_file?;
510                let mut arg = arg.to_string();
511                arg.replace_range(ix..ix + SAVED_FILE_INLINE.len(), saved_file);
512                cmd.arg(arg);
513                continue;
514            }
515            // Legacy syntax: full argument match
516            if arg == SAVED_FILE_PLACEHOLDER_DOLLAR {
517                let saved_file = self.saved_file?;
518                cmd.arg(saved_file);
519                continue;
520            }
521            cmd.arg(arg);
522        }
523        cmd.current_dir(&template.cwd);
524        Some(cmd)
525    }
526}
527
528impl FlycheckActor {
529    fn new(
530        id: usize,
531        generation: DiagnosticsGeneration,
532        sender: Sender<FlycheckMessage>,
533        config: FlycheckConfig,
534        config_json: FlycheckConfigJson,
535        sysroot_root: Option<AbsPathBuf>,
536        workspace_root: AbsPathBuf,
537        manifest_path: Option<AbsPathBuf>,
538        ws_target_dir: Option<Utf8PathBuf>,
539        ws_build_dir: Option<Utf8PathBuf>,
540        toolchain_version: Option<semver::Version>,
541    ) -> FlycheckActor {
542        tracing::info!(%id, ?workspace_root, "Spawning flycheck");
543        FlycheckActor {
544            id,
545            generation,
546            sender,
547            config,
548            config_json,
549            sysroot_root,
550            root: Arc::new(workspace_root),
551            scope: FlycheckScope::Workspace,
552            manifest_path,
553            ws_target_dir,
554            ws_build_dir,
555            command_handle: None,
556            command_receiver: None,
557            diagnostics_cleared_for: Default::default(),
558            diagnostics_received: DiagnosticsReceived::NotYet,
559            toolchain_version,
560        }
561    }
562
563    fn report_progress(&self, progress: Progress) {
564        self.send(FlycheckMessage::Progress { id: self.id, progress });
565    }
566
567    fn next_event(&self, inbox: &Receiver<StateChange>) -> Option<Event> {
568        let Some(command_receiver) = &self.command_receiver else {
569            return inbox.recv().ok().map(Event::RequestStateChange);
570        };
571
572        // Biased to give restarts a preference so check outputs don't block a restart or stop
573        select_biased! {
574            recv(inbox) -> msg => msg.ok().map(Event::RequestStateChange),
575            recv(command_receiver) -> msg => Some(Event::CheckEvent(msg.ok())),
576        }
577    }
578
579    fn run(mut self, inbox: Receiver<StateChange>) {
580        'event: while let Some(event) = self.next_event(&inbox) {
581            match event {
582                Event::RequestStateChange(StateChange::Cancel) => {
583                    tracing::debug!(flycheck_id = self.id, "flycheck cancelled");
584                    self.cancel_check_process();
585                }
586                Event::RequestStateChange(StateChange::Restart {
587                    mut generation,
588                    mut scope,
589                    mut saved_file,
590                    mut target,
591                }) => {
592                    // Cancel the previously spawned process
593                    self.cancel_check_process();
594
595                    // Debounce by briefly waiting for other state changes.
596                    while let Ok(restart) = inbox.recv_timeout(Duration::from_millis(50)) {
597                        match restart {
598                            StateChange::Cancel => {
599                                // We got a cancel straight after this restart request, so
600                                // don't do anything.
601                                continue 'event;
602                            }
603                            StateChange::Restart {
604                                generation: g,
605                                scope: s,
606                                saved_file: sf,
607                                target: t,
608                            } => {
609                                // We got another restart request. Take the parameters
610                                // from the last restart request in this time window,
611                                // because the most recent request is probably the most
612                                // relevant to the user.
613                                generation = g;
614                                scope = s;
615                                saved_file = sf;
616                                target = t;
617                            }
618                        }
619                    }
620
621                    let command = self.check_command(&scope, saved_file.as_deref(), target);
622                    self.scope = scope.clone();
623                    self.generation = generation;
624
625                    let Some((command, origin)) = command else {
626                        tracing::debug!(?scope, "failed to build flycheck command");
627                        continue;
628                    };
629
630                    let debug_command = format!("{command:?}");
631                    let user_facing_command = self.config.to_string();
632
633                    tracing::debug!(?origin, ?command, "will restart flycheck");
634                    let (sender, receiver) = unbounded();
635                    match CommandHandle::spawn(
636                        command,
637                        CheckParser,
638                        sender,
639                        match &self.config {
640                            FlycheckConfig::Automatic { cargo_options, .. } => {
641                                let target_dir = cargo_options
642                                    .target_dir_config
643                                    .target_dir(self.ws_target_dir.as_deref());
644
645                                let output_dir = target_dir
646                                    .as_deref()
647                                    .or(self.ws_build_dir.as_deref())
648                                    .or(self.ws_target_dir.as_deref());
649
650                                Some(
651                                    // As `CommandHandle::spawn`'s working directory is
652                                    // rust-analyzer's working directory, which might be different
653                                    // from the flycheck's working directory, we should canonicalize
654                                    // the output directory, otherwise we might write it into the
655                                    // wrong target dir.
656                                    // If `output_dir` is an absolute path, it will replace
657                                    // `self.root` and that's an intended behavior.
658                                    self.root
659                                        .join(output_dir.unwrap_or(
660                                            Utf8Path::new("target").join("rust-analyzer").as_path(),
661                                        ))
662                                        .join(format!("flycheck{}", self.id))
663                                        .into(),
664                                )
665                            }
666                            _ => None,
667                        },
668                    ) {
669                        Ok(command_handle) => {
670                            tracing::debug!(?origin, command = %debug_command, "did restart flycheck");
671                            self.command_handle = Some(command_handle);
672                            self.command_receiver = Some(receiver);
673                            self.report_progress(Progress::DidStart { user_facing_command });
674                        }
675                        Err(error) => {
676                            self.report_progress(Progress::DidFailToRestart(format!(
677                                "Failed to run the following command: {debug_command} origin={origin:?} error={error}"
678                            )));
679                        }
680                    }
681                }
682                Event::CheckEvent(None) => {
683                    tracing::debug!(flycheck_id = self.id, "flycheck finished");
684
685                    // Watcher finished
686                    let command_handle = self.command_handle.take().unwrap();
687                    self.command_receiver.take();
688                    let formatted_handle = format!("{command_handle:?}");
689
690                    let res = command_handle.join();
691                    if let Err(error) = &res {
692                        tracing::error!(
693                            "Flycheck failed to run the following command: {}, error={}",
694                            formatted_handle,
695                            error
696                        );
697                    }
698                    if self.diagnostics_received == DiagnosticsReceived::NotYet {
699                        tracing::trace!(flycheck_id = self.id, "clearing diagnostics");
700                        // We finished without receiving any diagnostics.
701                        //
702                        // `cargo check` generally outputs something, even if there are no
703                        // warnings/errors, so we always know which package was checked.
704                        //
705                        // ```text
706                        // $ cargo check --message-format=json 2>/dev/null
707                        // {"reason":"compiler-artifact","package_id":"path+file:///Users/wilfred/tmp/scratch#0.1.0",...}
708                        // ```
709                        //
710                        // However, rustc only returns JSON if there are diagnostics present, so a
711                        // build without warnings or errors has an empty output.
712                        //
713                        // ```
714                        // $ rustc --error-format=json bad.rs
715                        // {"$message_type":"diagnostic","message":"mismatched types","...}
716                        //
717                        // $ rustc --error-format=json good.rs
718                        // ```
719                        //
720                        // So if we got zero diagnostics, it was almost certainly a check that
721                        // wasn't specific to a package.
722                        self.send(FlycheckMessage::ClearDiagnostics {
723                            id: self.id,
724                            kind: ClearDiagnosticsKind::All(ClearScope::Workspace),
725                        });
726                    } else if res.is_ok() {
727                        // We clear diagnostics for packages on
728                        // `[CargoCheckMessage::CompilerArtifact]` but there seem to be setups where
729                        // cargo may not report an artifact to our runner at all. To handle such
730                        // cases, clear stale diagnostics when flycheck completes successfully.
731                        match &self.scope {
732                            FlycheckScope::Workspace => {
733                                self.send(FlycheckMessage::ClearDiagnostics {
734                                    id: self.id,
735                                    kind: ClearDiagnosticsKind::OlderThan(
736                                        self.generation,
737                                        ClearScope::Workspace,
738                                    ),
739                                });
740                            }
741                            FlycheckScope::Package { package, workspace_deps } => {
742                                for pkg in
743                                    std::iter::once(package).chain(workspace_deps.iter().flatten())
744                                {
745                                    self.send(FlycheckMessage::ClearDiagnostics {
746                                        id: self.id,
747                                        kind: ClearDiagnosticsKind::OlderThan(
748                                            self.generation,
749                                            ClearScope::Package(pkg.clone()),
750                                        ),
751                                    });
752                                }
753                            }
754                        }
755                    }
756                    self.clear_diagnostics_state();
757
758                    self.report_progress(Progress::DidFinish(res));
759                }
760                Event::CheckEvent(Some(message)) => match message {
761                    CheckMessage::CompilerArtifact(msg) => {
762                        tracing::trace!(
763                            flycheck_id = self.id,
764                            artifact = msg.target.name,
765                            package_id = msg.package_id.repr,
766                            "artifact received"
767                        );
768                        self.report_progress(Progress::DidCheckCrate(format!(
769                            "{} ({})",
770                            msg.target.name,
771                            msg.target.kind.iter().format_with(", ", |kind, f| f(&kind)),
772                        )));
773                        let package_id = Arc::new(msg.package_id);
774                        if self
775                            .diagnostics_cleared_for
776                            .insert(PackageSpecifier::Cargo { package_id: package_id.clone() })
777                        {
778                            tracing::trace!(
779                                flycheck_id = self.id,
780                                package_id = package_id.repr,
781                                "clearing diagnostics"
782                            );
783                            self.send(FlycheckMessage::ClearDiagnostics {
784                                id: self.id,
785                                kind: ClearDiagnosticsKind::All(ClearScope::Package(
786                                    PackageSpecifier::Cargo { package_id },
787                                )),
788                            });
789                        }
790                    }
791                    CheckMessage::Diagnostic { diagnostic, package_id } => {
792                        tracing::trace!(
793                            flycheck_id = self.id,
794                            message = diagnostic.message,
795                            package_id = package_id.as_ref().map(|it| it.as_str()),
796                            "diagnostic received"
797                        );
798                        if self.diagnostics_received == DiagnosticsReceived::NotYet {
799                            self.diagnostics_received = DiagnosticsReceived::AtLeastOne;
800                        }
801                        if let Some(package_id) = &package_id {
802                            if self.diagnostics_cleared_for.insert(package_id.clone()) {
803                                tracing::trace!(
804                                    flycheck_id = self.id,
805                                    package_id = package_id.as_str(),
806                                    "clearing diagnostics"
807                                );
808                                self.send(FlycheckMessage::ClearDiagnostics {
809                                    id: self.id,
810                                    kind: ClearDiagnosticsKind::All(ClearScope::Package(
811                                        package_id.clone(),
812                                    )),
813                                });
814                            }
815                        } else if self.diagnostics_received
816                            != DiagnosticsReceived::AtLeastOneAndClearedWorkspace
817                        {
818                            self.diagnostics_received =
819                                DiagnosticsReceived::AtLeastOneAndClearedWorkspace;
820                            self.send(FlycheckMessage::ClearDiagnostics {
821                                id: self.id,
822                                kind: ClearDiagnosticsKind::All(ClearScope::Workspace),
823                            });
824                        }
825                        self.send(FlycheckMessage::AddDiagnostic {
826                            id: self.id,
827                            generation: self.generation,
828                            package_id,
829                            workspace_root: self.root.clone(),
830                            diagnostic,
831                        });
832                    }
833                },
834            }
835        }
836        // If we rerun the thread, we need to discard the previous check results first
837        self.cancel_check_process();
838    }
839
840    fn cancel_check_process(&mut self) {
841        if let Some(command_handle) = self.command_handle.take() {
842            tracing::debug!(
843                command = ?command_handle,
844                "did cancel flycheck"
845            );
846            command_handle.cancel();
847            self.command_receiver.take();
848            self.report_progress(Progress::DidCancel);
849        }
850        self.clear_diagnostics_state();
851    }
852
853    fn clear_diagnostics_state(&mut self) {
854        self.diagnostics_cleared_for.clear();
855        self.diagnostics_received = DiagnosticsReceived::NotYet;
856    }
857
858    fn explicit_check_command(
859        &self,
860        scope: &FlycheckScope,
861        saved_file: Option<&AbsPath>,
862    ) -> Option<Command> {
863        let label = match scope {
864            // We could add a runnable like "RunnableKind::FlycheckWorkspace". But generally
865            // if you're not running cargo, it's because your workspace is too big to check
866            // all at once. You can always use `check_overrideCommand` with no {label}.
867            FlycheckScope::Workspace => return None,
868            FlycheckScope::Package { package: PackageSpecifier::BuildInfo { label }, .. } => {
869                label.as_str()
870            }
871            FlycheckScope::Package {
872                package: PackageSpecifier::Cargo { package_id: label },
873                ..
874            } => &label.repr,
875        };
876        let template = self.config_json.single_template.as_ref()?;
877        let subs = Substitutions { label: Some(label), saved_file: saved_file.map(|x| x.as_str()) };
878        subs.substitute(template, &FxHashMap::default())
879    }
880
881    /// Construct a `Command` object for checking the user's code. If the user
882    /// has specified a custom command with placeholders that we cannot fill,
883    /// return None.
884    fn check_command(
885        &self,
886        scope: &FlycheckScope,
887        saved_file: Option<&AbsPath>,
888        target: Option<Target>,
889    ) -> Option<(Command, FlycheckCommandOrigin)> {
890        match &self.config {
891            FlycheckConfig::Automatic { cargo_options, ansi_color_output } => {
892                // Only use the rust-project.json's flycheck config when no check_overrideCommand
893                // is configured. In the FlycheckConcig::CustomCommand branch we will still do
894                // label substitution, but on the overrideCommand instead.
895                //
896                // There needs to be SOME way to override what your discoverConfig tool says,
897                // because to change the flycheck runnable there you may have to literally
898                // recompile the tool.
899                if self.config_json.any_configured() {
900                    // Completely handle according to rust-project.json.
901                    // We don't consider this to be "using cargo" so we will not apply any of the
902                    // CargoOptions to the command.
903                    let cmd = self.explicit_check_command(scope, saved_file)?;
904                    return Some((cmd, FlycheckCommandOrigin::ProjectJsonRunnable));
905                }
906
907                let mut cmd =
908                    toolchain::command(Tool::Cargo.path(), &*self.root, &cargo_options.extra_env);
909                if let Some(sysroot_root) = &self.sysroot_root
910                    && !cargo_options.extra_env.contains_key("RUSTUP_TOOLCHAIN")
911                    && std::env::var_os("RUSTUP_TOOLCHAIN").is_none()
912                {
913                    cmd.env("RUSTUP_TOOLCHAIN", AsRef::<std::path::Path>::as_ref(sysroot_root));
914                }
915                cmd.env("CARGO_LOG", "cargo::core::compiler::fingerprint=info");
916                cmd.arg(&cargo_options.subcommand);
917
918                let package_repr = match scope {
919                    FlycheckScope::Workspace => {
920                        cmd.arg("--workspace");
921                        None
922                    }
923                    FlycheckScope::Package {
924                        package: PackageSpecifier::Cargo { package_id },
925                        ..
926                    } => {
927                        cmd.arg("-p").arg(&package_id.repr);
928                        Some(package_id.repr.as_str())
929                    }
930                    FlycheckScope::Package {
931                        package: PackageSpecifier::BuildInfo { .. }, ..
932                    } => {
933                        // No way to flycheck this single package. All we have is a build label.
934                        // There's no way to really say whether this build label happens to be
935                        // a cargo canonical name, so we won't try.
936                        return None;
937                    }
938                };
939
940                if let Some(tgt) = target {
941                    match tgt {
942                        Target::Bin(tgt) => cmd.arg("--bin").arg(tgt),
943                        Target::Example(tgt) => cmd.arg("--example").arg(tgt),
944                        Target::Test(tgt) => cmd.arg("--test").arg(tgt),
945                        Target::Benchmark(tgt) => cmd.arg("--bench").arg(tgt),
946                    };
947                }
948
949                cmd.arg(if *ansi_color_output {
950                    "--message-format=json-diagnostic-rendered-ansi"
951                } else {
952                    "--message-format=json"
953                });
954
955                if let Some(manifest_path) = &self.manifest_path {
956                    cmd.arg("--manifest-path");
957                    cmd.arg(manifest_path);
958                    if manifest_path.extension() == Some("rs") {
959                        cmd.env("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS", "nightly");
960                        cmd.arg("-Zscript");
961                    }
962                }
963
964                cmd.arg("--keep-going");
965
966                cargo_options.apply_on_command(
967                    &mut cmd,
968                    self.ws_target_dir.as_ref().map(Utf8PathBuf::as_path),
969                    package_repr,
970                    self.toolchain_version.as_ref(),
971                );
972                cmd.args(&cargo_options.extra_args);
973                Some((cmd, FlycheckCommandOrigin::Cargo))
974            }
975            FlycheckConfig::CustomCommand { command, args, extra_env, invocation_strategy } => {
976                let root = match invocation_strategy {
977                    InvocationStrategy::Once => &*self.root,
978                    InvocationStrategy::PerWorkspace => {
979                        // FIXME: &affected_workspace
980                        &*self.root
981                    }
982                };
983                let runnable = project_json::Runnable {
984                    program: command.clone(),
985                    cwd: Utf8Path::to_owned(root.as_ref()),
986                    args: args.clone(),
987                    kind: project_json::RunnableKind::Flycheck,
988                };
989
990                let label = match scope {
991                    FlycheckScope::Workspace => None,
992                    // We support substituting both build labels (e.g. buck, bazel) and cargo package ids.
993                    // With cargo package ids, you get `cargo check -p path+file:///path/to/rust-analyzer/crates/hir#0.0.0`.
994                    // That does work!
995                    FlycheckScope::Package { package, .. } => Some(package.as_str()),
996                };
997
998                let subs = Substitutions { label, saved_file: saved_file.map(|x| x.as_str()) };
999                let cmd = subs.substitute(&runnable, extra_env)?;
1000
1001                Some((cmd, FlycheckCommandOrigin::CheckOverrideCommand))
1002            }
1003        }
1004    }
1005
1006    #[track_caller]
1007    fn send(&self, check_task: FlycheckMessage) {
1008        self.sender.send(check_task).unwrap();
1009    }
1010}
1011
1012#[allow(clippy::large_enum_variant)]
1013#[derive(Debug)]
1014enum CheckMessage {
1015    /// A message from `cargo check`, including details like the path
1016    /// to the relevant `Cargo.toml`.
1017    CompilerArtifact(cargo_metadata::Artifact),
1018    /// A diagnostic message from rustc itself.
1019    Diagnostic { diagnostic: Diagnostic, package_id: Option<PackageSpecifier> },
1020}
1021
1022struct CheckParser;
1023
1024impl CheckParser {
1025    fn parse_line(&self, line: &str, error: &mut String) -> Option<CheckMessage> {
1026        let mut deserializer = serde_json::Deserializer::from_str(line);
1027        deserializer.disable_recursion_limit();
1028        if let Ok(message) = JsonMessage::deserialize(&mut deserializer) {
1029            return match message {
1030                // Skip certain kinds of messages to only spend time on what's useful
1031                JsonMessage::Cargo(message) => match message {
1032                    cargo_metadata::Message::CompilerArtifact(artifact) if !artifact.fresh => {
1033                        Some(CheckMessage::CompilerArtifact(artifact))
1034                    }
1035                    cargo_metadata::Message::CompilerMessage(msg) => {
1036                        Some(CheckMessage::Diagnostic {
1037                            diagnostic: msg.message,
1038                            package_id: Some(PackageSpecifier::Cargo {
1039                                package_id: Arc::new(msg.package_id),
1040                            }),
1041                        })
1042                    }
1043                    _ => None,
1044                },
1045                JsonMessage::Rustc(message) => {
1046                    Some(CheckMessage::Diagnostic { diagnostic: message, package_id: None })
1047                }
1048            };
1049        }
1050
1051        error.push_str(line);
1052        error.push('\n');
1053        None
1054    }
1055}
1056
1057impl JsonLinesParser<CheckMessage> for CheckParser {
1058    fn from_line(&self, line: &str, error: &mut String) -> Option<CheckMessage> {
1059        self.parse_line(line, error)
1060    }
1061
1062    fn from_stderr_line(&self, line: &str, error: &mut String) -> Option<CheckMessage> {
1063        self.parse_line(line, error)
1064    }
1065
1066    fn from_eof(&self) -> Option<CheckMessage> {
1067        None
1068    }
1069}
1070
1071#[derive(Deserialize, Debug)]
1072#[serde(untagged)]
1073enum JsonMessage {
1074    Cargo(cargo_metadata::Message),
1075    Rustc(Diagnostic),
1076}
1077
1078#[cfg(test)]
1079mod tests {
1080    use super::*;
1081    use ide_db::FxHashMap;
1082    use itertools::Itertools;
1083    use paths::Utf8Path;
1084    use project_model::project_json;
1085
1086    #[test]
1087    fn test_substitutions() {
1088        let label = ":label";
1089        let saved_file = "file.rs";
1090
1091        // Runnable says it needs both; you need both.
1092        assert_eq!(test_substitute(None, None, "{label} {saved_file}").as_deref(), None);
1093        assert_eq!(test_substitute(Some(label), None, "{label} {saved_file}").as_deref(), None);
1094        assert_eq!(
1095            test_substitute(None, Some(saved_file), "{label} {saved_file}").as_deref(),
1096            None
1097        );
1098        assert_eq!(
1099            test_substitute(Some(label), Some(saved_file), "{label} {saved_file}").as_deref(),
1100            Some("build :label file.rs")
1101        );
1102
1103        // Only need label? only need label.
1104        assert_eq!(test_substitute(None, None, "{label}").as_deref(), None);
1105        assert_eq!(test_substitute(Some(label), None, "{label}").as_deref(), Some("build :label"),);
1106        assert_eq!(test_substitute(None, Some(saved_file), "{label}").as_deref(), None,);
1107        assert_eq!(
1108            test_substitute(Some(label), Some(saved_file), "{label}").as_deref(),
1109            Some("build :label"),
1110        );
1111
1112        // Only need saved_file
1113        assert_eq!(test_substitute(None, None, "{saved_file}").as_deref(), None);
1114        assert_eq!(test_substitute(Some(label), None, "{saved_file}").as_deref(), None);
1115        assert_eq!(
1116            test_substitute(None, Some(saved_file), "{saved_file}").as_deref(),
1117            Some("build file.rs")
1118        );
1119        assert_eq!(
1120            test_substitute(Some(label), Some(saved_file), "{saved_file}").as_deref(),
1121            Some("build file.rs")
1122        );
1123
1124        // Need neither
1125        assert_eq!(test_substitute(None, None, "xxx").as_deref(), Some("build xxx"));
1126        assert_eq!(test_substitute(Some(label), None, "xxx").as_deref(), Some("build xxx"));
1127        assert_eq!(test_substitute(None, Some(saved_file), "xxx").as_deref(), Some("build xxx"));
1128        assert_eq!(
1129            test_substitute(Some(label), Some(saved_file), "xxx").as_deref(),
1130            Some("build xxx")
1131        );
1132
1133        // {label} mid-argument substitution
1134        assert_eq!(
1135            test_substitute(Some(label), None, "--label={label}").as_deref(),
1136            Some("build --label=:label")
1137        );
1138
1139        // {saved_file} mid-argument substitution
1140        assert_eq!(
1141            test_substitute(None, Some(saved_file), "--saved={saved_file}").as_deref(),
1142            Some("build --saved=file.rs")
1143        );
1144
1145        // $saved_file legacy support (no mid-argument substitution, we never supported that)
1146        assert_eq!(
1147            test_substitute(None, Some(saved_file), "$saved_file").as_deref(),
1148            Some("build file.rs")
1149        );
1150
1151        fn test_substitute(
1152            label: Option<&str>,
1153            saved_file: Option<&str>,
1154            args: &str,
1155        ) -> Option<String> {
1156            Substitutions { label, saved_file }
1157                .substitute(
1158                    &project_json::Runnable {
1159                        program: "build".to_owned(),
1160                        args: Vec::from_iter(args.split_whitespace().map(ToOwned::to_owned)),
1161                        cwd: Utf8Path::new("/path").to_owned(),
1162                        kind: project_json::RunnableKind::Flycheck,
1163                    },
1164                    &FxHashMap::default(),
1165                )
1166                .map(|command| {
1167                    command.get_args().map(|x| x.to_string_lossy()).collect_vec().join(" ")
1168                })
1169                .map(|args| format!("build {}", args))
1170        }
1171    }
1172
1173    #[test]
1174    fn test_flycheck_config_display() {
1175        let clippy = FlycheckConfig::Automatic {
1176            cargo_options: CargoOptions {
1177                subcommand: "clippy".to_owned(),
1178                target_tuples: vec![],
1179                all_targets: false,
1180                set_test: false,
1181                no_default_features: false,
1182                all_features: false,
1183                features: vec![],
1184                extra_args: vec![],
1185                extra_test_bin_args: vec![],
1186                extra_env: FxHashMap::default(),
1187                config_path: None,
1188                target_dir_config: TargetDirectoryConfig::default(),
1189            },
1190            ansi_color_output: true,
1191        };
1192        assert_eq!(clippy.to_string(), "cargo clippy");
1193
1194        let custom_dollar = FlycheckConfig::CustomCommand {
1195            command: "check".to_owned(),
1196            args: vec!["--input".to_owned(), "$saved_file".to_owned()],
1197            extra_env: FxHashMap::default(),
1198            invocation_strategy: InvocationStrategy::Once,
1199        };
1200        assert_eq!(custom_dollar.to_string(), "check --input ...");
1201
1202        let custom_inline = FlycheckConfig::CustomCommand {
1203            command: "check".to_owned(),
1204            args: vec!["--input".to_owned(), "{saved_file}".to_owned()],
1205            extra_env: FxHashMap::default(),
1206            invocation_strategy: InvocationStrategy::Once,
1207        };
1208        assert_eq!(custom_inline.to_string(), "check --input ...");
1209
1210        let custom_rs = FlycheckConfig::CustomCommand {
1211            command: "check".to_owned(),
1212            args: vec!["--input".to_owned(), "/path/to/file.rs".to_owned()],
1213            extra_env: FxHashMap::default(),
1214            invocation_strategy: InvocationStrategy::Once,
1215        };
1216        assert_eq!(custom_rs.to_string(), "check --input ...");
1217    }
1218}