diff options
Diffstat (limited to 'crates/flycheck')
-rw-r--r-- | crates/flycheck/Cargo.toml | 16 | ||||
-rw-r--r-- | crates/flycheck/src/lib.rs | 285 |
2 files changed, 301 insertions, 0 deletions
diff --git a/crates/flycheck/Cargo.toml b/crates/flycheck/Cargo.toml new file mode 100644 index 000000000..dc26b8ce7 --- /dev/null +++ b/crates/flycheck/Cargo.toml | |||
@@ -0,0 +1,16 @@ | |||
1 | [package] | ||
2 | edition = "2018" | ||
3 | name = "flycheck" | ||
4 | version = "0.1.0" | ||
5 | authors = ["rust-analyzer developers"] | ||
6 | |||
7 | [lib] | ||
8 | doctest = false | ||
9 | |||
10 | [dependencies] | ||
11 | crossbeam-channel = "0.4.0" | ||
12 | log = "0.4.8" | ||
13 | cargo_metadata = "0.10.0" | ||
14 | serde_json = "1.0.48" | ||
15 | jod-thread = "0.1.1" | ||
16 | ra_toolchain = { path = "../ra_toolchain" } | ||
diff --git a/crates/flycheck/src/lib.rs b/crates/flycheck/src/lib.rs new file mode 100644 index 000000000..92ec4f92e --- /dev/null +++ b/crates/flycheck/src/lib.rs | |||
@@ -0,0 +1,285 @@ | |||
1 | //! cargo_check 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::{ | ||
6 | fmt, | ||
7 | io::{self, BufReader}, | ||
8 | path::PathBuf, | ||
9 | process::{Command, Stdio}, | ||
10 | time::Duration, | ||
11 | }; | ||
12 | |||
13 | use crossbeam_channel::{never, select, unbounded, Receiver, Sender}; | ||
14 | |||
15 | pub use cargo_metadata::diagnostic::{ | ||
16 | Applicability, Diagnostic, DiagnosticLevel, DiagnosticSpan, DiagnosticSpanMacroExpansion, | ||
17 | }; | ||
18 | |||
19 | #[derive(Clone, Debug, PartialEq, Eq)] | ||
20 | pub enum FlycheckConfig { | ||
21 | CargoCommand { | ||
22 | command: String, | ||
23 | all_targets: 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 | cmd_send: Sender<Restart>, | ||
53 | handle: jod_thread::JoinHandle, | ||
54 | } | ||
55 | |||
56 | impl FlycheckHandle { | ||
57 | pub fn spawn( | ||
58 | sender: Box<dyn Fn(Message) + Send>, | ||
59 | config: FlycheckConfig, | ||
60 | workspace_root: PathBuf, | ||
61 | ) -> FlycheckHandle { | ||
62 | let (cmd_send, cmd_recv) = unbounded::<Restart>(); | ||
63 | let handle = jod_thread::spawn(move || { | ||
64 | FlycheckActor::new(sender, config, workspace_root).run(cmd_recv); | ||
65 | }); | ||
66 | FlycheckHandle { cmd_send, handle } | ||
67 | } | ||
68 | |||
69 | /// Schedule a re-start of the cargo check worker. | ||
70 | pub fn update(&self) { | ||
71 | self.cmd_send.send(Restart).unwrap(); | ||
72 | } | ||
73 | } | ||
74 | |||
75 | #[derive(Debug)] | ||
76 | pub enum Message { | ||
77 | /// Request adding a diagnostic with fixes included to a file | ||
78 | AddDiagnostic { workspace_root: PathBuf, diagnostic: Diagnostic }, | ||
79 | |||
80 | /// Request check progress notification to client | ||
81 | Progress(Progress), | ||
82 | } | ||
83 | |||
84 | #[derive(Debug)] | ||
85 | pub enum Progress { | ||
86 | DidStart, | ||
87 | DidCheckCrate(String), | ||
88 | DidFinish, | ||
89 | DidCancel, | ||
90 | } | ||
91 | |||
92 | struct Restart; | ||
93 | |||
94 | struct FlycheckActor { | ||
95 | sender: Box<dyn Fn(Message) + Send>, | ||
96 | config: FlycheckConfig, | ||
97 | workspace_root: PathBuf, | ||
98 | /// WatchThread exists to wrap around the communication needed to be able to | ||
99 | /// run `cargo check` without blocking. Currently the Rust standard library | ||
100 | /// doesn't provide a way to read sub-process output without blocking, so we | ||
101 | /// have to wrap sub-processes output handling in a thread and pass messages | ||
102 | /// back over a channel. | ||
103 | // XXX: drop order is significant | ||
104 | check_process: Option<(Receiver<cargo_metadata::Message>, jod_thread::JoinHandle)>, | ||
105 | } | ||
106 | |||
107 | enum Event { | ||
108 | Restart(Restart), | ||
109 | CheckEvent(Option<cargo_metadata::Message>), | ||
110 | } | ||
111 | |||
112 | impl FlycheckActor { | ||
113 | fn new( | ||
114 | sender: Box<dyn Fn(Message) + Send>, | ||
115 | config: FlycheckConfig, | ||
116 | workspace_root: PathBuf, | ||
117 | ) -> FlycheckActor { | ||
118 | FlycheckActor { sender, config, workspace_root, check_process: None } | ||
119 | } | ||
120 | fn next_event(&self, inbox: &Receiver<Restart>) -> Option<Event> { | ||
121 | let check_chan = self.check_process.as_ref().map(|(chan, _thread)| chan); | ||
122 | select! { | ||
123 | recv(inbox) -> msg => msg.ok().map(Event::Restart), | ||
124 | recv(check_chan.unwrap_or(&never())) -> msg => Some(Event::CheckEvent(msg.ok())), | ||
125 | } | ||
126 | } | ||
127 | fn run(&mut self, inbox: Receiver<Restart>) { | ||
128 | while let Some(event) = self.next_event(&inbox) { | ||
129 | match event { | ||
130 | Event::Restart(Restart) => { | ||
131 | while let Ok(Restart) = inbox.recv_timeout(Duration::from_millis(50)) {} | ||
132 | self.cancel_check_process(); | ||
133 | self.check_process = Some(self.start_check_process()); | ||
134 | self.send(Message::Progress(Progress::DidStart)); | ||
135 | } | ||
136 | Event::CheckEvent(None) => { | ||
137 | // Watcher finished, replace it with a never channel to | ||
138 | // avoid busy-waiting. | ||
139 | assert!(self.check_process.take().is_some()); | ||
140 | self.send(Message::Progress(Progress::DidFinish)); | ||
141 | } | ||
142 | Event::CheckEvent(Some(message)) => match message { | ||
143 | cargo_metadata::Message::CompilerArtifact(msg) => { | ||
144 | self.send(Message::Progress(Progress::DidCheckCrate(msg.target.name))); | ||
145 | } | ||
146 | |||
147 | cargo_metadata::Message::CompilerMessage(msg) => { | ||
148 | self.send(Message::AddDiagnostic { | ||
149 | workspace_root: self.workspace_root.clone(), | ||
150 | diagnostic: msg.message, | ||
151 | }); | ||
152 | } | ||
153 | |||
154 | cargo_metadata::Message::BuildScriptExecuted(_) | ||
155 | | cargo_metadata::Message::BuildFinished(_) | ||
156 | | cargo_metadata::Message::TextLine(_) | ||
157 | | cargo_metadata::Message::Unknown => {} | ||
158 | }, | ||
159 | } | ||
160 | } | ||
161 | // If we rerun the thread, we need to discard the previous check results first | ||
162 | self.cancel_check_process(); | ||
163 | } | ||
164 | fn cancel_check_process(&mut self) { | ||
165 | if self.check_process.take().is_some() { | ||
166 | self.send(Message::Progress(Progress::DidCancel)); | ||
167 | } | ||
168 | } | ||
169 | fn start_check_process(&self) -> (Receiver<cargo_metadata::Message>, jod_thread::JoinHandle) { | ||
170 | let mut cmd = match &self.config { | ||
171 | FlycheckConfig::CargoCommand { | ||
172 | command, | ||
173 | all_targets, | ||
174 | all_features, | ||
175 | extra_args, | ||
176 | features, | ||
177 | } => { | ||
178 | let mut cmd = Command::new(ra_toolchain::cargo()); | ||
179 | cmd.arg(command); | ||
180 | cmd.args(&["--workspace", "--message-format=json", "--manifest-path"]) | ||
181 | .arg(self.workspace_root.join("Cargo.toml")); | ||
182 | if *all_targets { | ||
183 | cmd.arg("--all-targets"); | ||
184 | } | ||
185 | if *all_features { | ||
186 | cmd.arg("--all-features"); | ||
187 | } else if !features.is_empty() { | ||
188 | cmd.arg("--features"); | ||
189 | cmd.arg(features.join(" ")); | ||
190 | } | ||
191 | cmd.args(extra_args); | ||
192 | cmd | ||
193 | } | ||
194 | FlycheckConfig::CustomCommand { command, args } => { | ||
195 | let mut cmd = Command::new(command); | ||
196 | cmd.args(args); | ||
197 | cmd | ||
198 | } | ||
199 | }; | ||
200 | cmd.current_dir(&self.workspace_root); | ||
201 | |||
202 | let (message_send, message_recv) = unbounded(); | ||
203 | let thread = jod_thread::spawn(move || { | ||
204 | // If we trigger an error here, we will do so in the loop instead, | ||
205 | // which will break out of the loop, and continue the shutdown | ||
206 | let res = run_cargo(cmd, &mut |message| { | ||
207 | // Skip certain kinds of messages to only spend time on what's useful | ||
208 | match &message { | ||
209 | cargo_metadata::Message::CompilerArtifact(artifact) if artifact.fresh => { | ||
210 | return true | ||
211 | } | ||
212 | cargo_metadata::Message::BuildScriptExecuted(_) | ||
213 | | cargo_metadata::Message::Unknown => return true, | ||
214 | _ => {} | ||
215 | } | ||
216 | |||
217 | // if the send channel was closed, we want to shutdown | ||
218 | message_send.send(message).is_ok() | ||
219 | }); | ||
220 | |||
221 | if let Err(err) = res { | ||
222 | // FIXME: make the `message_send` to be `Sender<Result<CheckEvent, CargoError>>` | ||
223 | // to display user-caused misconfiguration errors instead of just logging them here | ||
224 | log::error!("Cargo watcher failed {:?}", err); | ||
225 | } | ||
226 | }); | ||
227 | (message_recv, thread) | ||
228 | } | ||
229 | |||
230 | fn send(&self, check_task: Message) { | ||
231 | (self.sender)(check_task) | ||
232 | } | ||
233 | } | ||
234 | |||
235 | fn run_cargo( | ||
236 | mut command: Command, | ||
237 | on_message: &mut dyn FnMut(cargo_metadata::Message) -> bool, | ||
238 | ) -> io::Result<()> { | ||
239 | let mut child = | ||
240 | command.stdout(Stdio::piped()).stderr(Stdio::null()).stdin(Stdio::null()).spawn()?; | ||
241 | |||
242 | // We manually read a line at a time, instead of using serde's | ||
243 | // stream deserializers, because the deserializer cannot recover | ||
244 | // from an error, resulting in it getting stuck, because we try to | ||
245 | // be resillient against failures. | ||
246 | // | ||
247 | // Because cargo only outputs one JSON object per line, we can | ||
248 | // simply skip a line if it doesn't parse, which just ignores any | ||
249 | // erroneus output. | ||
250 | let stdout = BufReader::new(child.stdout.take().unwrap()); | ||
251 | let mut read_at_least_one_message = false; | ||
252 | for message in cargo_metadata::Message::parse_stream(stdout) { | ||
253 | let message = match message { | ||
254 | Ok(message) => message, | ||
255 | Err(err) => { | ||
256 | log::error!("Invalid json from cargo check, ignoring ({})", err); | ||
257 | continue; | ||
258 | } | ||
259 | }; | ||
260 | |||
261 | read_at_least_one_message = true; | ||
262 | |||
263 | if !on_message(message) { | ||
264 | break; | ||
265 | } | ||
266 | } | ||
267 | |||
268 | // It is okay to ignore the result, as it only errors if the process is already dead | ||
269 | let _ = child.kill(); | ||
270 | |||
271 | let exit_status = child.wait()?; | ||
272 | if !exit_status.success() && !read_at_least_one_message { | ||
273 | // FIXME: Read the stderr to display the reason, see `read2()` reference in PR comment: | ||
274 | // https://github.com/rust-analyzer/rust-analyzer/pull/3632#discussion_r395605298 | ||
275 | return Err(io::Error::new( | ||
276 | io::ErrorKind::Other, | ||
277 | format!( | ||
278 | "the command produced no valid metadata (exit code: {:?}): {:?}", | ||
279 | exit_status, command | ||
280 | ), | ||
281 | )); | ||
282 | } | ||
283 | |||
284 | Ok(()) | ||
285 | } | ||