1use crate::{
2 diagnostic_set::DiagnosticEntry, CodeAction, CodeLabel, Completion, CursorShape, Diagnostic,
3 Language,
4};
5use anyhow::{anyhow, Result};
6use clock::ReplicaId;
7use lsp::{DiagnosticSeverity, LanguageServerId};
8use rpc::proto;
9use std::{ops::Range, sync::Arc};
10use text::*;
11
12pub use proto::{BufferState, Operation};
13
14pub fn serialize_fingerprint(fingerprint: RopeFingerprint) -> String {
15 fingerprint.to_hex()
16}
17
18pub fn deserialize_fingerprint(fingerprint: &str) -> Result<RopeFingerprint> {
19 RopeFingerprint::from_hex(fingerprint)
20 .map_err(|error| anyhow!("invalid fingerprint: {}", error))
21}
22
23pub fn deserialize_line_ending(message: proto::LineEnding) -> fs::LineEnding {
24 match message {
25 proto::LineEnding::Unix => fs::LineEnding::Unix,
26 proto::LineEnding::Windows => fs::LineEnding::Windows,
27 }
28}
29
30pub fn serialize_line_ending(message: fs::LineEnding) -> proto::LineEnding {
31 match message {
32 fs::LineEnding::Unix => proto::LineEnding::Unix,
33 fs::LineEnding::Windows => proto::LineEnding::Windows,
34 }
35}
36
37pub fn serialize_operation(operation: &crate::Operation) -> proto::Operation {
38 proto::Operation {
39 variant: Some(match operation {
40 crate::Operation::Buffer(text::Operation::Edit(edit)) => {
41 proto::operation::Variant::Edit(serialize_edit_operation(edit))
42 }
43
44 crate::Operation::Buffer(text::Operation::Undo {
45 undo,
46 lamport_timestamp,
47 }) => proto::operation::Variant::Undo(proto::operation::Undo {
48 replica_id: undo.id.replica_id as u32,
49 local_timestamp: undo.id.value,
50 lamport_timestamp: lamport_timestamp.value,
51 version: serialize_version(&undo.version),
52 counts: undo
53 .counts
54 .iter()
55 .map(|(edit_id, count)| proto::UndoCount {
56 replica_id: edit_id.replica_id as u32,
57 local_timestamp: edit_id.value,
58 count: *count,
59 })
60 .collect(),
61 }),
62
63 crate::Operation::UpdateSelections {
64 selections,
65 line_mode,
66 lamport_timestamp,
67 cursor_shape,
68 } => proto::operation::Variant::UpdateSelections(proto::operation::UpdateSelections {
69 replica_id: lamport_timestamp.replica_id as u32,
70 lamport_timestamp: lamport_timestamp.value,
71 selections: serialize_selections(selections),
72 line_mode: *line_mode,
73 cursor_shape: serialize_cursor_shape(cursor_shape) as i32,
74 }),
75
76 crate::Operation::UpdateDiagnostics {
77 lamport_timestamp,
78 server_id,
79 diagnostics,
80 } => proto::operation::Variant::UpdateDiagnostics(proto::UpdateDiagnostics {
81 replica_id: lamport_timestamp.replica_id as u32,
82 lamport_timestamp: lamport_timestamp.value,
83 server_id: server_id.0 as u64,
84 diagnostics: serialize_diagnostics(diagnostics.iter()),
85 }),
86
87 crate::Operation::UpdateCompletionTriggers {
88 triggers,
89 lamport_timestamp,
90 } => proto::operation::Variant::UpdateCompletionTriggers(
91 proto::operation::UpdateCompletionTriggers {
92 replica_id: lamport_timestamp.replica_id as u32,
93 lamport_timestamp: lamport_timestamp.value,
94 triggers: triggers.clone(),
95 },
96 ),
97 }),
98 }
99}
100
101pub fn serialize_edit_operation(operation: &EditOperation) -> proto::operation::Edit {
102 proto::operation::Edit {
103 replica_id: operation.timestamp.replica_id as u32,
104 local_timestamp: operation.timestamp.local,
105 lamport_timestamp: operation.timestamp.lamport,
106 version: serialize_version(&operation.version),
107 ranges: operation.ranges.iter().map(serialize_range).collect(),
108 new_text: operation
109 .new_text
110 .iter()
111 .map(|text| text.to_string())
112 .collect(),
113 }
114}
115
116pub fn serialize_undo_map_entry(
117 (edit_id, counts): (&clock::Local, &[(clock::Local, u32)]),
118) -> proto::UndoMapEntry {
119 proto::UndoMapEntry {
120 replica_id: edit_id.replica_id as u32,
121 local_timestamp: edit_id.value,
122 counts: counts
123 .iter()
124 .map(|(undo_id, count)| proto::UndoCount {
125 replica_id: undo_id.replica_id as u32,
126 local_timestamp: undo_id.value,
127 count: *count,
128 })
129 .collect(),
130 }
131}
132
133pub fn serialize_selections(selections: &Arc<[Selection<Anchor>]>) -> Vec<proto::Selection> {
134 selections.iter().map(serialize_selection).collect()
135}
136
137pub fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
138 proto::Selection {
139 id: selection.id as u64,
140 start: Some(proto::EditorAnchor {
141 anchor: Some(serialize_anchor(&selection.start)),
142 excerpt_id: 0,
143 }),
144 end: Some(proto::EditorAnchor {
145 anchor: Some(serialize_anchor(&selection.end)),
146 excerpt_id: 0,
147 }),
148 reversed: selection.reversed,
149 }
150}
151
152pub fn serialize_cursor_shape(cursor_shape: &CursorShape) -> proto::CursorShape {
153 match cursor_shape {
154 CursorShape::Bar => proto::CursorShape::CursorBar,
155 CursorShape::Block => proto::CursorShape::CursorBlock,
156 CursorShape::Underscore => proto::CursorShape::CursorUnderscore,
157 CursorShape::Hollow => proto::CursorShape::CursorHollow,
158 }
159}
160
161pub fn deserialize_cursor_shape(cursor_shape: proto::CursorShape) -> CursorShape {
162 match cursor_shape {
163 proto::CursorShape::CursorBar => CursorShape::Bar,
164 proto::CursorShape::CursorBlock => CursorShape::Block,
165 proto::CursorShape::CursorUnderscore => CursorShape::Underscore,
166 proto::CursorShape::CursorHollow => CursorShape::Hollow,
167 }
168}
169
170pub fn serialize_diagnostics<'a>(
171 diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<Anchor>>,
172) -> Vec<proto::Diagnostic> {
173 diagnostics
174 .into_iter()
175 .map(|entry| proto::Diagnostic {
176 source: entry.diagnostic.source.clone(),
177 start: Some(serialize_anchor(&entry.range.start)),
178 end: Some(serialize_anchor(&entry.range.end)),
179 message: entry.diagnostic.message.clone(),
180 severity: match entry.diagnostic.severity {
181 DiagnosticSeverity::ERROR => proto::diagnostic::Severity::Error,
182 DiagnosticSeverity::WARNING => proto::diagnostic::Severity::Warning,
183 DiagnosticSeverity::INFORMATION => proto::diagnostic::Severity::Information,
184 DiagnosticSeverity::HINT => proto::diagnostic::Severity::Hint,
185 _ => proto::diagnostic::Severity::None,
186 } as i32,
187 group_id: entry.diagnostic.group_id as u64,
188 is_primary: entry.diagnostic.is_primary,
189 is_valid: entry.diagnostic.is_valid,
190 code: entry.diagnostic.code.clone(),
191 is_disk_based: entry.diagnostic.is_disk_based,
192 is_unnecessary: entry.diagnostic.is_unnecessary,
193 })
194 .collect()
195}
196
197pub fn serialize_anchor(anchor: &Anchor) -> proto::Anchor {
198 proto::Anchor {
199 replica_id: anchor.timestamp.replica_id as u32,
200 local_timestamp: anchor.timestamp.value,
201 offset: anchor.offset as u64,
202 bias: match anchor.bias {
203 Bias::Left => proto::Bias::Left as i32,
204 Bias::Right => proto::Bias::Right as i32,
205 },
206 buffer_id: anchor.buffer_id,
207 }
208}
209
210pub fn deserialize_operation(message: proto::Operation) -> Result<crate::Operation> {
211 Ok(
212 match message
213 .variant
214 .ok_or_else(|| anyhow!("missing operation variant"))?
215 {
216 proto::operation::Variant::Edit(edit) => {
217 crate::Operation::Buffer(text::Operation::Edit(deserialize_edit_operation(edit)))
218 }
219 proto::operation::Variant::Undo(undo) => {
220 crate::Operation::Buffer(text::Operation::Undo {
221 lamport_timestamp: clock::Lamport {
222 replica_id: undo.replica_id as ReplicaId,
223 value: undo.lamport_timestamp,
224 },
225 undo: UndoOperation {
226 id: clock::Local {
227 replica_id: undo.replica_id as ReplicaId,
228 value: undo.local_timestamp,
229 },
230 version: deserialize_version(&undo.version),
231 counts: undo
232 .counts
233 .into_iter()
234 .map(|c| {
235 (
236 clock::Local {
237 replica_id: c.replica_id as ReplicaId,
238 value: c.local_timestamp,
239 },
240 c.count,
241 )
242 })
243 .collect(),
244 },
245 })
246 }
247 proto::operation::Variant::UpdateSelections(message) => {
248 let selections = message
249 .selections
250 .into_iter()
251 .filter_map(|selection| {
252 Some(Selection {
253 id: selection.id as usize,
254 start: deserialize_anchor(selection.start?.anchor?)?,
255 end: deserialize_anchor(selection.end?.anchor?)?,
256 reversed: selection.reversed,
257 goal: SelectionGoal::None,
258 })
259 })
260 .collect::<Vec<_>>();
261
262 crate::Operation::UpdateSelections {
263 lamport_timestamp: clock::Lamport {
264 replica_id: message.replica_id as ReplicaId,
265 value: message.lamport_timestamp,
266 },
267 selections: Arc::from(selections),
268 line_mode: message.line_mode,
269 cursor_shape: deserialize_cursor_shape(
270 proto::CursorShape::from_i32(message.cursor_shape)
271 .ok_or_else(|| anyhow!("Missing cursor shape"))?,
272 ),
273 }
274 }
275 proto::operation::Variant::UpdateDiagnostics(message) => {
276 crate::Operation::UpdateDiagnostics {
277 lamport_timestamp: clock::Lamport {
278 replica_id: message.replica_id as ReplicaId,
279 value: message.lamport_timestamp,
280 },
281 server_id: LanguageServerId(message.server_id as usize),
282 diagnostics: deserialize_diagnostics(message.diagnostics),
283 }
284 }
285 proto::operation::Variant::UpdateCompletionTriggers(message) => {
286 crate::Operation::UpdateCompletionTriggers {
287 triggers: message.triggers,
288 lamport_timestamp: clock::Lamport {
289 replica_id: message.replica_id as ReplicaId,
290 value: message.lamport_timestamp,
291 },
292 }
293 }
294 },
295 )
296}
297
298pub fn deserialize_edit_operation(edit: proto::operation::Edit) -> EditOperation {
299 EditOperation {
300 timestamp: InsertionTimestamp {
301 replica_id: edit.replica_id as ReplicaId,
302 local: edit.local_timestamp,
303 lamport: edit.lamport_timestamp,
304 },
305 version: deserialize_version(&edit.version),
306 ranges: edit.ranges.into_iter().map(deserialize_range).collect(),
307 new_text: edit.new_text.into_iter().map(Arc::from).collect(),
308 }
309}
310
311pub fn deserialize_undo_map_entry(
312 entry: proto::UndoMapEntry,
313) -> (clock::Local, Vec<(clock::Local, u32)>) {
314 (
315 clock::Local {
316 replica_id: entry.replica_id as u16,
317 value: entry.local_timestamp,
318 },
319 entry
320 .counts
321 .into_iter()
322 .map(|undo_count| {
323 (
324 clock::Local {
325 replica_id: undo_count.replica_id as u16,
326 value: undo_count.local_timestamp,
327 },
328 undo_count.count,
329 )
330 })
331 .collect(),
332 )
333}
334
335pub fn deserialize_selections(selections: Vec<proto::Selection>) -> Arc<[Selection<Anchor>]> {
336 Arc::from(
337 selections
338 .into_iter()
339 .filter_map(deserialize_selection)
340 .collect::<Vec<_>>(),
341 )
342}
343
344pub fn deserialize_selection(selection: proto::Selection) -> Option<Selection<Anchor>> {
345 Some(Selection {
346 id: selection.id as usize,
347 start: deserialize_anchor(selection.start?.anchor?)?,
348 end: deserialize_anchor(selection.end?.anchor?)?,
349 reversed: selection.reversed,
350 goal: SelectionGoal::None,
351 })
352}
353
354pub fn deserialize_diagnostics(
355 diagnostics: Vec<proto::Diagnostic>,
356) -> Arc<[DiagnosticEntry<Anchor>]> {
357 diagnostics
358 .into_iter()
359 .filter_map(|diagnostic| {
360 Some(DiagnosticEntry {
361 range: deserialize_anchor(diagnostic.start?)?..deserialize_anchor(diagnostic.end?)?,
362 diagnostic: Diagnostic {
363 source: diagnostic.source,
364 severity: match proto::diagnostic::Severity::from_i32(diagnostic.severity)? {
365 proto::diagnostic::Severity::Error => DiagnosticSeverity::ERROR,
366 proto::diagnostic::Severity::Warning => DiagnosticSeverity::WARNING,
367 proto::diagnostic::Severity::Information => DiagnosticSeverity::INFORMATION,
368 proto::diagnostic::Severity::Hint => DiagnosticSeverity::HINT,
369 proto::diagnostic::Severity::None => return None,
370 },
371 message: diagnostic.message,
372 group_id: diagnostic.group_id as usize,
373 code: diagnostic.code,
374 is_valid: diagnostic.is_valid,
375 is_primary: diagnostic.is_primary,
376 is_disk_based: diagnostic.is_disk_based,
377 is_unnecessary: diagnostic.is_unnecessary,
378 },
379 })
380 })
381 .collect()
382}
383
384pub fn deserialize_anchor(anchor: proto::Anchor) -> Option<Anchor> {
385 Some(Anchor {
386 timestamp: clock::Local {
387 replica_id: anchor.replica_id as ReplicaId,
388 value: anchor.local_timestamp,
389 },
390 offset: anchor.offset as usize,
391 bias: match proto::Bias::from_i32(anchor.bias)? {
392 proto::Bias::Left => Bias::Left,
393 proto::Bias::Right => Bias::Right,
394 },
395 buffer_id: anchor.buffer_id,
396 })
397}
398
399pub fn lamport_timestamp_for_operation(operation: &proto::Operation) -> Option<clock::Lamport> {
400 let replica_id;
401 let value;
402 match operation.variant.as_ref()? {
403 proto::operation::Variant::Edit(op) => {
404 replica_id = op.replica_id;
405 value = op.lamport_timestamp;
406 }
407 proto::operation::Variant::Undo(op) => {
408 replica_id = op.replica_id;
409 value = op.lamport_timestamp;
410 }
411 proto::operation::Variant::UpdateDiagnostics(op) => {
412 replica_id = op.replica_id;
413 value = op.lamport_timestamp;
414 }
415 proto::operation::Variant::UpdateSelections(op) => {
416 replica_id = op.replica_id;
417 value = op.lamport_timestamp;
418 }
419 proto::operation::Variant::UpdateCompletionTriggers(op) => {
420 replica_id = op.replica_id;
421 value = op.lamport_timestamp;
422 }
423 }
424
425 Some(clock::Lamport {
426 replica_id: replica_id as ReplicaId,
427 value,
428 })
429}
430
431pub fn serialize_completion(completion: &Completion) -> proto::Completion {
432 proto::Completion {
433 old_start: Some(serialize_anchor(&completion.old_range.start)),
434 old_end: Some(serialize_anchor(&completion.old_range.end)),
435 new_text: completion.new_text.clone(),
436 lsp_completion: serde_json::to_vec(&completion.lsp_completion).unwrap(),
437 }
438}
439
440pub async fn deserialize_completion(
441 completion: proto::Completion,
442 language: Option<Arc<Language>>,
443) -> Result<Completion> {
444 let old_start = completion
445 .old_start
446 .and_then(deserialize_anchor)
447 .ok_or_else(|| anyhow!("invalid old start"))?;
448 let old_end = completion
449 .old_end
450 .and_then(deserialize_anchor)
451 .ok_or_else(|| anyhow!("invalid old end"))?;
452 let lsp_completion = serde_json::from_slice(&completion.lsp_completion)?;
453
454 let mut label = None;
455 if let Some(language) = language {
456 label = language.label_for_completion(&lsp_completion).await;
457 }
458
459 Ok(Completion {
460 old_range: old_start..old_end,
461 new_text: completion.new_text,
462 label: label.unwrap_or_else(|| {
463 CodeLabel::plain(
464 lsp_completion.label.clone(),
465 lsp_completion.filter_text.as_deref(),
466 )
467 }),
468 lsp_completion,
469 })
470}
471
472pub fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
473 proto::CodeAction {
474 server_id: action.server_id.0 as u64,
475 start: Some(serialize_anchor(&action.range.start)),
476 end: Some(serialize_anchor(&action.range.end)),
477 lsp_action: serde_json::to_vec(&action.lsp_action).unwrap(),
478 }
479}
480
481pub fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
482 let start = action
483 .start
484 .and_then(deserialize_anchor)
485 .ok_or_else(|| anyhow!("invalid start"))?;
486 let end = action
487 .end
488 .and_then(deserialize_anchor)
489 .ok_or_else(|| anyhow!("invalid end"))?;
490 let lsp_action = serde_json::from_slice(&action.lsp_action)?;
491 Ok(CodeAction {
492 server_id: LanguageServerId(action.server_id as usize),
493 range: start..end,
494 lsp_action,
495 })
496}
497
498pub fn serialize_transaction(transaction: &Transaction) -> proto::Transaction {
499 proto::Transaction {
500 id: Some(serialize_local_timestamp(transaction.id)),
501 edit_ids: transaction
502 .edit_ids
503 .iter()
504 .copied()
505 .map(serialize_local_timestamp)
506 .collect(),
507 start: serialize_version(&transaction.start),
508 }
509}
510
511pub fn deserialize_transaction(transaction: proto::Transaction) -> Result<Transaction> {
512 Ok(Transaction {
513 id: deserialize_local_timestamp(
514 transaction
515 .id
516 .ok_or_else(|| anyhow!("missing transaction id"))?,
517 ),
518 edit_ids: transaction
519 .edit_ids
520 .into_iter()
521 .map(deserialize_local_timestamp)
522 .collect(),
523 start: deserialize_version(&transaction.start),
524 })
525}
526
527pub fn serialize_local_timestamp(timestamp: clock::Local) -> proto::LocalTimestamp {
528 proto::LocalTimestamp {
529 replica_id: timestamp.replica_id as u32,
530 value: timestamp.value,
531 }
532}
533
534pub fn deserialize_local_timestamp(timestamp: proto::LocalTimestamp) -> clock::Local {
535 clock::Local {
536 replica_id: timestamp.replica_id as ReplicaId,
537 value: timestamp.value,
538 }
539}
540
541pub fn serialize_range(range: &Range<FullOffset>) -> proto::Range {
542 proto::Range {
543 start: range.start.0 as u64,
544 end: range.end.0 as u64,
545 }
546}
547
548pub fn deserialize_range(range: proto::Range) -> Range<FullOffset> {
549 FullOffset(range.start as usize)..FullOffset(range.end as usize)
550}
551
552pub fn deserialize_version(message: &[proto::VectorClockEntry]) -> clock::Global {
553 let mut version = clock::Global::new();
554 for entry in message {
555 version.observe(clock::Local {
556 replica_id: entry.replica_id as ReplicaId,
557 value: entry.timestamp,
558 });
559 }
560 version
561}
562
563pub fn serialize_version(version: &clock::Global) -> Vec<proto::VectorClockEntry> {
564 version
565 .iter()
566 .map(|entry| proto::VectorClockEntry {
567 replica_id: entry.replica_id as u32,
568 timestamp: entry.value,
569 })
570 .collect()
571}