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