PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/src/tools/rust-analyzer/crates/flycheck/src/lib.rs

https://bitbucket.org/sailfish009/rust
Rust | 336 lines | 274 code | 31 blank | 31 comment | 21 complexity | ca3b03075145f1f5d3ef788383a1f930 MD5 | raw file
Possible License(s): Apache-2.0, 0BSD, JSON, MIT
  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. use std::{
  5. fmt,
  6. io::{self, BufReader},
  7. ops,
  8. path::PathBuf,
  9. process::{self, Command, Stdio},
  10. time::Duration,
  11. };
  12. use crossbeam_channel::{never, select, unbounded, Receiver, Sender};
  13. pub use cargo_metadata::diagnostic::{
  14. Applicability, Diagnostic, DiagnosticCode, DiagnosticLevel, DiagnosticSpan,
  15. DiagnosticSpanMacroExpansion,
  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. impl fmt::Display for FlycheckConfig {
  34. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  35. match self {
  36. FlycheckConfig::CargoCommand { command, .. } => write!(f, "cargo {}", command),
  37. FlycheckConfig::CustomCommand { command, args } => {
  38. write!(f, "{} {}", command, args.join(" "))
  39. }
  40. }
  41. }
  42. }
  43. /// Flycheck wraps the shared state and communication machinery used for
  44. /// running `cargo check` (or other compatible command) and providing
  45. /// diagnostics based on the output.
  46. /// The spawned thread is shut down when this struct is dropped.
  47. #[derive(Debug)]
  48. pub struct FlycheckHandle {
  49. // XXX: drop order is significant
  50. sender: Sender<Restart>,
  51. thread: jod_thread::JoinHandle,
  52. }
  53. impl FlycheckHandle {
  54. pub fn spawn(
  55. sender: Box<dyn Fn(Message) + Send>,
  56. config: FlycheckConfig,
  57. workspace_root: PathBuf,
  58. ) -> FlycheckHandle {
  59. let actor = FlycheckActor::new(sender, config, workspace_root);
  60. let (sender, receiver) = unbounded::<Restart>();
  61. let thread = jod_thread::spawn(move || actor.run(receiver));
  62. FlycheckHandle { sender, thread }
  63. }
  64. /// Schedule a re-start of the cargo check worker.
  65. pub fn update(&self) {
  66. self.sender.send(Restart).unwrap();
  67. }
  68. }
  69. #[derive(Debug)]
  70. pub enum Message {
  71. /// Request adding a diagnostic with fixes included to a file
  72. AddDiagnostic { workspace_root: PathBuf, diagnostic: Diagnostic },
  73. /// Request check progress notification to client
  74. Progress(Progress),
  75. }
  76. #[derive(Debug)]
  77. pub enum Progress {
  78. DidStart,
  79. DidCheckCrate(String),
  80. DidFinish(io::Result<()>),
  81. DidCancel,
  82. }
  83. struct Restart;
  84. struct FlycheckActor {
  85. sender: Box<dyn Fn(Message) + Send>,
  86. config: FlycheckConfig,
  87. workspace_root: PathBuf,
  88. /// WatchThread exists to wrap around the communication needed to be able to
  89. /// run `cargo check` without blocking. Currently the Rust standard library
  90. /// doesn't provide a way to read sub-process output without blocking, so we
  91. /// have to wrap sub-processes output handling in a thread and pass messages
  92. /// back over a channel.
  93. cargo_handle: Option<CargoHandle>,
  94. }
  95. enum Event {
  96. Restart(Restart),
  97. CheckEvent(Option<cargo_metadata::Message>),
  98. }
  99. impl FlycheckActor {
  100. fn new(
  101. sender: Box<dyn Fn(Message) + Send>,
  102. config: FlycheckConfig,
  103. workspace_root: PathBuf,
  104. ) -> FlycheckActor {
  105. FlycheckActor { sender, config, workspace_root, cargo_handle: None }
  106. }
  107. fn next_event(&self, inbox: &Receiver<Restart>) -> Option<Event> {
  108. let check_chan = self.cargo_handle.as_ref().map(|cargo| &cargo.receiver);
  109. select! {
  110. recv(inbox) -> msg => msg.ok().map(Event::Restart),
  111. recv(check_chan.unwrap_or(&never())) -> msg => Some(Event::CheckEvent(msg.ok())),
  112. }
  113. }
  114. fn run(mut self, inbox: Receiver<Restart>) {
  115. while let Some(event) = self.next_event(&inbox) {
  116. match event {
  117. Event::Restart(Restart) => {
  118. while let Ok(Restart) = inbox.recv_timeout(Duration::from_millis(50)) {}
  119. self.cancel_check_process();
  120. let mut command = self.check_command();
  121. log::info!("restart flycheck {:?}", command);
  122. command.stdout(Stdio::piped()).stderr(Stdio::null()).stdin(Stdio::null());
  123. if let Ok(child) = command.spawn().map(JodChild) {
  124. self.cargo_handle = Some(CargoHandle::spawn(child));
  125. self.send(Message::Progress(Progress::DidStart));
  126. }
  127. }
  128. Event::CheckEvent(None) => {
  129. // Watcher finished, replace it with a never channel to
  130. // avoid busy-waiting.
  131. let cargo_handle = self.cargo_handle.take().unwrap();
  132. let res = cargo_handle.join();
  133. if res.is_err() {
  134. log::error!(
  135. "Flycheck failed to run the following command: {:?}",
  136. self.check_command()
  137. )
  138. }
  139. self.send(Message::Progress(Progress::DidFinish(res)));
  140. }
  141. Event::CheckEvent(Some(message)) => match message {
  142. cargo_metadata::Message::CompilerArtifact(msg) => {
  143. self.send(Message::Progress(Progress::DidCheckCrate(msg.target.name)));
  144. }
  145. cargo_metadata::Message::CompilerMessage(msg) => {
  146. self.send(Message::AddDiagnostic {
  147. workspace_root: self.workspace_root.clone(),
  148. diagnostic: msg.message,
  149. });
  150. }
  151. cargo_metadata::Message::BuildScriptExecuted(_)
  152. | cargo_metadata::Message::BuildFinished(_)
  153. | cargo_metadata::Message::TextLine(_)
  154. | cargo_metadata::Message::Unknown => {}
  155. },
  156. }
  157. }
  158. // If we rerun the thread, we need to discard the previous check results first
  159. self.cancel_check_process();
  160. }
  161. fn cancel_check_process(&mut self) {
  162. if self.cargo_handle.take().is_some() {
  163. self.send(Message::Progress(Progress::DidCancel));
  164. }
  165. }
  166. fn check_command(&self) -> Command {
  167. let mut cmd = match &self.config {
  168. FlycheckConfig::CargoCommand {
  169. command,
  170. target_triple,
  171. no_default_features,
  172. all_targets,
  173. all_features,
  174. extra_args,
  175. features,
  176. } => {
  177. let mut cmd = Command::new(toolchain::cargo());
  178. cmd.arg(command);
  179. cmd.args(&["--workspace", "--message-format=json", "--manifest-path"])
  180. .arg(self.workspace_root.join("Cargo.toml"));
  181. if let Some(target) = target_triple {
  182. cmd.args(&["--target", target.as_str()]);
  183. }
  184. if *all_targets {
  185. cmd.arg("--all-targets");
  186. }
  187. if *all_features {
  188. cmd.arg("--all-features");
  189. } else {
  190. if *no_default_features {
  191. cmd.arg("--no-default-features");
  192. }
  193. if !features.is_empty() {
  194. cmd.arg("--features");
  195. cmd.arg(features.join(" "));
  196. }
  197. }
  198. cmd.args(extra_args);
  199. cmd
  200. }
  201. FlycheckConfig::CustomCommand { command, args } => {
  202. let mut cmd = Command::new(command);
  203. cmd.args(args);
  204. cmd
  205. }
  206. };
  207. cmd.current_dir(&self.workspace_root);
  208. cmd
  209. }
  210. fn send(&self, check_task: Message) {
  211. (self.sender)(check_task)
  212. }
  213. }
  214. struct CargoHandle {
  215. child: JodChild,
  216. #[allow(unused)]
  217. thread: jod_thread::JoinHandle<io::Result<bool>>,
  218. receiver: Receiver<cargo_metadata::Message>,
  219. }
  220. impl CargoHandle {
  221. fn spawn(mut child: JodChild) -> CargoHandle {
  222. let child_stdout = child.stdout.take().unwrap();
  223. let (sender, receiver) = unbounded();
  224. let actor = CargoActor::new(child_stdout, sender);
  225. let thread = jod_thread::spawn(move || actor.run());
  226. CargoHandle { child, thread, receiver }
  227. }
  228. fn join(mut self) -> io::Result<()> {
  229. // It is okay to ignore the result, as it only errors if the process is already dead
  230. let _ = self.child.kill();
  231. let exit_status = self.child.wait()?;
  232. let read_at_least_one_message = self.thread.join()?;
  233. if !exit_status.success() && !read_at_least_one_message {
  234. // FIXME: Read the stderr to display the reason, see `read2()` reference in PR comment:
  235. // https://github.com/rust-analyzer/rust-analyzer/pull/3632#discussion_r395605298
  236. return Err(io::Error::new(
  237. io::ErrorKind::Other,
  238. format!(
  239. "Cargo watcher failed, the command produced no valid metadata (exit code: {:?})",
  240. exit_status
  241. ),
  242. ));
  243. }
  244. Ok(())
  245. }
  246. }
  247. struct CargoActor {
  248. child_stdout: process::ChildStdout,
  249. sender: Sender<cargo_metadata::Message>,
  250. }
  251. impl CargoActor {
  252. fn new(
  253. child_stdout: process::ChildStdout,
  254. sender: Sender<cargo_metadata::Message>,
  255. ) -> CargoActor {
  256. CargoActor { child_stdout, sender }
  257. }
  258. fn run(self) -> io::Result<bool> {
  259. // We manually read a line at a time, instead of using serde's
  260. // stream deserializers, because the deserializer cannot recover
  261. // from an error, resulting in it getting stuck, because we try to
  262. // be resilient against failures.
  263. //
  264. // Because cargo only outputs one JSON object per line, we can
  265. // simply skip a line if it doesn't parse, which just ignores any
  266. // erroneus output.
  267. let stdout = BufReader::new(self.child_stdout);
  268. let mut read_at_least_one_message = false;
  269. for message in cargo_metadata::Message::parse_stream(stdout) {
  270. let message = match message {
  271. Ok(message) => message,
  272. Err(err) => {
  273. log::error!("Invalid json from cargo check, ignoring ({})", err);
  274. continue;
  275. }
  276. };
  277. read_at_least_one_message = true;
  278. // Skip certain kinds of messages to only spend time on what's useful
  279. match &message {
  280. cargo_metadata::Message::CompilerArtifact(artifact) if artifact.fresh => (),
  281. cargo_metadata::Message::BuildScriptExecuted(_)
  282. | cargo_metadata::Message::Unknown => (),
  283. _ => self.sender.send(message).unwrap(),
  284. }
  285. }
  286. Ok(read_at_least_one_message)
  287. }
  288. }
  289. struct JodChild(process::Child);
  290. impl ops::Deref for JodChild {
  291. type Target = process::Child;
  292. fn deref(&self) -> &process::Child {
  293. &self.0
  294. }
  295. }
  296. impl ops::DerefMut for JodChild {
  297. fn deref_mut(&mut self) -> &mut process::Child {
  298. &mut self.0
  299. }
  300. }
  301. impl Drop for JodChild {
  302. fn drop(&mut self) {
  303. let _ = self.0.kill();
  304. }
  305. }