1 //! Flycheck provides the functionality needed to run `cargo check` or
2 //! another compatible command (f.x. clippy) in a background thread and provide
3 //! LSP diagnostics based on the output of the command.
5 use std::{fmt, io, process::Command, time::Duration};
7 use crossbeam_channel::{never, select, unbounded, Receiver, Sender};
9 use serde::Deserialize;
10 use stdx::process::streaming_output;
12 pub use cargo_metadata::diagnostic::{
13 Applicability, Diagnostic, DiagnosticCode, DiagnosticLevel, DiagnosticSpan,
14 DiagnosticSpanMacroExpansion,
17 #[derive(Clone, Debug, PartialEq, Eq)]
18 pub enum FlycheckConfig {
21 target_triple: Option<String>,
23 no_default_features: bool,
25 features: Vec<String>,
26 extra_args: Vec<String>,
34 impl fmt::Display for FlycheckConfig {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 FlycheckConfig::CargoCommand { command, .. } => write!(f, "cargo {}", command),
38 FlycheckConfig::CustomCommand { command, args } => {
39 write!(f, "{} {}", command, args.join(" "))
45 /// Flycheck wraps the shared state and communication machinery used for
46 /// running `cargo check` (or other compatible command) and providing
47 /// diagnostics based on the output.
48 /// The spawned thread is shut down when this struct is dropped.
50 pub struct FlycheckHandle {
51 // XXX: drop order is significant
52 sender: Sender<Restart>,
53 _thread: jod_thread::JoinHandle,
59 sender: Box<dyn Fn(Message) + Send>,
60 config: FlycheckConfig,
61 workspace_root: AbsPathBuf,
63 let actor = FlycheckActor::new(id, sender, config, workspace_root);
64 let (sender, receiver) = unbounded::<Restart>();
65 let thread = jod_thread::Builder::new()
66 .name("Flycheck".to_owned())
67 .spawn(move || actor.run(receiver))
68 .expect("failed to spawn thread");
69 FlycheckHandle { sender, _thread: thread }
72 /// Schedule a re-start of the cargo check worker.
73 pub fn update(&self) {
74 self.sender.send(Restart).unwrap();
79 /// Request adding a diagnostic with fixes included to a file
80 AddDiagnostic { workspace_root: AbsPathBuf, diagnostic: Diagnostic },
82 /// Request check progress notification to client
84 /// Flycheck instance ID
90 impl fmt::Debug for Message {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 Message::AddDiagnostic { workspace_root, diagnostic } => f
94 .debug_struct("AddDiagnostic")
95 .field("workspace_root", workspace_root)
96 .field("diagnostic_code", &diagnostic.code.as_ref().map(|it| &it.code))
98 Message::Progress { id, progress } => {
99 f.debug_struct("Progress").field("id", id).field("progress", progress).finish()
108 DidCheckCrate(String),
109 DidFinish(io::Result<()>),
115 struct FlycheckActor {
117 sender: Box<dyn Fn(Message) + Send>,
118 config: FlycheckConfig,
119 workspace_root: AbsPathBuf,
120 /// WatchThread exists to wrap around the communication needed to be able to
121 /// run `cargo check` without blocking. Currently the Rust standard library
122 /// doesn't provide a way to read sub-process output without blocking, so we
123 /// have to wrap sub-processes output handling in a thread and pass messages
124 /// back over a channel.
125 cargo_handle: Option<CargoHandle>,
130 CheckEvent(Option<CargoMessage>),
136 sender: Box<dyn Fn(Message) + Send>,
137 config: FlycheckConfig,
138 workspace_root: AbsPathBuf,
140 FlycheckActor { id, sender, config, workspace_root, cargo_handle: None }
142 fn progress(&self, progress: Progress) {
143 self.send(Message::Progress { id: self.id, progress });
145 fn next_event(&self, inbox: &Receiver<Restart>) -> Option<Event> {
146 let check_chan = self.cargo_handle.as_ref().map(|cargo| &cargo.receiver);
148 recv(inbox) -> msg => msg.ok().map(Event::Restart),
149 recv(check_chan.unwrap_or(&never())) -> msg => Some(Event::CheckEvent(msg.ok())),
152 fn run(mut self, inbox: Receiver<Restart>) {
153 while let Some(event) = self.next_event(&inbox) {
155 Event::Restart(Restart) => {
156 while let Ok(Restart) = inbox.recv_timeout(Duration::from_millis(50)) {}
158 self.cancel_check_process();
160 let command = self.check_command();
161 tracing::info!("restart flycheck {:?}", command);
162 self.cargo_handle = Some(CargoHandle::spawn(command));
163 self.progress(Progress::DidStart);
165 Event::CheckEvent(None) => {
166 // Watcher finished, replace it with a never channel to
167 // avoid busy-waiting.
168 let cargo_handle = self.cargo_handle.take().unwrap();
169 let res = cargo_handle.join();
172 "Flycheck failed to run the following command: {:?}",
176 self.progress(Progress::DidFinish(res));
178 Event::CheckEvent(Some(message)) => match message {
179 CargoMessage::CompilerArtifact(msg) => {
180 self.progress(Progress::DidCheckCrate(msg.target.name));
183 CargoMessage::Diagnostic(msg) => {
184 self.send(Message::AddDiagnostic {
185 workspace_root: self.workspace_root.clone(),
192 // If we rerun the thread, we need to discard the previous check results first
193 self.cancel_check_process();
195 fn cancel_check_process(&mut self) {
196 if self.cargo_handle.take().is_some() {
197 self.progress(Progress::DidCancel);
200 fn check_command(&self) -> Command {
201 let mut cmd = match &self.config {
202 FlycheckConfig::CargoCommand {
211 let mut cmd = Command::new(toolchain::cargo());
213 cmd.current_dir(&self.workspace_root);
214 cmd.args(&["--workspace", "--message-format=json", "--manifest-path"])
215 .arg(self.workspace_root.join("Cargo.toml").as_os_str());
217 if let Some(target) = target_triple {
218 cmd.args(&["--target", target.as_str()]);
221 cmd.arg("--all-targets");
224 cmd.arg("--all-features");
226 if *no_default_features {
227 cmd.arg("--no-default-features");
229 if !features.is_empty() {
230 cmd.arg("--features");
231 cmd.arg(features.join(" "));
234 cmd.args(extra_args);
237 FlycheckConfig::CustomCommand { command, args } => {
238 let mut cmd = Command::new(command);
243 cmd.current_dir(&self.workspace_root);
247 fn send(&self, check_task: Message) {
248 (self.sender)(check_task);
253 thread: jod_thread::JoinHandle<io::Result<()>>,
254 receiver: Receiver<CargoMessage>,
258 fn spawn(command: Command) -> CargoHandle {
259 let (sender, receiver) = unbounded();
260 let actor = CargoActor::new(sender);
261 let thread = jod_thread::Builder::new()
262 .name("CargoHandle".to_owned())
263 .spawn(move || actor.run(command))
264 .expect("failed to spawn thread");
265 CargoHandle { thread, receiver }
268 fn join(self) -> io::Result<()> {
274 sender: Sender<CargoMessage>,
278 fn new(sender: Sender<CargoMessage>) -> CargoActor {
279 CargoActor { sender }
282 fn run(self, command: Command) -> io::Result<()> {
283 // We manually read a line at a time, instead of using serde's
284 // stream deserializers, because the deserializer cannot recover
285 // from an error, resulting in it getting stuck, because we try to
286 // be resilient against failures.
288 // Because cargo only outputs one JSON object per line, we can
289 // simply skip a line if it doesn't parse, which just ignores any
292 let mut error = String::new();
293 let mut read_at_least_one_message = false;
294 let output = streaming_output(
297 read_at_least_one_message = true;
299 // Try to deserialize a message from Cargo or Rustc.
300 let mut deserializer = serde_json::Deserializer::from_str(line);
301 deserializer.disable_recursion_limit();
302 if let Ok(message) = JsonMessage::deserialize(&mut deserializer) {
304 // Skip certain kinds of messages to only spend time on what's useful
305 JsonMessage::Cargo(message) => match message {
306 cargo_metadata::Message::CompilerArtifact(artifact)
307 if !artifact.fresh =>
309 self.sender.send(CargoMessage::CompilerArtifact(artifact)).unwrap();
311 cargo_metadata::Message::CompilerMessage(msg) => {
312 self.sender.send(CargoMessage::Diagnostic(msg.message)).unwrap();
316 JsonMessage::Rustc(message) => {
317 self.sender.send(CargoMessage::Diagnostic(message)).unwrap();
323 error.push_str(line);
328 Ok(_) if read_at_least_one_message => Ok(()),
329 Ok(output) if output.status.success() => Ok(()),
331 Err(io::Error::new(io::ErrorKind::Other, format!(
332 "Cargo watcher failed, the command produced no valid metadata (exit code: {:?}):\n{}",
336 Err(e) => Err(io::Error::new(e.kind(), format!("{:?}: {}", e, error))),
342 CompilerArtifact(cargo_metadata::Artifact),
343 Diagnostic(Diagnostic),
346 #[derive(Deserialize)]
349 Cargo(cargo_metadata::Message),