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