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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
use std::{
convert::From,
fmt, fs, io,
ops::Range,
path::{Component, Path, Prefix},
};
use crate::{
buffer::{BufferCapabilities, BufferHandle},
buffer_position::{BufferPosition, BufferRange},
editor::Editor,
editor_utils::MessageKind,
glob::InvalidGlobError,
json::{
FromJson, Json, JsonArray, JsonConvertError, JsonInteger, JsonKey, JsonObject, JsonString,
JsonValue,
},
platform::{Platform, PlatformRequest, ProcessHandle},
};
pub const BUFFER_LEN: usize = 4 * 1024;
pub struct UriParseError;
pub enum Uri<'a> {
Path(&'a Path),
}
impl<'a> Uri<'a> {
pub fn parse(root: &'a Path, uri: &'a str) -> Result<Self, UriParseError> {
let uri = uri.strip_prefix("file:///").ok_or(UriParseError)?;
let path = Path::new(uri);
let path = path.strip_prefix(root).unwrap_or(path);
Ok(Self::Path(path))
}
}
impl<'a> fmt::Display for Uri<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fn fmt_path(f: &mut fmt::Formatter, path: &Path) -> fmt::Result {
let mut components = path.components().peekable();
let mut has_prefix = false;
while let Some(component) = components.next() {
match component {
Component::Prefix(prefix) => match prefix.kind() {
Prefix::Verbatim(p) => match p.to_str() {
Some(p) => {
f.write_str(p)?;
has_prefix = true;
}
None => return Err(fmt::Error),
},
Prefix::VerbatimDisk(d) | Prefix::Disk(d) => {
f.write_fmt(format_args!("{}:", d as char))?;
has_prefix = true;
}
_ => continue,
},
Component::RootDir => {
if has_prefix {
continue;
}
}
Component::CurDir => f.write_str(".")?,
Component::ParentDir => f.write_str("..")?,
Component::Normal(component) => match component.to_str() {
Some(component) => f.write_str(component)?,
None => return Err(fmt::Error),
},
}
if let None = components.peek() {
break;
}
f.write_str("/")?;
}
Ok(())
}
match *self {
Self::Path(path) => {
f.write_str("file:///")?;
fmt_path(f, path)
}
}
}
}
pub fn path_to_language_id(path: &Path) -> &str {
let extension = match path.extension().and_then(|e| e.to_str()) {
Some(extension) => extension,
None => return "",
};
let mut buf = [0; 8];
let extension_len = extension.len();
if extension_len > buf.len() {
return extension;
}
for (bb, eb) in buf.iter_mut().zip(extension.bytes()) {
*bb = eb.to_ascii_lowercase();
}
let extension_lowercase = &buf[..extension_len];
match extension_lowercase {
b"abap" => "abap",
b"bat" | b"cmd" => "bat",
b"bib" => "bibtex",
b"clj" | b"cljs" | b"cljc" | b"edn" => "closure",
b"coffee" | b"litcoffee" => "coffeescript",
b"c" | b"h" => "c",
b"cc" | b"cpp" | b"cxx" | b"c++" | b"hh" | b"hpp" | b"hxx" | b"h++" => "cpp",
b"cs" | b"csx" => "csharp",
b"css" => "css",
b"diff" => "diff",
b"dart" => "dart",
b"dockerfile" => "dockerfile",
b"ex" | b"exs" => "elixir",
b"erl" | b"hrl" => "erlang",
b"fs" | b"fsi" | b"fsx" | b"fsscript" => "fsharp",
b"go" => "go",
b"groovy" | b"gvy" | b"gy" | b"gsh" => "groovy",
b"html" | b"htm" => "html",
b"ini" => "ini",
b"java" => "java",
b"js" | b"mjs" => "javascript",
b"json" => "json",
b"less" => "less",
b"lua" => "lua",
b"md" => "markdown",
b"m" => "objective-c",
b"mm" => "objective-cpp",
b"plx" | b"pl" | b"pm" | b"xs" | b"t" | b"pod" => "perl",
b"php" | b"phtml" | b"php3" | b"php4" | b"php5" | b"php7" | b"phps" | b"php-s" | b"pht"
| b"phar" => "php",
b"ps1" | b"ps1xml" | b"psc1" | b"psd1" | b"psm1" | b"pssc" | b"psrc" | b"cdxml" => {
"powershell"
}
b"py" | b"pyi" | b"pyc" | b"pyd" | b"pyo" | b"pyw" | b"pyz" => "python",
b"r" | b"rdata" | b"rds" | b"rda" => "r",
b"razor" | b"cshtml" | b"vbhtml" => "razor",
b"rb" => "ruby",
b"rs" => "rust",
b"scss" => "scss",
b"sass" => "sass",
b"scala" | b"sc" => "scala",
b"sh" => "shellscript",
b"sql" => "sql",
b"swift" => "swift",
b"ts" | b"tsx" => "typescript",
b"tex" => "tex",
b"vb" => "vb",
b"xml" => "xml",
b"yaml" | b"yml" => "yaml",
_ => extension,
}
}
pub enum ServerEvent {
ParseError,
Request(ServerRequest),
Notification(ServerNotification),
Response(ServerResponse),
}
pub struct ServerRequest {
pub id: JsonValue,
pub method: JsonString,
pub params: JsonValue,
}
pub struct ServerNotification {
pub method: JsonString,
pub params: JsonValue,
}
pub struct ServerResponse {
pub id: RequestId,
pub result: Result<JsonValue, ResponseError>,
}
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct RequestId(pub usize);
impl From<RequestId> for JsonValue {
fn from(id: RequestId) -> JsonValue {
JsonValue::Integer(id.0 as _)
}
}
#[derive(Default)]
pub struct ResponseError {
pub code: JsonInteger,
pub message: JsonKey,
pub data: JsonValue,
}
impl ResponseError {
pub fn parse_error() -> Self {
Self {
code: -32700,
message: JsonKey::Str("ParseError"),
data: JsonValue::Null,
}
}
pub fn method_not_found() -> Self {
Self {
code: -32601,
message: JsonKey::Str("MethodNotFound"),
data: JsonValue::Null,
}
}
}
impl<'json> FromJson<'json> for ResponseError {
fn from_json(value: JsonValue, json: &'json Json) -> Result<Self, JsonConvertError> {
let value = match value {
JsonValue::Object(value) => value,
_ => return Err(JsonConvertError),
};
let mut this = Self::default();
for (key, value) in value.members(json) {
match key {
"code" => this.code = FromJson::from_json(value, json)?,
"message" => this.message = FromJson::from_json(value, json)?,
"data" => this.data = FromJson::from_json(value, json)?,
_ => return Err(JsonConvertError),
}
}
Ok(this)
}
}
pub enum ProtocolError {
ParseError,
MethodNotFound,
}
impl From<UriParseError> for ProtocolError {
fn from(_: UriParseError) -> Self {
Self::ParseError
}
}
impl From<JsonConvertError> for ProtocolError {
fn from(_: JsonConvertError) -> Self {
Self::ParseError
}
}
impl From<InvalidGlobError> for ProtocolError {
fn from(_: InvalidGlobError) -> Self {
Self::ParseError
}
}
#[derive(Default, Clone, Copy)]
pub struct DocumentPosition {
pub line: u32,
pub character: u32,
}
impl DocumentPosition {
pub fn to_json_value(self, json: &mut Json) -> JsonValue {
let mut value = JsonObject::default();
value.set("line".into(), JsonValue::Integer(self.line as _), json);
value.set(
"character".into(),
JsonValue::Integer(self.character as _),
json,
);
value.into()
}
}
impl From<BufferPosition> for DocumentPosition {
fn from(position: BufferPosition) -> Self {
Self {
line: position.line_index as _,
character: position.column_byte_index as _,
}
}
}
impl From<DocumentPosition> for BufferPosition {
fn from(position: DocumentPosition) -> Self {
Self {
line_index: position.line as _,
column_byte_index: position.character as _,
}
}
}
impl<'json> FromJson<'json> for DocumentPosition {
fn from_json(value: JsonValue, json: &'json Json) -> Result<Self, JsonConvertError> {
let value = match value {
JsonValue::Object(value) => value,
_ => return Err(JsonConvertError),
};
let mut this = Self::default();
for (key, value) in value.members(json) {
match key {
"line" => this.line = FromJson::from_json(value, json)?,
"character" => this.character = FromJson::from_json(value, json)?,
_ => return Err(JsonConvertError),
}
}
Ok(this)
}
}
#[derive(Default, Clone, Copy)]
pub struct DocumentRange {
pub start: DocumentPosition,
pub end: DocumentPosition,
}
impl DocumentRange {
pub fn to_json_value(self, json: &mut Json) -> JsonValue {
let mut value = JsonObject::default();
value.set("start".into(), self.start.to_json_value(json), json);
value.set("end".into(), self.end.to_json_value(json), json);
value.into()
}
}
impl From<BufferRange> for DocumentRange {
fn from(range: BufferRange) -> Self {
Self {
start: range.from.into(),
end: range.to.into(),
}
}
}
impl From<DocumentRange> for BufferRange {
fn from(range: DocumentRange) -> Self {
BufferRange::between(range.start.into(), range.end.into())
}
}
impl<'json> FromJson<'json> for DocumentRange {
fn from_json(value: JsonValue, json: &'json Json) -> Result<Self, JsonConvertError> {
let value = match value {
JsonValue::Object(value) => value,
_ => return Err(JsonConvertError),
};
let mut this = Self::default();
for (key, value) in value.members(json) {
match key {
"start" => this.start = FromJson::from_json(value, json)?,
"end" => this.end = FromJson::from_json(value, json)?,
_ => return Err(JsonConvertError),
}
}
Ok(this)
}
}
#[derive(Default)]
pub struct DocumentLocation {
pub uri: JsonString,
pub range: DocumentRange,
}
impl<'json> FromJson<'json> for DocumentLocation {
fn from_json(value: JsonValue, json: &'json Json) -> Result<Self, JsonConvertError> {
let value = match value {
JsonValue::Object(value) => value,
_ => return Err(JsonConvertError),
};
let mut this = Self::default();
for (key, value) in value.members(json) {
match key {
"uri" => this.uri = FromJson::from_json(value, json)?,
"range" => this.range = FromJson::from_json(value, json)?,
_ => return Err(JsonConvertError),
}
}
Ok(this)
}
}
#[derive(Default)]
pub struct TextEdit {
pub range: DocumentRange,
pub new_text: JsonString,
}
impl TextEdit {
pub fn apply_edits(
editor: &mut Editor,
buffer_handle: BufferHandle,
temp_edits: &mut Vec<(BufferRange, BufferRange)>,
edits: JsonArray,
json: &Json,
) {
let buffer = match editor.buffers.get_mut(buffer_handle) {
Some(buffer) => buffer,
None => return,
};
buffer.commit_edits();
temp_edits.clear();
for edit in edits.elements(json) {
let edit = match TextEdit::from_json(edit, json) {
Ok(edit) => edit,
Err(_) => continue,
};
let mut delete_range: BufferRange = edit.range.into();
let text = edit.new_text.as_str(&json);
for (d, i) in temp_edits.iter() {
delete_range.from = delete_range.from.delete(*d);
delete_range.to = delete_range.to.delete(*d);
delete_range.from = delete_range.from.insert(*i);
delete_range.to = delete_range.to.insert(*i);
}
buffer.delete_range(&mut editor.word_database, delete_range, &mut editor.events);
let insert_range = buffer.insert_text(
&mut editor.word_database,
delete_range.from,
text,
&mut editor.events,
);
temp_edits.push((delete_range, insert_range));
}
buffer.commit_edits();
}
}
impl<'json> FromJson<'json> for TextEdit {
fn from_json(value: JsonValue, json: &'json Json) -> Result<Self, JsonConvertError> {
let value = match value {
JsonValue::Object(value) => value,
_ => return Err(JsonConvertError),
};
let mut this = Self::default();
for (key, value) in value.members(json) {
match key {
"range" => this.range = FromJson::from_json(value, json)?,
"newText" => this.new_text = FromJson::from_json(value, json)?,
_ => return Err(JsonConvertError),
}
}
Ok(this)
}
}
#[derive(Default)]
pub struct DocumentEdit {
pub uri: JsonString,
pub edits: JsonArray,
}
impl<'json> FromJson<'json> for DocumentEdit {
fn from_json(value: JsonValue, json: &'json Json) -> Result<Self, JsonConvertError> {
let value = match value {
JsonValue::Object(value) => value,
_ => return Err(JsonConvertError),
};
let mut this = Self::default();
for (key, value) in value.members(json) {
match key {
"textDocument" => this.uri = JsonString::from_json(value.get("uri", json), json)?,
"edits" => this.edits = JsonArray::from_json(value, json)?,
_ => (),
}
}
Ok(this)
}
}
#[derive(Default)]
pub struct CreateFileOperation {
pub uri: JsonString,
pub overwrite: bool,
pub ignore_if_exists: bool,
}
impl<'json> FromJson<'json> for CreateFileOperation {
fn from_json(value: JsonValue, json: &'json Json) -> Result<Self, JsonConvertError> {
let value = match value {
JsonValue::Object(value) => value,
_ => return Err(JsonConvertError),
};
let mut this = Self::default();
for (key, value) in value.members(json) {
match key {
"uri" => this.uri = JsonString::from_json(value, json)?,
"options" => {
for (key, value) in value.members(json) {
match key {
"overwrite" => {
this.overwrite = matches!(value, JsonValue::Boolean(true))
}
"ignoreIfExists" => {
this.ignore_if_exists = matches!(value, JsonValue::Boolean(true))
}
_ => (),
}
}
}
_ => (),
}
}
Ok(this)
}
}
#[derive(Default)]
pub struct RenameFileOperation {
pub old_uri: JsonString,
pub new_uri: JsonString,
pub overwrite: bool,
pub ignore_if_exists: bool,
}
impl<'json> FromJson<'json> for RenameFileOperation {
fn from_json(value: JsonValue, json: &'json Json) -> Result<Self, JsonConvertError> {
let value = match value {
JsonValue::Object(value) => value,
_ => return Err(JsonConvertError),
};
let mut this = Self::default();
for (key, value) in value.members(json) {
match key {
"oldUri" => this.old_uri = JsonString::from_json(value, json)?,
"newUri" => this.new_uri = JsonString::from_json(value, json)?,
"options" => {
for (key, value) in value.members(json) {
match key {
"overwrite" => {
this.overwrite = matches!(value, JsonValue::Boolean(true))
}
"ignoreIfExists" => {
this.ignore_if_exists = matches!(value, JsonValue::Boolean(true))
}
_ => (),
}
}
}
_ => (),
}
}
Ok(this)
}
}
#[derive(Default)]
pub struct DeleteFileOperation {
pub uri: JsonString,
pub recursive: bool,
pub ignore_if_not_exists: bool,
}
impl<'json> FromJson<'json> for DeleteFileOperation {
fn from_json(value: JsonValue, json: &'json Json) -> Result<Self, JsonConvertError> {
let value = match value {
JsonValue::Object(value) => value,
_ => return Err(JsonConvertError),
};
let mut this = Self::default();
for (key, value) in value.members(json) {
match key {
"uri" => this.uri = JsonString::from_json(value, json)?,
"options" => {
for (key, value) in value.members(json) {
match key {
"recursive" => {
this.recursive = matches!(value, JsonValue::Boolean(true))
}
"ignoreIfNotExists" => {
this.ignore_if_not_exists =
matches!(value, JsonValue::Boolean(true))
}
_ => (),
}
}
}
_ => (),
}
}
Ok(this)
}
}
pub enum WorkspaceEditChange {
DocumentEdit(DocumentEdit),
CreateFile(CreateFileOperation),
RenameFile(RenameFileOperation),
DeleteFile(DeleteFileOperation),
}
impl<'json> FromJson<'json> for WorkspaceEditChange {
fn from_json(value: JsonValue, json: &'json Json) -> Result<Self, JsonConvertError> {
let this = match value.clone().get("kind", json) {
JsonValue::String(s) => match s.as_str(json) {
"create" => Self::CreateFile(FromJson::from_json(value, json)?),
"rename" => Self::RenameFile(FromJson::from_json(value, json)?),
"delete" => Self::DeleteFile(FromJson::from_json(value, json)?),
_ => return Err(JsonConvertError),
},
_ => Self::DocumentEdit(FromJson::from_json(value, json)?),
};
Ok(this)
}
}
#[derive(Default)]
pub struct WorkspaceEdit {
document_changes: JsonArray,
}
impl WorkspaceEdit {
pub fn apply(
&self,
editor: &mut Editor,
temp_edits: &mut Vec<(BufferRange, BufferRange)>,
root: &Path,
json: &Json,
) {
for change in self.document_changes.clone().elements(json) {
let change = match WorkspaceEditChange::from_json(change, json) {
Ok(change) => change,
Err(_) => return,
};
match change {
WorkspaceEditChange::DocumentEdit(edit) => {
let path = match Uri::parse(&root, edit.uri.as_str(json)) {
Ok(Uri::Path(path)) => path,
Err(_) => return,
};
let buffer_handle = editor
.buffers
.find_with_path(&editor.current_directory, path);
let (is_temp, buffer_handle) = match buffer_handle {
Some(handle) => (false, handle),
None => {
let buffer = editor.buffers.add_new();
buffer.capabilities = BufferCapabilities::log();
buffer.capabilities.can_save = true;
buffer.path.clear();
buffer.path.push(path);
let _ = buffer.discard_and_reload_from_file(
&mut editor.word_database,
&mut editor.events,
);
(true, buffer.handle())
}
};
TextEdit::apply_edits(editor, buffer_handle, temp_edits, edit.edits, json);
if is_temp {
if let Some(buffer) = editor.buffers.get_mut(buffer_handle) {
let _ = buffer.save_to_file(None, &mut editor.events);
}
editor
.buffers
.defer_remove(buffer_handle, &mut editor.events);
}
}
WorkspaceEditChange::CreateFile(op) => {
let path = match Uri::parse(&root, op.uri.as_str(json)) {
Ok(Uri::Path(path)) => path,
Err(_) => return,
};
let mut open_options = fs::OpenOptions::new();
open_options.write(true);
if op.overwrite {
open_options.truncate(true).create(true);
} else {
open_options.create_new(true);
}
if open_options.open(path).is_err() && !op.ignore_if_exists {
editor
.status_bar
.write(MessageKind::Error)
.fmt(format_args!("could not create file {:?}", path));
}
}
WorkspaceEditChange::RenameFile(op) => {
let old_path = match Uri::parse(&root, op.old_uri.as_str(json)) {
Ok(Uri::Path(path)) => path,
Err(_) => return,
};
let new_path = match Uri::parse(&root, op.new_uri.as_str(json)) {
Ok(Uri::Path(path)) => path,
Err(_) => return,
};
if op.overwrite || !new_path.exists() || !op.ignore_if_exists {
if fs::rename(old_path, new_path).is_err() && !op.ignore_if_exists {}
}
}
WorkspaceEditChange::DeleteFile(op) => {
let path = match Uri::parse(&root, op.uri.as_str(json)) {
Ok(Uri::Path(path)) => path,
Err(_) => return,
};
if op.recursive {
if fs::remove_dir_all(path).is_err() && !op.ignore_if_not_exists {
editor
.status_bar
.write(MessageKind::Error)
.fmt(format_args!("could not delete directory {:?}", path));
}
} else {
if fs::remove_file(path).is_err() && !op.ignore_if_not_exists {
editor
.status_bar
.write(MessageKind::Error)
.fmt(format_args!("could not delete file {:?}", path));
}
}
}
}
}
}
}
impl<'json> FromJson<'json> for WorkspaceEdit {
fn from_json(value: JsonValue, json: &'json Json) -> Result<Self, JsonConvertError> {
let value = match value {
JsonValue::Object(value) => value,
_ => return Err(JsonConvertError),
};
let mut this = Self::default();
let changes = value.get("documentChanges", json);
this.document_changes = FromJson::from_json(changes, json)?;
Ok(this)
}
}
#[derive(Default)]
pub struct DocumentDiagnostic {
pub message: JsonString,
pub range: DocumentRange,
pub data: JsonValue,
}
impl DocumentDiagnostic {
pub fn to_json_value(self, json: &mut Json) -> JsonValue {
let mut value = JsonObject::default();
value.set("message".into(), self.message.into(), json);
value.set("range".into(), self.range.to_json_value(json), json);
value.set("data".into(), self.data, json);
value.into()
}
}
impl<'json> FromJson<'json> for DocumentDiagnostic {
fn from_json(value: JsonValue, json: &'json Json) -> Result<Self, JsonConvertError> {
let value = match value {
JsonValue::Object(value) => value,
_ => return Err(JsonConvertError),
};
let mut this = Self::default();
for (key, value) in value.members(json) {
match key {
"message" => this.message = JsonString::from_json(value, json)?,
"range" => this.range = DocumentRange::from_json(value, json)?,
"data" => this.data = value,
_ => (),
}
}
Ok(this)
}
}
#[derive(Default)]
pub struct DocumentCodeAction {
pub title: JsonString,
pub edit: WorkspaceEdit,
pub disabled: bool,
}
impl<'json> FromJson<'json> for DocumentCodeAction {
fn from_json(value: JsonValue, json: &'json Json) -> Result<Self, JsonConvertError> {
let value = match value {
JsonValue::Object(value) => value,
_ => return Err(JsonConvertError),
};
let mut this = Self::default();
for (key, value) in value.members(json) {
match key {
"title" => this.title = JsonString::from_json(value, json)?,
"edit" => this.edit = WorkspaceEdit::from_json(value, json)?,
"disabled" => this.disabled = true,
_ => (),
}
}
Ok(this)
}
}
#[derive(Default)]
pub struct DocumentSymbolInformation {
pub name: JsonString,
pub uri: JsonString,
pub range: DocumentRange,
pub container_name: Option<JsonString>,
pub children: JsonArray,
}
impl<'json> FromJson<'json> for DocumentSymbolInformation {
fn from_json(value: JsonValue, json: &'json Json) -> Result<Self, JsonConvertError> {
let value = match value {
JsonValue::Object(value) => value,
_ => return Err(JsonConvertError),
};
let mut this = Self::default();
for (key, value) in value.members(json) {
match key {
"name" => this.name = JsonString::from_json(value, json)?,
"location" => {
let location = DocumentLocation::from_json(value, json)?;
this.uri = location.uri;
this.range = location.range;
}
"selectionRange" => this.range = DocumentRange::from_json(value, json)?,
"containerName" => this.container_name = FromJson::from_json(value, json)?,
"children" => this.children = JsonArray::from_json(value, json)?,
_ => (),
}
}
Ok(this)
}
}
#[derive(Default)]
pub struct DocumentCompletionItem {
pub text: JsonString,
}
impl<'json> FromJson<'json> for DocumentCompletionItem {
fn from_json(value: JsonValue, json: &'json Json) -> Result<Self, JsonConvertError> {
let value = match value {
JsonValue::Object(value) => value,
_ => return Err(JsonConvertError),
};
let mut this = Self::default();
for (key, value) in value.members(json) {
match key {
"label" => this.text = JsonString::from_json(value, json)?,
"insertText" => this.text = JsonString::from_json(value, json)?,
_ => (),
}
}
Ok(this)
}
}
fn try_get_content_range(buf: &[u8]) -> Option<Range<usize>> {
fn find_pattern_end(buf: &[u8], pattern: &[u8]) -> Option<usize> {
let len = pattern.len();
buf.windows(len).position(|w| w == pattern).map(|p| p + len)
}
fn parse_number(buf: &[u8]) -> usize {
let mut n = 0;
for b in buf {
if b.is_ascii_digit() {
n *= 10;
n += (b - b'0') as usize;
} else {
break;
}
}
n
}
let content_length_index = find_pattern_end(buf, b"Content-Length: ")?;
let buf = &buf[content_length_index..];
let content_index = find_pattern_end(buf, b"\r\n\r\n")?;
let content_len = parse_number(buf);
let buf = &buf[content_index..];
if buf.len() >= content_len {
let start = content_length_index + content_index;
let end = start + content_len;
Some(start..end)
} else {
None
}
}
fn parse_server_event(json: &Json, body: JsonValue) -> ServerEvent {
let body = match body {
JsonValue::Object(body) => body,
_ => return ServerEvent::ParseError,
};
let mut id = JsonValue::Null;
let mut method = JsonValue::Null;
let mut params = JsonValue::Null;
let mut result = JsonValue::Null;
let mut error: Option<ResponseError> = None;
for (key, value) in body.members(json) {
match key {
"id" => id = value,
"method" => method = value,
"params" => params = value,
"result" => result = value,
"error" => {
error = match FromJson::from_json(value, json) {
Ok(error) => error,
Err(_) => return ServerEvent::ParseError,
}
}
_ => (),
}
}
if let JsonValue::String(method) = method {
match id {
JsonValue::Integer(_) | JsonValue::String(_) => {
ServerEvent::Request(ServerRequest { id, method, params })
}
JsonValue::Null => ServerEvent::Notification(ServerNotification { method, params }),
_ => return ServerEvent::ParseError,
}
} else if let Some(error) = error {
let id = match id {
JsonValue::Integer(n) if n > 0 => n as _,
_ => return ServerEvent::ParseError,
};
ServerEvent::Response(ServerResponse {
id: RequestId(id),
result: Err(error),
})
} else {
let id = match id {
JsonValue::Integer(n) if n > 0 => n as _,
_ => return ServerEvent::ParseError,
};
ServerEvent::Response(ServerResponse {
id: RequestId(id),
result: Ok(result),
})
}
}
pub struct ServerEventIter {
read_len: usize,
}
impl ServerEventIter {
pub fn next(&mut self, protocol: &mut Protocol, json: &mut Json) -> Option<ServerEvent> {
let slice = &protocol.read_buf[self.read_len..];
if slice.is_empty() {
return None;
}
let range = try_get_content_range(slice)?;
self.read_len += range.end;
let mut reader = io::Cursor::new(&slice[range]);
let event = match json.read(&mut reader) {
Ok(body) => parse_server_event(json, body),
_ => ServerEvent::ParseError,
};
Some(event)
}
pub fn finish(&self, protocol: &mut Protocol) {
protocol.read_buf.drain(..self.read_len);
}
}
pub struct Protocol {
process_handle: Option<ProcessHandle>,
body_buf: Vec<u8>,
read_buf: Vec<u8>,
next_request_id: usize,
}
impl Protocol {
pub fn new() -> Self {
Self {
process_handle: None,
body_buf: Vec::new(),
read_buf: Vec::new(),
next_request_id: 1,
}
}
pub fn process_handle(&self) -> Option<ProcessHandle> {
self.process_handle
}
pub fn set_process_handle(&mut self, handle: ProcessHandle) {
self.process_handle = Some(handle);
}
pub fn parse_events(&mut self, bytes: &[u8]) -> ServerEventIter {
self.read_buf.extend_from_slice(bytes);
ServerEventIter { read_len: 0 }
}
pub fn request(
&mut self,
platform: &mut Platform,
json: &mut Json,
method: &'static str,
params: JsonValue,
) -> RequestId {
let id = self.next_request_id;
let mut body = JsonObject::default();
body.set("jsonrpc".into(), "2.0".into(), json);
body.set("id".into(), JsonValue::Integer(id as _), json);
body.set("method".into(), method.into(), json);
body.set("params".into(), params, json);
self.next_request_id += 1;
self.send_body(platform, json, body.into());
RequestId(id)
}
pub fn notify(
&mut self,
platform: &mut Platform,
json: &mut Json,
method: &'static str,
params: JsonValue,
) {
let mut body = JsonObject::default();
body.set("jsonrpc".into(), "2.0".into(), json);
body.set("method".into(), method.into(), json);
body.set("params".into(), params, json);
self.send_body(platform, json, body.into());
}
pub fn respond(
&mut self,
platform: &mut Platform,
json: &mut Json,
request_id: JsonValue,
result: Result<JsonValue, ResponseError>,
) {
let mut body = JsonObject::default();
body.set("id".into(), request_id, json);
match result {
Ok(result) => body.set("result".into(), result, json),
Err(error) => {
let mut e = JsonObject::default();
e.set("code".into(), error.code.into(), json);
e.set("message".into(), error.message.into(), json);
e.set("data".into(), error.data, json);
body.set("error".into(), e.into(), json);
}
}
self.send_body(platform, json, body.into());
}
fn send_body(&mut self, platform: &mut Platform, json: &mut Json, body: JsonValue) {
use io::Write;
let mut buf = platform.buf_pool.acquire();
let write = buf.write();
json.write(&mut self.body_buf, &body);
let _ = write!(write, "Content-Length: {}\r\n\r\n", self.body_buf.len());
write.append(&mut self.body_buf);
if let Some(handle) = self.process_handle {
let buf = buf.share();
platform.enqueue_request(PlatformRequest::WriteToProcess { handle, buf });
}
}
}
struct PendingRequest {
id: RequestId,
method: &'static str,
}
#[derive(Default)]
pub struct PendingRequestColection {
pending_requests: Vec<PendingRequest>,
}
impl PendingRequestColection {
pub fn add(&mut self, id: RequestId, method: &'static str) {
for request in &mut self.pending_requests {
if request.id.0 == 0 {
request.id = id;
request.method = method;
return;
}
}
self.pending_requests.push(PendingRequest { id, method });
}
pub fn take(&mut self, id: RequestId) -> Option<&'static str> {
for i in 0..self.pending_requests.len() {
let request = &self.pending_requests[i];
if request.id == id {
let request = self.pending_requests.swap_remove(i);
return Some(request.method);
}
}
None
}
}