]> git.lizzy.rs Git - rust.git/blob - crates/flycheck/src/lib.rs
internal: Show more project building errors to the user
[rust.git] / crates / flycheck / src / lib.rs
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.
4
5 use std::{fmt, io, process::Command, time::Duration};
6
7 use crossbeam_channel::{never, select, unbounded, Receiver, Sender};
8 use paths::AbsPathBuf;
9 use serde::Deserialize;
10 use stdx::process::streaming_output;
11
12 pub use cargo_metadata::diagnostic::{
13     Applicability, Diagnostic, DiagnosticCode, DiagnosticLevel, DiagnosticSpan,
14     DiagnosticSpanMacroExpansion,
15 };
16
17 #[derive(Clone, Debug, PartialEq, Eq)]
18 pub enum FlycheckConfig {
19     CargoCommand {
20         command: String,
21         target_triple: Option<String>,
22         all_targets: bool,
23         no_default_features: bool,
24         all_features: bool,
25         features: Vec<String>,
26         extra_args: Vec<String>,
27     },
28     CustomCommand {
29         command: String,
30         args: Vec<String>,
31     },
32 }
33
34 impl fmt::Display for FlycheckConfig {
35     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36         match self {
37             FlycheckConfig::CargoCommand { command, .. } => write!(f, "cargo {}", command),
38             FlycheckConfig::CustomCommand { command, args } => {
39                 write!(f, "{} {}", command, args.join(" "))
40             }
41         }
42     }
43 }
44
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.
49 #[derive(Debug)]
50 pub struct FlycheckHandle {
51     // XXX: drop order is significant
52     sender: Sender<Restart>,
53     _thread: jod_thread::JoinHandle,
54 }
55
56 impl FlycheckHandle {
57     pub fn spawn(
58         id: usize,
59         sender: Box<dyn Fn(Message) + Send>,
60         config: FlycheckConfig,
61         workspace_root: AbsPathBuf,
62     ) -> FlycheckHandle {
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 }
70     }
71
72     /// Schedule a re-start of the cargo check worker.
73     pub fn update(&self) {
74         self.sender.send(Restart).unwrap();
75     }
76 }
77
78 pub enum Message {
79     /// Request adding a diagnostic with fixes included to a file
80     AddDiagnostic { workspace_root: AbsPathBuf, diagnostic: Diagnostic },
81
82     /// Request check progress notification to client
83     Progress {
84         /// Flycheck instance ID
85         id: usize,
86         progress: Progress,
87     },
88 }
89
90 impl fmt::Debug for Message {
91     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92         match self {
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))
97                 .finish(),
98             Message::Progress { id, progress } => {
99                 f.debug_struct("Progress").field("id", id).field("progress", progress).finish()
100             }
101         }
102     }
103 }
104
105 #[derive(Debug)]
106 pub enum Progress {
107     DidStart,
108     DidCheckCrate(String),
109     DidFinish(io::Result<()>),
110     DidCancel,
111 }
112
113 struct Restart;
114
115 struct FlycheckActor {
116     id: usize,
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>,
126 }
127
128 enum Event {
129     Restart(Restart),
130     CheckEvent(Option<CargoMessage>),
131 }
132
133 impl FlycheckActor {
134     fn new(
135         id: usize,
136         sender: Box<dyn Fn(Message) + Send>,
137         config: FlycheckConfig,
138         workspace_root: AbsPathBuf,
139     ) -> FlycheckActor {
140         FlycheckActor { id, sender, config, workspace_root, cargo_handle: None }
141     }
142     fn progress(&self, progress: Progress) {
143         self.send(Message::Progress { id: self.id, progress });
144     }
145     fn next_event(&self, inbox: &Receiver<Restart>) -> Option<Event> {
146         let check_chan = self.cargo_handle.as_ref().map(|cargo| &cargo.receiver);
147         select! {
148             recv(inbox) -> msg => msg.ok().map(Event::Restart),
149             recv(check_chan.unwrap_or(&never())) -> msg => Some(Event::CheckEvent(msg.ok())),
150         }
151     }
152     fn run(mut self, inbox: Receiver<Restart>) {
153         while let Some(event) = self.next_event(&inbox) {
154             match event {
155                 Event::Restart(Restart) => {
156                     while let Ok(Restart) = inbox.recv_timeout(Duration::from_millis(50)) {}
157
158                     self.cancel_check_process();
159
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);
164                 }
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();
170                     if res.is_err() {
171                         tracing::error!(
172                             "Flycheck failed to run the following command: {:?}",
173                             self.check_command()
174                         );
175                     }
176                     self.progress(Progress::DidFinish(res));
177                 }
178                 Event::CheckEvent(Some(message)) => match message {
179                     CargoMessage::CompilerArtifact(msg) => {
180                         self.progress(Progress::DidCheckCrate(msg.target.name));
181                     }
182
183                     CargoMessage::Diagnostic(msg) => {
184                         self.send(Message::AddDiagnostic {
185                             workspace_root: self.workspace_root.clone(),
186                             diagnostic: msg,
187                         });
188                     }
189                 },
190             }
191         }
192         // If we rerun the thread, we need to discard the previous check results first
193         self.cancel_check_process();
194     }
195     fn cancel_check_process(&mut self) {
196         if self.cargo_handle.take().is_some() {
197             self.progress(Progress::DidCancel);
198         }
199     }
200     fn check_command(&self) -> Command {
201         let mut cmd = match &self.config {
202             FlycheckConfig::CargoCommand {
203                 command,
204                 target_triple,
205                 no_default_features,
206                 all_targets,
207                 all_features,
208                 extra_args,
209                 features,
210             } => {
211                 let mut cmd = Command::new(toolchain::cargo());
212                 cmd.arg(command);
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());
216
217                 if let Some(target) = target_triple {
218                     cmd.args(&["--target", target.as_str()]);
219                 }
220                 if *all_targets {
221                     cmd.arg("--all-targets");
222                 }
223                 if *all_features {
224                     cmd.arg("--all-features");
225                 } else {
226                     if *no_default_features {
227                         cmd.arg("--no-default-features");
228                     }
229                     if !features.is_empty() {
230                         cmd.arg("--features");
231                         cmd.arg(features.join(" "));
232                     }
233                 }
234                 cmd.args(extra_args);
235                 cmd
236             }
237             FlycheckConfig::CustomCommand { command, args } => {
238                 let mut cmd = Command::new(command);
239                 cmd.args(args);
240                 cmd
241             }
242         };
243         cmd.current_dir(&self.workspace_root);
244         cmd
245     }
246
247     fn send(&self, check_task: Message) {
248         (self.sender)(check_task);
249     }
250 }
251
252 struct CargoHandle {
253     thread: jod_thread::JoinHandle<io::Result<()>>,
254     receiver: Receiver<CargoMessage>,
255 }
256
257 impl CargoHandle {
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 }
266     }
267
268     fn join(self) -> io::Result<()> {
269         self.thread.join()
270     }
271 }
272
273 struct CargoActor {
274     sender: Sender<CargoMessage>,
275 }
276
277 impl CargoActor {
278     fn new(sender: Sender<CargoMessage>) -> CargoActor {
279         CargoActor { sender }
280     }
281
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.
287         //
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
290         // erroneus output.
291
292         let mut error = String::new();
293         let mut read_at_least_one_message = false;
294         let output = streaming_output(
295             command,
296             &mut |line| {
297                 read_at_least_one_message = true;
298
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) {
303                     match message {
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 =>
308                             {
309                                 self.sender.send(CargoMessage::CompilerArtifact(artifact)).unwrap();
310                             }
311                             cargo_metadata::Message::CompilerMessage(msg) => {
312                                 self.sender.send(CargoMessage::Diagnostic(msg.message)).unwrap();
313                             }
314                             _ => (),
315                         },
316                         JsonMessage::Rustc(message) => {
317                             self.sender.send(CargoMessage::Diagnostic(message)).unwrap();
318                         }
319                     }
320                 }
321             },
322             &mut |line| {
323                 error.push_str(line);
324                 error.push('\n');
325             },
326         );
327         match output {
328             Ok(_) if read_at_least_one_message => Ok(()),
329             Ok(output) if output.status.success() => Ok(()),
330             Ok(output)  => {
331                 Err(io::Error::new(io::ErrorKind::Other, format!(
332                     "Cargo watcher failed, the command produced no valid metadata (exit code: {:?}):\n{}",
333                     output.status, error
334                 )))
335             }
336             Err(e) => Err(io::Error::new(e.kind(), format!("{:?}: {}", e, error))),
337         }
338     }
339 }
340
341 enum CargoMessage {
342     CompilerArtifact(cargo_metadata::Artifact),
343     Diagnostic(Diagnostic),
344 }
345
346 #[derive(Deserialize)]
347 #[serde(untagged)]
348 enum JsonMessage {
349     Cargo(cargo_metadata::Message),
350     Rustc(Diagnostic),
351 }