-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathlib.rs
More file actions
2064 lines (1891 loc) · 78.9 KB
/
lib.rs
File metadata and controls
2064 lines (1891 loc) · 78.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Bacon Language Server
use std::collections::{HashMap, HashSet};
use std::env;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use argh::FromArgs;
use bacon::Bacon;
use flume::RecvError;
use ls_types::{Diagnostic, DiagnosticSeverity, MessageType, ProgressToken, Range, Uri, WorkspaceFolder};
use native::Cargo;
use percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode};
use serde_json::{Map, Value};
use shadow::ShadowWorkspace;
use tokio::sync::{RwLock, RwLockWriteGuard};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tower_lsp_server::{Client, LspService, Server, jsonrpc};
use tracing_subscriber::fmt::format::FmtSpan;
mod bacon;
mod lsp;
mod native;
mod shadow;
const PKG_NAME: &str = env!("CARGO_PKG_NAME");
pub const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
const LOCATIONS_FILE: &str = ".bacon-locations";
const BACON_BACKGROUND_COMMAND: &str = "bacon";
const BACON_BACKGROUND_COMMAND_ARGS: &str = "--headless -j bacon-ls";
// Characters that must be percent-encoded when putting an OS path into a
// `file://` URI. We keep `/` unencoded so it continues to split the path into
// segments (clients expect multi-segment URIs). This covers the reserved URI
// characters plus a few that break `Uri` parsing in practice (space, `#`,
// `?`, `%`, `[`/`]`, backslash, etc.).
const PATH_ENCODE_SET: &AsciiSet = &CONTROLS
.add(b' ')
.add(b'"')
.add(b'#')
.add(b'<')
.add(b'>')
.add(b'?')
.add(b'[')
.add(b'\\')
.add(b']')
.add(b'^')
.add(b'`')
.add(b'{')
.add(b'|')
.add(b'}')
.add(b'%');
/// Build a `file://...` URI string from an OS path. Percent-encodes any
/// characters that would otherwise break URI parsing (spaces, `#`, `?`, `%`,
/// etc.), while leaving `/` intact so path segments survive.
pub(crate) fn path_to_file_uri(path: &str) -> String {
format!("file://{}", utf8_percent_encode(path, PATH_ENCODE_SET))
}
/// Hash key for deduplicating diagnostics that share the same range, severity,
/// and message. `DiagnosticSeverity` is `Eq` but not `Hash` in `ls-types`, so we
/// project it down to a small integer tag.
pub(crate) type DiagKey = (Range, i32, String);
pub(crate) fn diag_key(d: &Diagnostic) -> DiagKey {
(d.range, severity_tag(d.severity), d.message.clone())
}
fn severity_tag(s: Option<DiagnosticSeverity>) -> i32 {
match s {
None => 0,
Some(s) if s == DiagnosticSeverity::ERROR => 1,
Some(s) if s == DiagnosticSeverity::WARNING => 2,
Some(s) if s == DiagnosticSeverity::INFORMATION => 3,
Some(s) if s == DiagnosticSeverity::HINT => 4,
Some(_) => -1,
}
}
/// bacon-ls - https://github.com/crisidev/bacon-ls
#[derive(Debug, FromArgs)]
pub struct Args {
/// display version information
#[argh(switch, short = 'v')]
pub version: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BackendChoice {
Cargo,
Bacon,
}
#[derive(Debug)]
enum BackendRuntime {
Bacon {
config: BaconOptions,
runtime: BaconRuntime,
},
Cargo {
config: CargoOptions,
runtime: CargoRuntime,
},
}
impl BackendRuntime {
fn backend_choice(&self) -> BackendChoice {
match self {
Self::Bacon { .. } => BackendChoice::Bacon,
Self::Cargo { .. } => BackendChoice::Cargo,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CargoRunState {
Idle,
Running,
RunningPending,
}
#[derive(Debug, Copy, Clone)]
pub(crate) enum PublishMode {
CancelRunning,
QueueIfRunning,
}
fn invalid_option(name: &str) -> jsonrpc::Error {
jsonrpc::Error {
code: jsonrpc::ErrorCode::InvalidParams,
message: format!("Invalid value for option \"{name}\"").into(),
data: None,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum CargoFeatures {
/// use `--all-features`
All,
/// pass the feature list as `--features=...`
List(Vec<String>),
}
impl Default for CargoFeatures {
fn default() -> Self {
Self::List(vec![])
}
}
impl CargoFeatures {
fn from_json_value(value: &Value) -> jsonrpc::Result<Self> {
match value {
Value::Null => Ok(Self::List(vec![])),
Value::String(str) if str == "all" => Ok(Self::All),
Value::Array(values) => {
let features = values
.iter()
.map(|item| {
item.as_str()
.map(|s| s.to_string())
.ok_or(jsonrpc::Error::new(jsonrpc::ErrorCode::InvalidParams))
})
.collect::<jsonrpc::Result<Vec<_>>>()?;
Ok(Self::List(features))
}
_ => Err(jsonrpc::Error {
code: jsonrpc::ErrorCode::InvalidParams,
message: "features must be a list of strings or the string \"all\"".into(),
data: None,
}),
}
}
}
#[derive(Debug)]
pub(crate) struct CargoOptions {
// "check" or "clippy"
pub(crate) command: String,
pub(crate) features: CargoFeatures,
// `-p crate_name`
pub(crate) package: Option<String>,
pub(crate) all_targets: bool,
pub(crate) no_default_features: bool,
// Extra arguments which do not have a nice wrapper
pub(crate) extra_command_args: Vec<String>,
pub(crate) env: Vec<(String, String)>,
pub(crate) publish_mode: PublishMode,
// Interval at which we refresh (send) cargo diagnostics we have so far
// None means wait until the cargo command is fully done
pub(crate) refresh_interval_seconds: Option<Duration>,
/// User override: when `Some(true)`, always emit children as separate
/// diagnostics instead of related information, regardless of client
/// capability. When `None`, follow the client advertisement.
pub(crate) separate_child_diagnostics: Option<bool>,
pub(crate) check_on_save: bool,
pub(crate) clear_diagnostics_on_check: bool,
/// Live-as-you-type diagnostics. When true, the server mirrors the
/// workspace into a hardlinked shadow under
/// `target/bacon-ls-live/shadow/`, replaces dirty buffers in the shadow
/// on `did_change`, and runs cargo against the shadow with a separate
/// target dir. Off by default.
pub(crate) update_on_insert: bool,
/// Quiet period after the most recent `did_change` before the live
/// cargo run is triggered. Coalesces bursts of keystrokes into a single
/// run.
pub(crate) update_on_insert_debounce: Duration,
}
impl CargoOptions {
pub(crate) fn build_command_args(&self) -> Vec<String> {
let mut args = vec![self.command.clone()];
args.push("--message-format=json-diagnostic-rendered-ansi".to_string());
match &self.features {
CargoFeatures::All => {
args.push("--all-features".to_string());
}
CargoFeatures::List(features) if !features.is_empty() => {
args.push("--features".to_string());
let mut features_list = String::new();
for feature in features[..features.len() - 1].iter() {
features_list += feature;
features_list += ",";
}
features_list += &features[features.len() - 1];
args.push(features_list);
}
_ => {}
}
if let Some(pkg) = self.package.clone() {
args.push("-p".to_string());
args.push(pkg);
}
if self.all_targets {
args.push("--all-targets".to_string());
}
if self.no_default_features {
args.push("--no-default-features".to_string());
}
for arg in self.extra_command_args.iter().cloned() {
args.push(arg);
}
args
}
pub(crate) fn update_from_json_obj(&mut self, cargo_obj: &Map<String, Value>) -> jsonrpc::Result<()> {
if let Some(value) = cargo_obj.get("command") {
self.command = value.as_str().ok_or_else(|| invalid_option("command"))?.to_string();
}
if let Some(value) = cargo_obj.get("features") {
self.features = CargoFeatures::from_json_value(value)?;
}
if let Some(value) = cargo_obj.get("package") {
self.package = Some(value.as_str().ok_or_else(|| invalid_option("package"))?.to_string());
}
if let Some(value) = cargo_obj.get("allTargets") {
self.all_targets = value.as_bool().ok_or_else(|| invalid_option("allTargets"))?;
}
if let Some(value) = cargo_obj.get("noDefaultFeatures") {
self.no_default_features = value.as_bool().ok_or_else(|| invalid_option("noDefaultFeatures"))?;
}
if let Some(value) = cargo_obj.get("extraArgs") {
self.extra_command_args = value
.as_array()
.ok_or_else(|| invalid_option("extraArgs"))?
.iter()
.map(|item| {
item.as_str()
.map(|s| s.to_string())
.ok_or_else(|| invalid_option("extraArgs"))
})
.collect::<jsonrpc::Result<Vec<_>>>()?;
}
if let Some(value) = cargo_obj.get("env") {
self.env = value
.as_object()
.ok_or_else(|| invalid_option("env"))?
.iter()
.map(|(k, v)| {
let val = v.as_str().ok_or_else(|| invalid_option("env"))?;
Ok((k.clone(), val.to_string()))
})
.collect::<jsonrpc::Result<Vec<_>>>()?;
}
if let Some(value) = cargo_obj.get("cancelRunning") {
let cancel = value.as_bool().ok_or_else(|| invalid_option("cancelRunning"))?;
self.publish_mode = if cancel {
PublishMode::CancelRunning
} else {
PublishMode::QueueIfRunning
};
}
if let Some(value) = cargo_obj.get("refreshIntervalSeconds") {
if value.is_null() {
self.refresh_interval_seconds = None;
} else {
let seconds = value.as_i64().ok_or_else(|| invalid_option("refreshIntervalSeconds"))?;
if seconds < 0 {
self.refresh_interval_seconds = None;
} else {
self.refresh_interval_seconds = Some(Duration::from_secs(seconds as u64));
}
}
}
if let Some(value) = cargo_obj.get("separateChildDiagnostics") {
self.separate_child_diagnostics = if value.is_null() {
None
} else {
Some(
value
.as_bool()
.ok_or_else(|| invalid_option("separateChildDiagnostics"))?,
)
};
}
if let Some(value) = cargo_obj.get("checkOnSave") {
self.check_on_save = value.as_bool().ok_or_else(|| invalid_option("checkOnSave"))?;
}
if let Some(value) = cargo_obj.get("clearDiagnosticsOnCheck") {
self.clear_diagnostics_on_check = value
.as_bool()
.ok_or_else(|| invalid_option("clearDiagnosticsOnCheck"))?;
}
if let Some(value) = cargo_obj.get("updateOnInsertDebounceMillis") {
let millis = value
.as_u64()
.ok_or_else(|| invalid_option("updateOnInsertDebounceMillis"))?;
self.update_on_insert_debounce = Duration::from_millis(millis);
}
Ok(())
}
pub(crate) fn reset(&mut self) {
*self = Self::default();
}
}
impl Default for CargoOptions {
fn default() -> Self {
Self {
env: Vec::new(),
publish_mode: PublishMode::CancelRunning,
command: "check".to_string(),
features: CargoFeatures::default(),
all_targets: false,
extra_command_args: vec![],
package: None,
refresh_interval_seconds: Some(Duration::from_secs(1)),
separate_child_diagnostics: None,
check_on_save: true,
clear_diagnostics_on_check: false,
update_on_insert: false,
update_on_insert_debounce: Duration::from_millis(500),
no_default_features: false,
}
}
}
#[derive(Debug)]
pub(crate) struct BaconOptions {
pub(crate) locations_file: String,
pub(crate) run_in_background: bool,
pub(crate) run_in_background_command: String,
pub(crate) run_in_background_command_args: String,
pub(crate) validate_preferences: bool,
pub(crate) create_preferences_file: bool,
pub(crate) synchronize_all_open_files_wait: Duration,
pub(crate) update_on_save: bool,
pub(crate) update_on_save_wait: Duration,
}
impl BaconOptions {
pub(crate) fn update_from_json_obj(&mut self, bacon_obj: &Map<String, Value>) -> jsonrpc::Result<()> {
if let Some(value) = bacon_obj.get("locationsFile") {
self.locations_file = value
.as_str()
.ok_or(jsonrpc::Error::new(jsonrpc::ErrorCode::InvalidParams))?
.to_string();
}
if let Some(value) = bacon_obj.get("runInBackground") {
self.run_in_background = value
.as_bool()
.ok_or(jsonrpc::Error::new(jsonrpc::ErrorCode::InvalidParams))?;
}
if let Some(value) = bacon_obj.get("runInBackgroundCommand") {
self.run_in_background_command = value
.as_str()
.ok_or(jsonrpc::Error::new(jsonrpc::ErrorCode::InvalidParams))?
.to_string();
}
if let Some(value) = bacon_obj.get("runInBackgroundCommandArguments") {
self.run_in_background_command_args = value
.as_str()
.ok_or(jsonrpc::Error::new(jsonrpc::ErrorCode::InvalidParams))?
.to_string();
}
if let Some(value) = bacon_obj.get("validatePreferences") {
self.validate_preferences = value
.as_bool()
.ok_or(jsonrpc::Error::new(jsonrpc::ErrorCode::InvalidParams))?;
}
if let Some(value) = bacon_obj.get("createPreferencesFile") {
self.create_preferences_file = value
.as_bool()
.ok_or(jsonrpc::Error::new(jsonrpc::ErrorCode::InvalidParams))?;
}
if let Some(value) = bacon_obj.get("synchronizeAllOpenFilesWaitMillis") {
self.synchronize_all_open_files_wait = Duration::from_millis(
value
.as_u64()
.ok_or(jsonrpc::Error::new(jsonrpc::ErrorCode::InvalidParams))?,
);
}
if let Some(value) = bacon_obj.get("updateOnSave") {
self.update_on_save = value
.as_bool()
.ok_or(jsonrpc::Error::new(jsonrpc::ErrorCode::InvalidParams))?;
}
if let Some(value) = bacon_obj.get("updateOnSaveWaitMillis") {
self.update_on_save_wait = Duration::from_millis(
value
.as_u64()
.ok_or(jsonrpc::Error::new(jsonrpc::ErrorCode::InvalidParams))?,
);
}
Ok(())
}
pub fn reset(&mut self) {
*self = Self::default();
}
}
impl Default for BaconOptions {
fn default() -> Self {
Self {
locations_file: LOCATIONS_FILE.to_string(),
run_in_background: true,
run_in_background_command: BACON_BACKGROUND_COMMAND.to_string(),
run_in_background_command_args: BACON_BACKGROUND_COMMAND_ARGS.to_string(),
validate_preferences: true,
create_preferences_file: true,
synchronize_all_open_files_wait: Duration::from_millis(2000),
update_on_save: true,
update_on_save_wait: Duration::from_millis(1000),
}
}
}
/// Per-invocation overrides used to redirect a cargo run from the real
/// workspace into the hardlinked shadow workspace for live diagnostics.
#[derive(Debug)]
pub(crate) struct LiveCheckContext {
pub(crate) shadow_root: PathBuf,
pub(crate) shadow_target_dir: PathBuf,
pub(crate) real_root: PathBuf,
}
#[derive(Debug)]
pub(crate) struct CargoRuntime {
cancel_token: CancellationToken,
run_state: CargoRunState,
files_with_diags: HashSet<Uri>,
diagnostics_version: i32,
build_folder: PathBuf,
// Timestamp of the most recent publish_cargo_diagnostics invocation.
// Used by did_open to avoid kicking off a redundant run when one was
// just triggered (e.g. the initial run from `initialized` immediately
// followed by the client's first `didOpen`).
last_run_started: Option<Instant>,
/// Hardlinked shadow of the workspace used for live "as you type"
/// diagnostics. None until the first did_change with `update_on_insert`
/// enabled — building it eagerly at backend init would block startup on
/// large workspaces for users who never trigger live mode.
pub(crate) shadow: Option<ShadowWorkspace>,
/// File URIs that currently have a dirty buffer overlaid in the shadow.
/// On did_save / did_close we restore each entry to a hardlink so the
/// next live run reads the on-disk version.
pub(crate) dirty_files: HashSet<Uri>,
/// Pending debounced live-cargo trigger. Each `did_change` cancels the
/// prior handle and schedules a new one so only the last keystroke fires
/// a check.
pub(crate) live_debounce: Option<JoinHandle<()>>,
}
impl Default for CargoRuntime {
fn default() -> Self {
Self {
cancel_token: CancellationToken::new(),
run_state: CargoRunState::Idle,
files_with_diags: HashSet::new(),
diagnostics_version: 0,
build_folder: PathBuf::new(),
last_run_started: None,
shadow: None,
dirty_files: HashSet::new(),
live_debounce: None,
}
}
}
#[derive(Debug)]
pub(crate) struct BaconRuntime {
pub(crate) shutdown_token: CancellationToken,
pub(crate) open_files: HashSet<Uri>,
// Some(..) if we have to run bacon in the background ourselves
pub(crate) command_handle: Option<JoinHandle<()>>,
pub(crate) sync_files_handle: JoinHandle<()>,
// Monotonic counter stamped onto each publishDiagnostics call so clients
// can discard stale results if publishes arrive out of order.
pub(crate) diagnostics_version: i32,
}
#[derive(Debug, Default)]
struct State {
project_root: Option<PathBuf>,
workspace_folders: Option<Vec<WorkspaceFolder>>,
diagnostics_data_supported: bool,
related_information_supported: bool,
backend: Option<BackendRuntime>,
/// Set by `initialize()` from `initialization_options.cargo.updateOnInsert`.
/// We need this at initialize-time to advertise a `Full` text-document
/// sync capability, because dynamic `client/registerCapability` for
/// `textDocument/didChange` after `initialized` doesn't reliably retrofit
/// already-attached buffers (Neovim, in particular, ignores it). A
/// statically-advertised capability is honored at attach.
init_update_on_insert: bool,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub(crate) struct CorrectionEdit {
pub(crate) range: Range,
pub(crate) new_text: String,
}
// A single logical fix can require several disjoint byte-range edits. For
// example, removing `Compact` from `use …::{Compact, FmtSpan}` produces three
// edits: remove `{`, remove `Compact, `, remove `}`, leaving `use …::FmtSpan`.
// All edits must be applied atomically so the file stays valid.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub(crate) struct Correction {
pub(crate) label: String,
pub(crate) edits: Vec<CorrectionEdit>,
}
impl Correction {
pub(crate) fn from_single(range: Range, new_text: &str) -> Self {
let label = if new_text.is_empty() {
"Remove".to_string()
} else {
format!("Replace with: {new_text}")
};
Self {
label,
edits: vec![CorrectionEdit {
range,
new_text: new_text.to_string(),
}],
}
}
pub(crate) fn from_multi(edits: Vec<CorrectionEdit>) -> Self {
let label = match edits.iter().find(|e| !e.new_text.is_empty()) {
None => "Remove".to_string(),
Some(e) => format!("Replace with: {}", e.new_text),
};
Self { label, edits }
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct DiagnosticData {
corrections: Vec<Correction>,
}
#[derive(Debug, Clone)]
pub struct BaconLs {
client: Arc<Client>,
state: Arc<RwLock<State>>,
}
impl BaconLs {
fn new(client: Client) -> Self {
Self {
client: Arc::new(client),
state: Arc::new(RwLock::new(State::default())),
}
}
fn configure_tracing(log_level: Option<String>, log_path: Option<&Path>) {
// Configure logging to file.
let level = log_level.unwrap_or_else(|| env::var("RUST_LOG").unwrap_or("off".to_string()));
if level == "off" {
return;
}
let default_path = PathBuf::from(format!("{PKG_NAME}.log"));
let log_path = log_path.unwrap_or(&default_path);
let file = match std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(log_path)
{
Ok(file) => file,
Err(e) => {
// stdin/stdout are the LSP jsonrpc pipes; stderr is usually
// captured by the client's trace window. One line there is the
// best we can do to tell the user why logging is silent.
eprintln!(
"{PKG_NAME}: could not open log file {}: {e} (tracing disabled)",
log_path.display()
);
return;
}
};
// try_init: tests may install the subscriber more than once across the
// process lifetime (cargo runs them in a single binary). Don't panic
// if a global subscriber is already set — the first one wins.
let _ = tracing_subscriber::fmt()
.with_env_filter(level)
.with_writer(file)
.with_thread_names(true)
.with_span_events(FmtSpan::CLOSE)
.with_target(true)
.with_file(true)
.with_line_number(true)
.try_init();
}
/// Run the LSP server.
pub async fn serve() {
Self::configure_tracing(None, None);
// Lock stdin / stdout.
let stdin = tokio::io::stdin();
let stdout = tokio::io::stdout();
// Start the service.
let (service, socket) = LspService::new(Self::new);
Server::new(stdin, stdout, socket).serve(service).await;
// Force the process to terminate instead of waiting for the tokio
// runtime to drain. Some background tasks (bacon subprocess readers,
// file watchers) can linger past the `exit` notification; if the
// process doesn't die promptly, `:LspRestart` in Neovim gives up
// before starting a fresh instance.
std::process::exit(0);
}
async fn find_git_root_directory(path: &Path) -> Option<PathBuf> {
let output = tokio::process::Command::new("git")
.arg("-C")
.arg(path)
.arg("rev-parse")
.arg("--show-toplevel")
.output()
.await
.ok()?;
if output.status.success() {
String::from_utf8(output.stdout).ok().map(|v| PathBuf::from(v.trim()))
} else {
None
}
}
fn detect_backend(values: &Map<String, Value>) -> Result<BackendChoice, String> {
if let Some(value) = values.get("backend") {
let backend = value.as_str().ok_or("'backend' must be a string")?;
match backend {
"cargo" => Ok(BackendChoice::Cargo),
"bacon" => Ok(BackendChoice::Bacon),
other => Err(format!("Invalid backend value '{other}'. Must be 'cargo' or 'bacon'.")),
}
} else {
let has_cargo = values.get("cargo").and_then(|v| v.as_object()).is_some();
let has_bacon = values.get("bacon").and_then(|v| v.as_object()).is_some();
match (has_cargo, has_bacon) {
(true, true) => Err(
"Both 'cargo' and 'bacon' config sections present without a 'backend' key. \
Set 'backend' to 'cargo' or 'bacon'."
.to_string(),
),
(_, true) => Ok(BackendChoice::Bacon),
_ => Ok(BackendChoice::Cargo),
}
}
}
async fn pull_configuration(&self) {
tracing::debug!("pull_configuration");
let configuration_fut = self.client.configuration(vec![ls_types::ConfigurationItem {
scope_uri: None,
section: Some("bacon_ls".to_string()),
}]);
// A client that never answers `workspace/configuration` (e.g. one
// mid-teardown) would otherwise keep this await alive forever, which
// in turn pins the `initialized` future inside the server loop and
// blocks a clean shutdown.
let response = match tokio::time::timeout(std::time::Duration::from_secs(5), configuration_fut).await {
Ok(Ok(response)) => response,
Ok(Err(e)) => {
tracing::error!("failed to pull configuration: {e}");
return;
}
Err(_) => {
tracing::warn!("workspace/configuration request timed out; proceeding with defaults");
return;
}
};
let Some(settings) = response.into_iter().next() else {
tracing::warn!("empty configuration response from client");
return;
};
tracing::trace!("pulled configuration: {settings:#?}");
self.adapt_to_settings(&settings).await;
}
async fn adapt_to_settings(&self, settings: &Value) {
let mut state = self.state.write().await;
let Some(values) = settings.as_object() else {
tracing::warn!("configuration is not a JSON object");
return;
};
if state.backend.is_none() {
let backend_choice = match Self::detect_backend(values) {
Ok(choice) => {
tracing::info!(backend = ?choice, "backend detected");
choice
}
Err(msg) => {
tracing::error!("{msg}");
self.client.show_message(MessageType::ERROR, &msg).await;
return;
}
};
match backend_choice {
BackendChoice::Bacon => {
let mut config = BaconOptions::default();
if let Some(bacon_obj) = values.get("bacon").and_then(|v| v.as_object())
&& let Err(e) = config.update_from_json_obj(bacon_obj)
{
tracing::error!("invalid bacon configuration: {e}");
self.client
.show_message(MessageType::ERROR, format!("Error in \"bacon\" section: {e}"))
.await;
}
if config.validate_preferences {
if let Err(e) = Bacon::validate_preferences(
&config.run_in_background_command,
config.create_preferences_file,
)
.await
{
tracing::error!("{e}");
self.client.show_message(MessageType::ERROR, e).await;
}
} else {
tracing::warn!("skipping validation of bacon preferences, validateBaconPreferences is false");
}
let proj_root = state.project_root.clone();
let shutdown_token = CancellationToken::new();
let command_handle = if config.run_in_background {
let mut current_dir = None;
if let Ok(cwd) = env::current_dir() {
current_dir = Self::find_git_root_directory(&cwd).await;
if let Some(dir) = ¤t_dir {
if !dir.join("Cargo.toml").exists() {
current_dir = proj_root;
}
} else {
current_dir = proj_root;
}
}
match Bacon::run_in_background(
&config.run_in_background_command,
&config.run_in_background_command_args,
current_dir.as_ref(),
shutdown_token.clone(),
)
.await
{
Ok(command) => {
tracing::info!("bacon was started successfully and is running in the background");
Some(command)
}
Err(e) => {
tracing::error!("{e}");
self.client.show_message(MessageType::ERROR, e).await;
None
}
}
} else {
tracing::warn!("skipping background bacon startup, runBaconInBackground is false");
None
};
let task_state = self.state.clone();
let task_client = self.client.clone();
state.backend = Some(BackendRuntime::Bacon {
config,
runtime: BaconRuntime {
shutdown_token,
open_files: HashSet::new(),
command_handle,
sync_files_handle: tokio::task::spawn(Self::synchronize_diagnostics(
task_state,
task_client,
)),
diagnostics_version: 0,
},
});
tracing::info!("bacon backend initialized");
}
BackendChoice::Cargo => {
let mut config = CargoOptions::default();
// `update_on_insert` is sourced exclusively from
// `initialization_options.cargo.updateOnInsert` (read in
// `initialize` and stashed on `State`). The static
// `textDocument/didChange` capability has to be decided
// before workspace settings even arrive, so the runtime
// gate has to come from the same place.
if state.init_update_on_insert {
config.update_on_insert = true;
}
if let Some(cargo_obj) = values.get("cargo").and_then(|v| v.as_object())
&& let Err(e) = config.update_from_json_obj(cargo_obj)
{
tracing::error!("invalid cargo configuration: {e}");
self.client
.show_message(MessageType::ERROR, format!("Error in \"cargo\" section: {e}"))
.await;
}
if let Err(e) = Self::init_cargo_backend(&mut state, config) {
tracing::error!("{e}");
drop(state);
self.client.show_message(MessageType::ERROR, e).await;
return;
}
drop(state);
}
}
} else {
let current_choice = match &state.backend {
Some(BackendRuntime::Bacon { .. }) => BackendChoice::Bacon,
Some(BackendRuntime::Cargo { .. }) => BackendChoice::Cargo,
None => unreachable!("backend is Some in this branch"),
};
let desired = match Self::detect_backend(values) {
Ok(choice) => choice,
Err(err) => {
tracing::error!("invalid backend configuration on reload: {err}");
self.client.show_message(MessageType::ERROR, &err).await;
return;
}
};
if desired != current_choice {
let msg = "Backend cannot be changed while the server is running. \
Restart the server to switch backends.";
tracing::error!("{msg}");
self.client.show_message(MessageType::ERROR, msg).await;
return;
}
let project_root = state.project_root.clone();
let init_update_on_insert = state.init_update_on_insert;
match &mut state.backend {
Some(BackendRuntime::Cargo { config, runtime }) => {
config.reset();
if init_update_on_insert {
config.update_on_insert = true;
}
if let Some(cargo_obj) = values.get("cargo").and_then(|v| v.as_object())
&& let Err(e) = config.update_from_json_obj(cargo_obj)
{
tracing::error!("invalid cargo configuration: {e}");
self.client
.show_message(MessageType::ERROR, format!("Error in \"cargo\" section: {e}"))
.await;
}
if let Some(root) = project_root {
runtime.build_folder = root;
}
tracing::debug!("cargo configuration updated");
}
Some(BackendRuntime::Bacon { config, .. }) => {
config.reset();
if let Some(bacon_obj) = values.get("bacon").and_then(|v| v.as_object())
&& let Err(e) = config.update_from_json_obj(bacon_obj)
{
tracing::error!("invalid bacon configuration: {e}");
self.client
.show_message(MessageType::ERROR, format!("Error in \"bacon\" section: {e}"))
.await;
}
tracing::debug!("bacon configuration updated");
}
None => unreachable!("backend is Some in this branch"),
}
}
}
fn init_cargo_backend(state: &mut RwLockWriteGuard<'_, State>, config: CargoOptions) -> Result<(), String> {
let build_folder = match &state.project_root {
Some(root) => root.clone(),
None => match env::current_dir() {
Ok(cwd) => {
tracing::warn!(
"no Cargo project root detected; falling back to current working directory: {}",
cwd.display()
);
cwd
}
Err(e) => {
return Err(format!(
"cargo backend cannot start: no project root detected and current working \
directory is unavailable ({e}). Open a folder containing a Cargo.toml and \
restart the server."
));
}
},
};
let runtime = CargoRuntime {
build_folder,
..CargoRuntime::default()
};
tracing::info!(build_folder = ?runtime.build_folder, "cargo backend initialized");
state.backend = Some(BackendRuntime::Cargo { config, runtime });
Ok(())
}
/// Trigger a save-time cargo run against the real workspace.
async fn publish_cargo_diagnostics(&self) {
self.publish_cargo_diagnostics_inner(None).await;
}
/// Trigger a live "as you type" cargo run against the hardlinked shadow
/// workspace. Builds the shadow on first call. Returns silently if
/// `update_on_insert` isn't on or the shadow can't be built.
pub(crate) async fn publish_cargo_diagnostics_live(&self) {
let live_on = {
let state = self.state.read().await;
matches!(
&state.backend,
Some(BackendRuntime::Cargo { config, .. }) if config.update_on_insert
)
};
if !live_on {
return;
}
let Some(shadow) = self.ensure_shadow_built().await else {
return;
};
let ctx = LiveCheckContext {
shadow_root: shadow.shadow_root().to_path_buf(),
shadow_target_dir: shadow.target_dir().to_path_buf(),
real_root: shadow.real_root().to_path_buf(),
};
self.publish_cargo_diagnostics_inner(Some(&ctx)).await;
}
async fn publish_cargo_diagnostics_inner(&self, live: Option<&LiveCheckContext>) {
tracing::info!(live = live.is_some(), "starting cargo diagnostics run");
let mut guard = self.state.write().await;
let project_root = guard.project_root.clone();
let related_information_supported = guard.related_information_supported;
let Some(BackendRuntime::Cargo { config, runtime }) = &mut guard.backend else {
return;
};
let use_related_information = !config
.separate_child_diagnostics