buffer.rs

   1use crate::diagnostic_set::{DiagnosticEntry, DiagnosticGroup};
   2pub use crate::{
   3    diagnostic_set::DiagnosticSet,
   4    highlight_map::{HighlightId, HighlightMap},
   5    proto, BracketPair, Grammar, Language, LanguageConfig, LanguageRegistry, LanguageServerConfig,
   6    PLAIN_TEXT,
   7};
   8use anyhow::{anyhow, Result};
   9use clock::ReplicaId;
  10use futures::FutureExt as _;
  11use gpui::{fonts::HighlightStyle, AppContext, Entity, ModelContext, MutableAppContext, Task};
  12use lazy_static::lazy_static;
  13use lsp::LanguageServer;
  14use parking_lot::Mutex;
  15use postage::{prelude::Stream, sink::Sink, watch};
  16use similar::{ChangeTag, TextDiff};
  17use smol::future::yield_now;
  18use std::{
  19    any::Any,
  20    cell::RefCell,
  21    cmp::{self, Ordering},
  22    collections::{BTreeMap, HashMap},
  23    ffi::OsString,
  24    future::Future,
  25    iter::{Iterator, Peekable},
  26    ops::{Deref, DerefMut, Range, Sub},
  27    path::{Path, PathBuf},
  28    str,
  29    sync::Arc,
  30    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
  31    vec,
  32};
  33use sum_tree::TreeMap;
  34use text::{operation_queue::OperationQueue, rope::TextDimension};
  35pub use text::{Buffer as TextBuffer, Operation as _, *};
  36use theme::SyntaxTheme;
  37use tree_sitter::{InputEdit, Parser, QueryCursor, Tree};
  38use util::{post_inc, TryFutureExt as _};
  39
  40#[cfg(any(test, feature = "test-support"))]
  41pub use tree_sitter_rust;
  42
  43pub use lsp::DiagnosticSeverity;
  44
  45thread_local! {
  46    static PARSER: RefCell<Parser> = RefCell::new(Parser::new());
  47}
  48
  49lazy_static! {
  50    static ref QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Default::default();
  51}
  52
  53// TODO - Make this configurable
  54const INDENT_SIZE: u32 = 4;
  55
  56pub struct Buffer {
  57    text: TextBuffer,
  58    file: Option<Box<dyn File>>,
  59    saved_version: clock::Global,
  60    saved_mtime: SystemTime,
  61    language: Option<Arc<Language>>,
  62    autoindent_requests: Vec<Arc<AutoindentRequest>>,
  63    pending_autoindent: Option<Task<()>>,
  64    sync_parse_timeout: Duration,
  65    syntax_tree: Mutex<Option<SyntaxTree>>,
  66    parsing_in_background: bool,
  67    parse_count: usize,
  68    diagnostics: DiagnosticSet,
  69    remote_selections: TreeMap<ReplicaId, SelectionSet>,
  70    selections_update_count: usize,
  71    diagnostics_update_count: usize,
  72    language_server: Option<LanguageServerState>,
  73    deferred_ops: OperationQueue<Operation>,
  74    #[cfg(test)]
  75    pub(crate) operations: Vec<Operation>,
  76}
  77
  78pub struct BufferSnapshot {
  79    text: text::BufferSnapshot,
  80    tree: Option<Tree>,
  81    diagnostics: DiagnosticSet,
  82    diagnostics_update_count: usize,
  83    remote_selections: TreeMap<ReplicaId, SelectionSet>,
  84    selections_update_count: usize,
  85    is_parsing: bool,
  86    language: Option<Arc<Language>>,
  87    parse_count: usize,
  88}
  89
  90#[derive(Clone, Debug)]
  91struct SelectionSet {
  92    selections: Arc<[Selection<Anchor>]>,
  93    lamport_timestamp: clock::Lamport,
  94}
  95
  96#[derive(Clone, Debug, PartialEq, Eq)]
  97pub struct GroupId {
  98    source: Arc<str>,
  99    id: usize,
 100}
 101
 102#[derive(Clone, Debug, PartialEq, Eq)]
 103pub struct Diagnostic {
 104    pub code: Option<String>,
 105    pub severity: DiagnosticSeverity,
 106    pub message: String,
 107    pub group_id: usize,
 108    pub is_valid: bool,
 109    pub is_primary: bool,
 110    pub is_disk_based: bool,
 111}
 112
 113struct LanguageServerState {
 114    server: Arc<LanguageServer>,
 115    latest_snapshot: watch::Sender<Option<LanguageServerSnapshot>>,
 116    pending_snapshots: BTreeMap<usize, LanguageServerSnapshot>,
 117    next_version: usize,
 118    _maintain_server: Task<Option<()>>,
 119}
 120
 121#[derive(Clone)]
 122struct LanguageServerSnapshot {
 123    buffer_snapshot: text::BufferSnapshot,
 124    version: usize,
 125    path: Arc<Path>,
 126}
 127
 128#[derive(Clone, Debug)]
 129pub enum Operation {
 130    Buffer(text::Operation),
 131    UpdateDiagnostics {
 132        diagnostics: Arc<[DiagnosticEntry<Anchor>]>,
 133        lamport_timestamp: clock::Lamport,
 134    },
 135    UpdateSelections {
 136        replica_id: ReplicaId,
 137        selections: Arc<[Selection<Anchor>]>,
 138        lamport_timestamp: clock::Lamport,
 139    },
 140}
 141
 142#[derive(Clone, Debug, Eq, PartialEq)]
 143pub enum Event {
 144    Edited,
 145    Dirtied,
 146    Saved,
 147    FileHandleChanged,
 148    Reloaded,
 149    Reparsed,
 150    DiagnosticsUpdated,
 151    Closed,
 152}
 153
 154pub trait File {
 155    fn mtime(&self) -> SystemTime;
 156
 157    /// Returns the path of this file relative to the worktree's root directory.
 158    fn path(&self) -> &Arc<Path>;
 159
 160    /// Returns the absolute path of this file.
 161    fn abs_path(&self) -> Option<PathBuf>;
 162
 163    /// Returns the path of this file relative to the worktree's parent directory (this means it
 164    /// includes the name of the worktree's root folder).
 165    fn full_path(&self) -> PathBuf;
 166
 167    /// Returns the last component of this handle's absolute path. If this handle refers to the root
 168    /// of its worktree, then this method will return the name of the worktree itself.
 169    fn file_name(&self) -> Option<OsString>;
 170
 171    fn is_deleted(&self) -> bool;
 172
 173    fn save(
 174        &self,
 175        buffer_id: u64,
 176        text: Rope,
 177        version: clock::Global,
 178        cx: &mut MutableAppContext,
 179    ) -> Task<Result<(clock::Global, SystemTime)>>;
 180
 181    fn load_local(&self, cx: &AppContext) -> Option<Task<Result<String>>>;
 182
 183    fn buffer_updated(&self, buffer_id: u64, operation: Operation, cx: &mut MutableAppContext);
 184
 185    fn buffer_removed(&self, buffer_id: u64, cx: &mut MutableAppContext);
 186
 187    fn as_any(&self) -> &dyn Any;
 188}
 189
 190struct QueryCursorHandle(Option<QueryCursor>);
 191
 192#[derive(Clone)]
 193struct SyntaxTree {
 194    tree: Tree,
 195    version: clock::Global,
 196}
 197
 198#[derive(Clone)]
 199struct AutoindentRequest {
 200    before_edit: BufferSnapshot,
 201    edited: Vec<Anchor>,
 202    inserted: Option<Vec<Range<Anchor>>>,
 203}
 204
 205#[derive(Debug)]
 206struct IndentSuggestion {
 207    basis_row: u32,
 208    indent: bool,
 209}
 210
 211struct TextProvider<'a>(&'a Rope);
 212
 213struct BufferChunkHighlights<'a> {
 214    captures: tree_sitter::QueryCaptures<'a, 'a, TextProvider<'a>>,
 215    next_capture: Option<(tree_sitter::QueryMatch<'a, 'a>, usize)>,
 216    stack: Vec<(usize, HighlightId)>,
 217    highlight_map: HighlightMap,
 218    theme: &'a SyntaxTheme,
 219    _query_cursor: QueryCursorHandle,
 220}
 221
 222pub struct BufferChunks<'a> {
 223    range: Range<usize>,
 224    chunks: rope::Chunks<'a>,
 225    diagnostic_endpoints: Peekable<vec::IntoIter<DiagnosticEndpoint>>,
 226    error_depth: usize,
 227    warning_depth: usize,
 228    information_depth: usize,
 229    hint_depth: usize,
 230    highlights: Option<BufferChunkHighlights<'a>>,
 231}
 232
 233#[derive(Clone, Copy, Debug, Default)]
 234pub struct Chunk<'a> {
 235    pub text: &'a str,
 236    pub highlight_style: Option<HighlightStyle>,
 237    pub diagnostic: Option<DiagnosticSeverity>,
 238}
 239
 240pub(crate) struct Diff {
 241    base_version: clock::Global,
 242    new_text: Arc<str>,
 243    changes: Vec<(ChangeTag, usize)>,
 244}
 245
 246#[derive(Clone, Copy)]
 247struct DiagnosticEndpoint {
 248    offset: usize,
 249    is_start: bool,
 250    severity: DiagnosticSeverity,
 251}
 252
 253impl Buffer {
 254    pub fn new<T: Into<Arc<str>>>(
 255        replica_id: ReplicaId,
 256        base_text: T,
 257        cx: &mut ModelContext<Self>,
 258    ) -> Self {
 259        Self::build(
 260            TextBuffer::new(
 261                replica_id,
 262                cx.model_id() as u64,
 263                History::new(base_text.into()),
 264            ),
 265            None,
 266        )
 267    }
 268
 269    pub fn from_file<T: Into<Arc<str>>>(
 270        replica_id: ReplicaId,
 271        base_text: T,
 272        file: Box<dyn File>,
 273        cx: &mut ModelContext<Self>,
 274    ) -> Self {
 275        Self::build(
 276            TextBuffer::new(
 277                replica_id,
 278                cx.model_id() as u64,
 279                History::new(base_text.into()),
 280            ),
 281            Some(file),
 282        )
 283    }
 284
 285    pub fn from_proto(
 286        replica_id: ReplicaId,
 287        message: proto::Buffer,
 288        file: Option<Box<dyn File>>,
 289        cx: &mut ModelContext<Self>,
 290    ) -> Result<Self> {
 291        let fragments_len = message.fragments.len();
 292        let buffer = TextBuffer::from_parts(
 293            replica_id,
 294            message.id,
 295            &message.visible_text,
 296            &message.deleted_text,
 297            message
 298                .undo_map
 299                .into_iter()
 300                .map(proto::deserialize_undo_map_entry),
 301            message
 302                .fragments
 303                .into_iter()
 304                .enumerate()
 305                .map(|(i, fragment)| {
 306                    proto::deserialize_buffer_fragment(fragment, i, fragments_len)
 307                }),
 308            message.lamport_timestamp,
 309            From::from(message.version),
 310        );
 311        let mut this = Self::build(buffer, file);
 312        for selection_set in message.selections {
 313            this.remote_selections.insert(
 314                selection_set.replica_id as ReplicaId,
 315                SelectionSet {
 316                    selections: proto::deserialize_selections(selection_set.selections),
 317                    lamport_timestamp: clock::Lamport {
 318                        replica_id: selection_set.replica_id as ReplicaId,
 319                        value: selection_set.lamport_timestamp,
 320                    },
 321                },
 322            );
 323        }
 324        let snapshot = this.snapshot();
 325        let entries = proto::deserialize_diagnostics(message.diagnostics);
 326        this.apply_diagnostic_update(
 327            DiagnosticSet::from_sorted_entries(entries.into_iter().cloned(), &snapshot),
 328            cx,
 329        );
 330
 331        let deferred_ops = message
 332            .deferred_operations
 333            .into_iter()
 334            .map(proto::deserialize_operation)
 335            .collect::<Result<Vec<_>>>()?;
 336        this.apply_ops(deferred_ops, cx)?;
 337
 338        Ok(this)
 339    }
 340
 341    pub fn to_proto(&self) -> proto::Buffer {
 342        proto::Buffer {
 343            id: self.remote_id(),
 344            visible_text: self.text.text(),
 345            deleted_text: self.text.deleted_text(),
 346            undo_map: self
 347                .text
 348                .undo_history()
 349                .map(proto::serialize_undo_map_entry)
 350                .collect(),
 351            version: From::from(&self.version),
 352            lamport_timestamp: self.lamport_clock.value,
 353            fragments: self
 354                .text
 355                .fragments()
 356                .map(proto::serialize_buffer_fragment)
 357                .collect(),
 358            selections: self
 359                .remote_selections
 360                .iter()
 361                .map(|(replica_id, set)| proto::SelectionSet {
 362                    replica_id: *replica_id as u32,
 363                    selections: proto::serialize_selections(&set.selections),
 364                    lamport_timestamp: set.lamport_timestamp.value,
 365                })
 366                .collect(),
 367            diagnostics: proto::serialize_diagnostics(self.diagnostics.iter()),
 368            deferred_operations: self
 369                .deferred_ops
 370                .iter()
 371                .map(proto::serialize_operation)
 372                .chain(
 373                    self.text
 374                        .deferred_ops()
 375                        .map(|op| proto::serialize_operation(&Operation::Buffer(op.clone()))),
 376                )
 377                .collect(),
 378        }
 379    }
 380
 381    pub fn with_language(
 382        mut self,
 383        language: Option<Arc<Language>>,
 384        language_server: Option<Arc<LanguageServer>>,
 385        cx: &mut ModelContext<Self>,
 386    ) -> Self {
 387        self.set_language(language, language_server, cx);
 388        self
 389    }
 390
 391    fn build(buffer: TextBuffer, file: Option<Box<dyn File>>) -> Self {
 392        let saved_mtime;
 393        if let Some(file) = file.as_ref() {
 394            saved_mtime = file.mtime();
 395        } else {
 396            saved_mtime = UNIX_EPOCH;
 397        }
 398
 399        Self {
 400            saved_mtime,
 401            saved_version: buffer.version(),
 402            text: buffer,
 403            file,
 404            syntax_tree: Mutex::new(None),
 405            parsing_in_background: false,
 406            parse_count: 0,
 407            sync_parse_timeout: Duration::from_millis(1),
 408            autoindent_requests: Default::default(),
 409            pending_autoindent: Default::default(),
 410            language: None,
 411            remote_selections: Default::default(),
 412            selections_update_count: 0,
 413            diagnostics: Default::default(),
 414            diagnostics_update_count: 0,
 415            language_server: None,
 416            deferred_ops: OperationQueue::new(),
 417            #[cfg(test)]
 418            operations: Default::default(),
 419        }
 420    }
 421
 422    pub fn snapshot(&self) -> BufferSnapshot {
 423        BufferSnapshot {
 424            text: self.text.snapshot(),
 425            tree: self.syntax_tree(),
 426            remote_selections: self.remote_selections.clone(),
 427            diagnostics: self.diagnostics.clone(),
 428            diagnostics_update_count: self.diagnostics_update_count,
 429            is_parsing: self.parsing_in_background,
 430            language: self.language.clone(),
 431            parse_count: self.parse_count,
 432            selections_update_count: self.selections_update_count,
 433        }
 434    }
 435
 436    pub fn file(&self) -> Option<&dyn File> {
 437        self.file.as_deref()
 438    }
 439
 440    pub fn save(
 441        &mut self,
 442        cx: &mut ModelContext<Self>,
 443    ) -> Result<Task<Result<(clock::Global, SystemTime)>>> {
 444        let file = self
 445            .file
 446            .as_ref()
 447            .ok_or_else(|| anyhow!("buffer has no file"))?;
 448        let text = self.as_rope().clone();
 449        let version = self.version();
 450        let save = file.save(self.remote_id(), text, version, cx.as_mut());
 451        Ok(cx.spawn(|this, mut cx| async move {
 452            let (version, mtime) = save.await?;
 453            this.update(&mut cx, |this, cx| {
 454                this.did_save(version.clone(), mtime, None, cx);
 455            });
 456            Ok((version, mtime))
 457        }))
 458    }
 459
 460    pub fn set_language(
 461        &mut self,
 462        language: Option<Arc<Language>>,
 463        language_server: Option<Arc<lsp::LanguageServer>>,
 464        cx: &mut ModelContext<Self>,
 465    ) {
 466        self.language = language;
 467        self.language_server = if let Some(server) = language_server {
 468            let (latest_snapshot_tx, mut latest_snapshot_rx) = watch::channel();
 469            Some(LanguageServerState {
 470                latest_snapshot: latest_snapshot_tx,
 471                pending_snapshots: Default::default(),
 472                next_version: 0,
 473                server: server.clone(),
 474                _maintain_server: cx.background().spawn(
 475                    async move {
 476                        let mut prev_snapshot: Option<LanguageServerSnapshot> = None;
 477                        while let Some(snapshot) = latest_snapshot_rx.recv().await {
 478                            if let Some(snapshot) = snapshot {
 479                                let uri = lsp::Url::from_file_path(&snapshot.path).unwrap();
 480                                if let Some(prev_snapshot) = prev_snapshot {
 481                                    let changes = lsp::DidChangeTextDocumentParams {
 482                                        text_document: lsp::VersionedTextDocumentIdentifier::new(
 483                                            uri,
 484                                            snapshot.version as i32,
 485                                        ),
 486                                        content_changes: snapshot
 487                                            .buffer_snapshot
 488                                            .edits_since::<(PointUtf16, usize)>(
 489                                                prev_snapshot.buffer_snapshot.version(),
 490                                            )
 491                                            .map(|edit| {
 492                                                let edit_start = edit.new.start.0;
 493                                                let edit_end = edit_start
 494                                                    + (edit.old.end.0 - edit.old.start.0);
 495                                                let new_text = snapshot
 496                                                    .buffer_snapshot
 497                                                    .text_for_range(
 498                                                        edit.new.start.1..edit.new.end.1,
 499                                                    )
 500                                                    .collect();
 501                                                lsp::TextDocumentContentChangeEvent {
 502                                                    range: Some(lsp::Range::new(
 503                                                        lsp::Position::new(
 504                                                            edit_start.row,
 505                                                            edit_start.column,
 506                                                        ),
 507                                                        lsp::Position::new(
 508                                                            edit_end.row,
 509                                                            edit_end.column,
 510                                                        ),
 511                                                    )),
 512                                                    range_length: None,
 513                                                    text: new_text,
 514                                                }
 515                                            })
 516                                            .collect(),
 517                                    };
 518                                    server
 519                                        .notify::<lsp::notification::DidChangeTextDocument>(changes)
 520                                        .await?;
 521                                } else {
 522                                    server
 523                                        .notify::<lsp::notification::DidOpenTextDocument>(
 524                                            lsp::DidOpenTextDocumentParams {
 525                                                text_document: lsp::TextDocumentItem::new(
 526                                                    uri,
 527                                                    Default::default(),
 528                                                    snapshot.version as i32,
 529                                                    snapshot.buffer_snapshot.text().to_string(),
 530                                                ),
 531                                            },
 532                                        )
 533                                        .await?;
 534                                }
 535
 536                                prev_snapshot = Some(snapshot);
 537                            }
 538                        }
 539                        Ok(())
 540                    }
 541                    .log_err(),
 542                ),
 543            })
 544        } else {
 545            None
 546        };
 547
 548        self.reparse(cx);
 549        self.update_language_server();
 550    }
 551
 552    pub fn did_save(
 553        &mut self,
 554        version: clock::Global,
 555        mtime: SystemTime,
 556        new_file: Option<Box<dyn File>>,
 557        cx: &mut ModelContext<Self>,
 558    ) {
 559        self.saved_mtime = mtime;
 560        self.saved_version = version;
 561        if let Some(new_file) = new_file {
 562            self.file = Some(new_file);
 563        }
 564        if let Some(state) = &self.language_server {
 565            cx.background()
 566                .spawn(
 567                    state
 568                        .server
 569                        .notify::<lsp::notification::DidSaveTextDocument>(
 570                            lsp::DidSaveTextDocumentParams {
 571                                text_document: lsp::TextDocumentIdentifier {
 572                                    uri: lsp::Url::from_file_path(
 573                                        self.file.as_ref().unwrap().abs_path().unwrap(),
 574                                    )
 575                                    .unwrap(),
 576                                },
 577                                text: None,
 578                            },
 579                        ),
 580                )
 581                .detach()
 582        }
 583        cx.emit(Event::Saved);
 584    }
 585
 586    pub fn file_updated(
 587        &mut self,
 588        new_file: Box<dyn File>,
 589        cx: &mut ModelContext<Self>,
 590    ) -> Option<Task<()>> {
 591        let old_file = self.file.as_ref()?;
 592        let mut file_changed = false;
 593        let mut task = None;
 594
 595        if new_file.path() != old_file.path() {
 596            file_changed = true;
 597        }
 598
 599        if new_file.is_deleted() {
 600            if !old_file.is_deleted() {
 601                file_changed = true;
 602                if !self.is_dirty() {
 603                    cx.emit(Event::Dirtied);
 604                }
 605            }
 606        } else {
 607            let new_mtime = new_file.mtime();
 608            if new_mtime != old_file.mtime() {
 609                file_changed = true;
 610
 611                if !self.is_dirty() {
 612                    task = Some(cx.spawn(|this, mut cx| {
 613                        async move {
 614                            let new_text = this.read_with(&cx, |this, cx| {
 615                                this.file.as_ref().and_then(|file| file.load_local(cx))
 616                            });
 617                            if let Some(new_text) = new_text {
 618                                let new_text = new_text.await?;
 619                                let diff = this
 620                                    .read_with(&cx, |this, cx| this.diff(new_text.into(), cx))
 621                                    .await;
 622                                this.update(&mut cx, |this, cx| {
 623                                    if this.apply_diff(diff, cx) {
 624                                        this.saved_version = this.version();
 625                                        this.saved_mtime = new_mtime;
 626                                        cx.emit(Event::Reloaded);
 627                                    }
 628                                });
 629                            }
 630                            Ok(())
 631                        }
 632                        .log_err()
 633                        .map(drop)
 634                    }));
 635                }
 636            }
 637        }
 638
 639        if file_changed {
 640            cx.emit(Event::FileHandleChanged);
 641        }
 642        self.file = Some(new_file);
 643        task
 644    }
 645
 646    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
 647        cx.emit(Event::Closed);
 648    }
 649
 650    pub fn language(&self) -> Option<&Arc<Language>> {
 651        self.language.as_ref()
 652    }
 653
 654    pub fn parse_count(&self) -> usize {
 655        self.parse_count
 656    }
 657
 658    pub fn selections_update_count(&self) -> usize {
 659        self.selections_update_count
 660    }
 661
 662    pub fn diagnostics_update_count(&self) -> usize {
 663        self.diagnostics_update_count
 664    }
 665
 666    pub(crate) fn syntax_tree(&self) -> Option<Tree> {
 667        if let Some(syntax_tree) = self.syntax_tree.lock().as_mut() {
 668            self.interpolate_tree(syntax_tree);
 669            Some(syntax_tree.tree.clone())
 670        } else {
 671            None
 672        }
 673    }
 674
 675    #[cfg(any(test, feature = "test-support"))]
 676    pub fn is_parsing(&self) -> bool {
 677        self.parsing_in_background
 678    }
 679
 680    #[cfg(test)]
 681    pub fn set_sync_parse_timeout(&mut self, timeout: Duration) {
 682        self.sync_parse_timeout = timeout;
 683    }
 684
 685    fn reparse(&mut self, cx: &mut ModelContext<Self>) -> bool {
 686        if self.parsing_in_background {
 687            return false;
 688        }
 689
 690        if let Some(grammar) = self.grammar().cloned() {
 691            let old_tree = self.syntax_tree();
 692            let text = self.as_rope().clone();
 693            let parsed_version = self.version();
 694            let parse_task = cx.background().spawn({
 695                let grammar = grammar.clone();
 696                async move { Self::parse_text(&text, old_tree, &grammar) }
 697            });
 698
 699            match cx
 700                .background()
 701                .block_with_timeout(self.sync_parse_timeout, parse_task)
 702            {
 703                Ok(new_tree) => {
 704                    self.did_finish_parsing(new_tree, parsed_version, cx);
 705                    return true;
 706                }
 707                Err(parse_task) => {
 708                    self.parsing_in_background = true;
 709                    cx.spawn(move |this, mut cx| async move {
 710                        let new_tree = parse_task.await;
 711                        this.update(&mut cx, move |this, cx| {
 712                            let grammar_changed = this
 713                                .grammar()
 714                                .map_or(true, |curr_grammar| !Arc::ptr_eq(&grammar, curr_grammar));
 715                            let parse_again = this.version.gt(&parsed_version) || grammar_changed;
 716                            this.parsing_in_background = false;
 717                            this.did_finish_parsing(new_tree, parsed_version, cx);
 718
 719                            if parse_again && this.reparse(cx) {
 720                                return;
 721                            }
 722                        });
 723                    })
 724                    .detach();
 725                }
 726            }
 727        }
 728        false
 729    }
 730
 731    fn parse_text(text: &Rope, old_tree: Option<Tree>, grammar: &Grammar) -> Tree {
 732        PARSER.with(|parser| {
 733            let mut parser = parser.borrow_mut();
 734            parser
 735                .set_language(grammar.ts_language)
 736                .expect("incompatible grammar");
 737            let mut chunks = text.chunks_in_range(0..text.len());
 738            let tree = parser
 739                .parse_with(
 740                    &mut move |offset, _| {
 741                        chunks.seek(offset);
 742                        chunks.next().unwrap_or("").as_bytes()
 743                    },
 744                    old_tree.as_ref(),
 745                )
 746                .unwrap();
 747            tree
 748        })
 749    }
 750
 751    fn interpolate_tree(&self, tree: &mut SyntaxTree) {
 752        for edit in self.edits_since::<(usize, Point)>(&tree.version) {
 753            let (bytes, lines) = edit.flatten();
 754            tree.tree.edit(&InputEdit {
 755                start_byte: bytes.new.start,
 756                old_end_byte: bytes.new.start + bytes.old.len(),
 757                new_end_byte: bytes.new.end,
 758                start_position: lines.new.start.to_ts_point(),
 759                old_end_position: (lines.new.start + (lines.old.end - lines.old.start))
 760                    .to_ts_point(),
 761                new_end_position: lines.new.end.to_ts_point(),
 762            });
 763        }
 764        tree.version = self.version();
 765    }
 766
 767    fn did_finish_parsing(
 768        &mut self,
 769        tree: Tree,
 770        version: clock::Global,
 771        cx: &mut ModelContext<Self>,
 772    ) {
 773        self.parse_count += 1;
 774        *self.syntax_tree.lock() = Some(SyntaxTree { tree, version });
 775        self.request_autoindent(cx);
 776        cx.emit(Event::Reparsed);
 777        cx.notify();
 778    }
 779
 780    pub fn update_diagnostics<T>(
 781        &mut self,
 782        version: Option<i32>,
 783        mut diagnostics: Vec<DiagnosticEntry<T>>,
 784        cx: &mut ModelContext<Self>,
 785    ) -> Result<Operation>
 786    where
 787        T: Copy + Ord + TextDimension + Sub<Output = T> + Clip + ToPoint,
 788    {
 789        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
 790            Ordering::Equal
 791                .then_with(|| b.is_primary.cmp(&a.is_primary))
 792                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
 793                .then_with(|| a.severity.cmp(&b.severity))
 794                .then_with(|| a.message.cmp(&b.message))
 795        }
 796
 797        let version = version.map(|version| version as usize);
 798        let content = if let Some(version) = version {
 799            let language_server = self.language_server.as_mut().unwrap();
 800            language_server
 801                .pending_snapshots
 802                .retain(|&v, _| v >= version);
 803            let snapshot = language_server
 804                .pending_snapshots
 805                .get(&version)
 806                .ok_or_else(|| anyhow!("missing snapshot"))?;
 807            &snapshot.buffer_snapshot
 808        } else {
 809            self.deref()
 810        };
 811
 812        diagnostics.sort_unstable_by(|a, b| {
 813            Ordering::Equal
 814                .then_with(|| a.range.start.cmp(&b.range.start))
 815                .then_with(|| b.range.end.cmp(&a.range.end))
 816                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
 817        });
 818
 819        let mut sanitized_diagnostics = Vec::new();
 820        let mut edits_since_save = content.edits_since::<T>(&self.saved_version).peekable();
 821        let mut last_edit_old_end = T::default();
 822        let mut last_edit_new_end = T::default();
 823        'outer: for entry in diagnostics {
 824            let mut start = entry.range.start;
 825            let mut end = entry.range.end;
 826
 827            // Some diagnostics are based on files on disk instead of buffers'
 828            // current contents. Adjust these diagnostics' ranges to reflect
 829            // any unsaved edits.
 830            if entry.diagnostic.is_disk_based {
 831                while let Some(edit) = edits_since_save.peek() {
 832                    if edit.old.end <= start {
 833                        last_edit_old_end = edit.old.end;
 834                        last_edit_new_end = edit.new.end;
 835                        edits_since_save.next();
 836                    } else if edit.old.start <= end && edit.old.end >= start {
 837                        continue 'outer;
 838                    } else {
 839                        break;
 840                    }
 841                }
 842
 843                let start_overshoot = start - last_edit_old_end;
 844                start = last_edit_new_end;
 845                start.add_assign(&start_overshoot);
 846
 847                let end_overshoot = end - last_edit_old_end;
 848                end = last_edit_new_end;
 849                end.add_assign(&end_overshoot);
 850            }
 851
 852            let range = start.clip(Bias::Left, content)..end.clip(Bias::Right, content);
 853            let mut range = range.start.to_point(content)..range.end.to_point(content);
 854            // Expand empty ranges by one character
 855            if range.start == range.end {
 856                range.end.column += 1;
 857                range.end = content.clip_point(range.end, Bias::Right);
 858                if range.start == range.end && range.end.column > 0 {
 859                    range.start.column -= 1;
 860                    range.start = content.clip_point(range.start, Bias::Left);
 861                }
 862            }
 863
 864            sanitized_diagnostics.push(DiagnosticEntry {
 865                range,
 866                diagnostic: entry.diagnostic,
 867            });
 868        }
 869        drop(edits_since_save);
 870
 871        let set = DiagnosticSet::new(sanitized_diagnostics, content);
 872        self.apply_diagnostic_update(set.clone(), cx);
 873        Ok(Operation::UpdateDiagnostics {
 874            diagnostics: set.iter().cloned().collect(),
 875            lamport_timestamp: self.text.lamport_clock.tick(),
 876        })
 877    }
 878
 879    fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
 880        if let Some(indent_columns) = self.compute_autoindents() {
 881            let indent_columns = cx.background().spawn(indent_columns);
 882            match cx
 883                .background()
 884                .block_with_timeout(Duration::from_micros(500), indent_columns)
 885            {
 886                Ok(indent_columns) => self.apply_autoindents(indent_columns, cx),
 887                Err(indent_columns) => {
 888                    self.pending_autoindent = Some(cx.spawn(|this, mut cx| async move {
 889                        let indent_columns = indent_columns.await;
 890                        this.update(&mut cx, |this, cx| {
 891                            this.apply_autoindents(indent_columns, cx);
 892                        });
 893                    }));
 894                }
 895            }
 896        }
 897    }
 898
 899    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, u32>>> {
 900        let max_rows_between_yields = 100;
 901        let snapshot = self.snapshot();
 902        if snapshot.language.is_none()
 903            || snapshot.tree.is_none()
 904            || self.autoindent_requests.is_empty()
 905        {
 906            return None;
 907        }
 908
 909        let autoindent_requests = self.autoindent_requests.clone();
 910        Some(async move {
 911            let mut indent_columns = BTreeMap::new();
 912            for request in autoindent_requests {
 913                let old_to_new_rows = request
 914                    .edited
 915                    .iter()
 916                    .map(|anchor| anchor.summary::<Point>(&request.before_edit).row)
 917                    .zip(
 918                        request
 919                            .edited
 920                            .iter()
 921                            .map(|anchor| anchor.summary::<Point>(&snapshot).row),
 922                    )
 923                    .collect::<BTreeMap<u32, u32>>();
 924
 925                let mut old_suggestions = HashMap::<u32, u32>::default();
 926                let old_edited_ranges =
 927                    contiguous_ranges(old_to_new_rows.keys().copied(), max_rows_between_yields);
 928                for old_edited_range in old_edited_ranges {
 929                    let suggestions = request
 930                        .before_edit
 931                        .suggest_autoindents(old_edited_range.clone())
 932                        .into_iter()
 933                        .flatten();
 934                    for (old_row, suggestion) in old_edited_range.zip(suggestions) {
 935                        let indentation_basis = old_to_new_rows
 936                            .get(&suggestion.basis_row)
 937                            .and_then(|from_row| old_suggestions.get(from_row).copied())
 938                            .unwrap_or_else(|| {
 939                                request
 940                                    .before_edit
 941                                    .indent_column_for_line(suggestion.basis_row)
 942                            });
 943                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 944                        old_suggestions.insert(
 945                            *old_to_new_rows.get(&old_row).unwrap(),
 946                            indentation_basis + delta,
 947                        );
 948                    }
 949                    yield_now().await;
 950                }
 951
 952                // At this point, old_suggestions contains the suggested indentation for all edited lines with respect to the state of the
 953                // buffer before the edit, but keyed by the row for these lines after the edits were applied.
 954                let new_edited_row_ranges =
 955                    contiguous_ranges(old_to_new_rows.values().copied(), max_rows_between_yields);
 956                for new_edited_row_range in new_edited_row_ranges {
 957                    let suggestions = snapshot
 958                        .suggest_autoindents(new_edited_row_range.clone())
 959                        .into_iter()
 960                        .flatten();
 961                    for (new_row, suggestion) in new_edited_row_range.zip(suggestions) {
 962                        let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 963                        let new_indentation = indent_columns
 964                            .get(&suggestion.basis_row)
 965                            .copied()
 966                            .unwrap_or_else(|| {
 967                                snapshot.indent_column_for_line(suggestion.basis_row)
 968                            })
 969                            + delta;
 970                        if old_suggestions
 971                            .get(&new_row)
 972                            .map_or(true, |old_indentation| new_indentation != *old_indentation)
 973                        {
 974                            indent_columns.insert(new_row, new_indentation);
 975                        }
 976                    }
 977                    yield_now().await;
 978                }
 979
 980                if let Some(inserted) = request.inserted.as_ref() {
 981                    let inserted_row_ranges = contiguous_ranges(
 982                        inserted
 983                            .iter()
 984                            .map(|range| range.to_point(&snapshot))
 985                            .flat_map(|range| range.start.row..range.end.row + 1),
 986                        max_rows_between_yields,
 987                    );
 988                    for inserted_row_range in inserted_row_ranges {
 989                        let suggestions = snapshot
 990                            .suggest_autoindents(inserted_row_range.clone())
 991                            .into_iter()
 992                            .flatten();
 993                        for (row, suggestion) in inserted_row_range.zip(suggestions) {
 994                            let delta = if suggestion.indent { INDENT_SIZE } else { 0 };
 995                            let new_indentation = indent_columns
 996                                .get(&suggestion.basis_row)
 997                                .copied()
 998                                .unwrap_or_else(|| {
 999                                    snapshot.indent_column_for_line(suggestion.basis_row)
1000                                })
1001                                + delta;
1002                            indent_columns.insert(row, new_indentation);
1003                        }
1004                        yield_now().await;
1005                    }
1006                }
1007            }
1008            indent_columns
1009        })
1010    }
1011
1012    fn apply_autoindents(
1013        &mut self,
1014        indent_columns: BTreeMap<u32, u32>,
1015        cx: &mut ModelContext<Self>,
1016    ) {
1017        self.autoindent_requests.clear();
1018        self.start_transaction();
1019        for (row, indent_column) in &indent_columns {
1020            self.set_indent_column_for_line(*row, *indent_column, cx);
1021        }
1022        self.end_transaction(cx);
1023    }
1024
1025    fn set_indent_column_for_line(&mut self, row: u32, column: u32, cx: &mut ModelContext<Self>) {
1026        let current_column = self.indent_column_for_line(row);
1027        if column > current_column {
1028            let offset = Point::new(row, 0).to_offset(&*self);
1029            self.edit(
1030                [offset..offset],
1031                " ".repeat((column - current_column) as usize),
1032                cx,
1033            );
1034        } else if column < current_column {
1035            self.edit(
1036                [Point::new(row, 0)..Point::new(row, current_column - column)],
1037                "",
1038                cx,
1039            );
1040        }
1041    }
1042
1043    pub(crate) fn diff(&self, new_text: Arc<str>, cx: &AppContext) -> Task<Diff> {
1044        // TODO: it would be nice to not allocate here.
1045        let old_text = self.text();
1046        let base_version = self.version();
1047        cx.background().spawn(async move {
1048            let changes = TextDiff::from_lines(old_text.as_str(), new_text.as_ref())
1049                .iter_all_changes()
1050                .map(|c| (c.tag(), c.value().len()))
1051                .collect::<Vec<_>>();
1052            Diff {
1053                base_version,
1054                new_text,
1055                changes,
1056            }
1057        })
1058    }
1059
1060    pub(crate) fn apply_diff(&mut self, diff: Diff, cx: &mut ModelContext<Self>) -> bool {
1061        if self.version == diff.base_version {
1062            self.start_transaction();
1063            let mut offset = 0;
1064            for (tag, len) in diff.changes {
1065                let range = offset..(offset + len);
1066                match tag {
1067                    ChangeTag::Equal => offset += len,
1068                    ChangeTag::Delete => self.edit(Some(range), "", cx),
1069                    ChangeTag::Insert => {
1070                        self.edit(Some(offset..offset), &diff.new_text[range], cx);
1071                        offset += len;
1072                    }
1073                }
1074            }
1075            self.end_transaction(cx);
1076            true
1077        } else {
1078            false
1079        }
1080    }
1081
1082    pub fn is_dirty(&self) -> bool {
1083        !self.saved_version.ge(&self.version)
1084            || self.file.as_ref().map_or(false, |file| file.is_deleted())
1085    }
1086
1087    pub fn has_conflict(&self) -> bool {
1088        !self.saved_version.ge(&self.version)
1089            && self
1090                .file
1091                .as_ref()
1092                .map_or(false, |file| file.mtime() > self.saved_mtime)
1093    }
1094
1095    pub fn subscribe(&mut self) -> Subscription {
1096        self.text.subscribe()
1097    }
1098
1099    pub fn start_transaction(&mut self) -> Option<TransactionId> {
1100        self.start_transaction_at(Instant::now())
1101    }
1102
1103    pub fn start_transaction_at(&mut self, now: Instant) -> Option<TransactionId> {
1104        self.text.start_transaction_at(now)
1105    }
1106
1107    pub fn end_transaction(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1108        self.end_transaction_at(Instant::now(), cx)
1109    }
1110
1111    pub fn end_transaction_at(
1112        &mut self,
1113        now: Instant,
1114        cx: &mut ModelContext<Self>,
1115    ) -> Option<TransactionId> {
1116        if let Some((transaction_id, start_version)) = self.text.end_transaction_at(now) {
1117            let was_dirty = start_version != self.saved_version;
1118            self.did_edit(&start_version, was_dirty, cx);
1119            Some(transaction_id)
1120        } else {
1121            None
1122        }
1123    }
1124
1125    pub fn set_active_selections(
1126        &mut self,
1127        selections: Arc<[Selection<Anchor>]>,
1128        cx: &mut ModelContext<Self>,
1129    ) {
1130        let lamport_timestamp = self.text.lamport_clock.tick();
1131        self.remote_selections.insert(
1132            self.text.replica_id(),
1133            SelectionSet {
1134                selections: selections.clone(),
1135                lamport_timestamp,
1136            },
1137        );
1138        self.send_operation(
1139            Operation::UpdateSelections {
1140                replica_id: self.text.replica_id(),
1141                selections,
1142                lamport_timestamp,
1143            },
1144            cx,
1145        );
1146    }
1147
1148    pub fn remove_active_selections(&mut self, cx: &mut ModelContext<Self>) {
1149        self.set_active_selections(Arc::from([]), cx);
1150    }
1151
1152    fn update_language_server(&mut self) {
1153        let language_server = if let Some(language_server) = self.language_server.as_mut() {
1154            language_server
1155        } else {
1156            return;
1157        };
1158        let abs_path = self
1159            .file
1160            .as_ref()
1161            .map_or(Path::new("/").to_path_buf(), |file| {
1162                file.abs_path().unwrap()
1163            });
1164
1165        let version = post_inc(&mut language_server.next_version);
1166        let snapshot = LanguageServerSnapshot {
1167            buffer_snapshot: self.text.snapshot(),
1168            version,
1169            path: Arc::from(abs_path),
1170        };
1171        language_server
1172            .pending_snapshots
1173            .insert(version, snapshot.clone());
1174        let _ = language_server
1175            .latest_snapshot
1176            .blocking_send(Some(snapshot));
1177    }
1178
1179    pub fn edit<I, S, T>(&mut self, ranges_iter: I, new_text: T, cx: &mut ModelContext<Self>)
1180    where
1181        I: IntoIterator<Item = Range<S>>,
1182        S: ToOffset,
1183        T: Into<String>,
1184    {
1185        self.edit_internal(ranges_iter, new_text, false, cx)
1186    }
1187
1188    pub fn edit_with_autoindent<I, S, T>(
1189        &mut self,
1190        ranges_iter: I,
1191        new_text: T,
1192        cx: &mut ModelContext<Self>,
1193    ) where
1194        I: IntoIterator<Item = Range<S>>,
1195        S: ToOffset,
1196        T: Into<String>,
1197    {
1198        self.edit_internal(ranges_iter, new_text, true, cx)
1199    }
1200
1201    pub fn edit_internal<I, S, T>(
1202        &mut self,
1203        ranges_iter: I,
1204        new_text: T,
1205        autoindent: bool,
1206        cx: &mut ModelContext<Self>,
1207    ) where
1208        I: IntoIterator<Item = Range<S>>,
1209        S: ToOffset,
1210        T: Into<String>,
1211    {
1212        let new_text = new_text.into();
1213
1214        // Skip invalid ranges and coalesce contiguous ones.
1215        let mut ranges: Vec<Range<usize>> = Vec::new();
1216        for range in ranges_iter {
1217            let range = range.start.to_offset(self)..range.end.to_offset(self);
1218            if !new_text.is_empty() || !range.is_empty() {
1219                if let Some(prev_range) = ranges.last_mut() {
1220                    if prev_range.end >= range.start {
1221                        prev_range.end = cmp::max(prev_range.end, range.end);
1222                    } else {
1223                        ranges.push(range);
1224                    }
1225                } else {
1226                    ranges.push(range);
1227                }
1228            }
1229        }
1230        if ranges.is_empty() {
1231            return;
1232        }
1233
1234        self.start_transaction();
1235        self.pending_autoindent.take();
1236        let autoindent_request = if autoindent && self.language.is_some() {
1237            let before_edit = self.snapshot();
1238            let edited = ranges
1239                .iter()
1240                .filter_map(|range| {
1241                    let start = range.start.to_point(self);
1242                    if new_text.starts_with('\n') && start.column == self.line_len(start.row) {
1243                        None
1244                    } else {
1245                        Some(self.anchor_before(range.start))
1246                    }
1247                })
1248                .collect();
1249            Some((before_edit, edited))
1250        } else {
1251            None
1252        };
1253
1254        let first_newline_ix = new_text.find('\n');
1255        let new_text_len = new_text.len();
1256
1257        let edit = self.text.edit(ranges.iter().cloned(), new_text);
1258
1259        if let Some((before_edit, edited)) = autoindent_request {
1260            let mut inserted = None;
1261            if let Some(first_newline_ix) = first_newline_ix {
1262                let mut delta = 0isize;
1263                inserted = Some(
1264                    ranges
1265                        .iter()
1266                        .map(|range| {
1267                            let start =
1268                                (delta + range.start as isize) as usize + first_newline_ix + 1;
1269                            let end = (delta + range.start as isize) as usize + new_text_len;
1270                            delta +=
1271                                (range.end as isize - range.start as isize) + new_text_len as isize;
1272                            self.anchor_before(start)..self.anchor_after(end)
1273                        })
1274                        .collect(),
1275                );
1276            }
1277
1278            self.autoindent_requests.push(Arc::new(AutoindentRequest {
1279                before_edit,
1280                edited,
1281                inserted,
1282            }));
1283        }
1284
1285        self.end_transaction(cx);
1286        self.send_operation(Operation::Buffer(text::Operation::Edit(edit)), cx);
1287    }
1288
1289    fn did_edit(
1290        &mut self,
1291        old_version: &clock::Global,
1292        was_dirty: bool,
1293        cx: &mut ModelContext<Self>,
1294    ) {
1295        if self.edits_since::<usize>(old_version).next().is_none() {
1296            return;
1297        }
1298
1299        self.reparse(cx);
1300        self.update_language_server();
1301
1302        cx.emit(Event::Edited);
1303        if !was_dirty {
1304            cx.emit(Event::Dirtied);
1305        }
1306        cx.notify();
1307    }
1308
1309    fn grammar(&self) -> Option<&Arc<Grammar>> {
1310        self.language.as_ref().and_then(|l| l.grammar.as_ref())
1311    }
1312
1313    pub fn apply_ops<I: IntoIterator<Item = Operation>>(
1314        &mut self,
1315        ops: I,
1316        cx: &mut ModelContext<Self>,
1317    ) -> Result<()> {
1318        self.pending_autoindent.take();
1319        let was_dirty = self.is_dirty();
1320        let old_version = self.version.clone();
1321        let mut deferred_ops = Vec::new();
1322        let buffer_ops = ops
1323            .into_iter()
1324            .filter_map(|op| match op {
1325                Operation::Buffer(op) => Some(op),
1326                _ => {
1327                    if self.can_apply_op(&op) {
1328                        self.apply_op(op, cx);
1329                    } else {
1330                        deferred_ops.push(op);
1331                    }
1332                    None
1333                }
1334            })
1335            .collect::<Vec<_>>();
1336        self.text.apply_ops(buffer_ops)?;
1337        self.deferred_ops.insert(deferred_ops);
1338        self.flush_deferred_ops(cx);
1339        self.did_edit(&old_version, was_dirty, cx);
1340        // Notify independently of whether the buffer was edited as the operations could include a
1341        // selection update.
1342        cx.notify();
1343        Ok(())
1344    }
1345
1346    fn flush_deferred_ops(&mut self, cx: &mut ModelContext<Self>) {
1347        let mut deferred_ops = Vec::new();
1348        for op in self.deferred_ops.drain().iter().cloned() {
1349            if self.can_apply_op(&op) {
1350                self.apply_op(op, cx);
1351            } else {
1352                deferred_ops.push(op);
1353            }
1354        }
1355        self.deferred_ops.insert(deferred_ops);
1356    }
1357
1358    fn can_apply_op(&self, operation: &Operation) -> bool {
1359        match operation {
1360            Operation::Buffer(_) => {
1361                unreachable!("buffer operations should never be applied at this layer")
1362            }
1363            Operation::UpdateDiagnostics {
1364                diagnostics: diagnostic_set,
1365                ..
1366            } => diagnostic_set.iter().all(|diagnostic| {
1367                self.text.can_resolve(&diagnostic.range.start)
1368                    && self.text.can_resolve(&diagnostic.range.end)
1369            }),
1370            Operation::UpdateSelections { selections, .. } => selections
1371                .iter()
1372                .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1373        }
1374    }
1375
1376    fn apply_op(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1377        match operation {
1378            Operation::Buffer(_) => {
1379                unreachable!("buffer operations should never be applied at this layer")
1380            }
1381            Operation::UpdateDiagnostics {
1382                diagnostics: diagnostic_set,
1383                ..
1384            } => {
1385                let snapshot = self.snapshot();
1386                self.apply_diagnostic_update(
1387                    DiagnosticSet::from_sorted_entries(diagnostic_set.iter().cloned(), &snapshot),
1388                    cx,
1389                );
1390            }
1391            Operation::UpdateSelections {
1392                replica_id,
1393                selections,
1394                lamport_timestamp,
1395            } => {
1396                if let Some(set) = self.remote_selections.get(&replica_id) {
1397                    if set.lamport_timestamp > lamport_timestamp {
1398                        return;
1399                    }
1400                }
1401
1402                self.remote_selections.insert(
1403                    replica_id,
1404                    SelectionSet {
1405                        selections,
1406                        lamport_timestamp,
1407                    },
1408                );
1409                self.text.lamport_clock.observe(lamport_timestamp);
1410                self.selections_update_count += 1;
1411            }
1412        }
1413    }
1414
1415    fn apply_diagnostic_update(&mut self, diagnostics: DiagnosticSet, cx: &mut ModelContext<Self>) {
1416        self.diagnostics = diagnostics;
1417        self.diagnostics_update_count += 1;
1418        cx.notify();
1419        cx.emit(Event::DiagnosticsUpdated);
1420    }
1421
1422    #[cfg(not(test))]
1423    pub fn send_operation(&mut self, operation: Operation, cx: &mut ModelContext<Self>) {
1424        if let Some(file) = &self.file {
1425            file.buffer_updated(self.remote_id(), operation, cx.as_mut());
1426        }
1427    }
1428
1429    #[cfg(test)]
1430    pub fn send_operation(&mut self, operation: Operation, _: &mut ModelContext<Self>) {
1431        self.operations.push(operation);
1432    }
1433
1434    pub fn remove_peer(&mut self, replica_id: ReplicaId, cx: &mut ModelContext<Self>) {
1435        self.remote_selections.remove(&replica_id);
1436        cx.notify();
1437    }
1438
1439    pub fn undo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1440        let was_dirty = self.is_dirty();
1441        let old_version = self.version.clone();
1442
1443        if let Some((transaction_id, operation)) = self.text.undo() {
1444            self.send_operation(Operation::Buffer(operation), cx);
1445            self.did_edit(&old_version, was_dirty, cx);
1446            Some(transaction_id)
1447        } else {
1448            None
1449        }
1450    }
1451
1452    pub fn undo_transaction(
1453        &mut self,
1454        transaction_id: TransactionId,
1455        cx: &mut ModelContext<Self>,
1456    ) -> bool {
1457        let was_dirty = self.is_dirty();
1458        let old_version = self.version.clone();
1459
1460        if let Some(operation) = self.text.undo_transaction(transaction_id) {
1461            self.send_operation(Operation::Buffer(operation), cx);
1462            self.did_edit(&old_version, was_dirty, cx);
1463            true
1464        } else {
1465            false
1466        }
1467    }
1468
1469    pub fn redo(&mut self, cx: &mut ModelContext<Self>) -> Option<TransactionId> {
1470        let was_dirty = self.is_dirty();
1471        let old_version = self.version.clone();
1472
1473        if let Some((transaction_id, operation)) = self.text.redo() {
1474            self.send_operation(Operation::Buffer(operation), cx);
1475            self.did_edit(&old_version, was_dirty, cx);
1476            Some(transaction_id)
1477        } else {
1478            None
1479        }
1480    }
1481
1482    pub fn redo_transaction(
1483        &mut self,
1484        transaction_id: TransactionId,
1485        cx: &mut ModelContext<Self>,
1486    ) -> bool {
1487        let was_dirty = self.is_dirty();
1488        let old_version = self.version.clone();
1489
1490        if let Some(operation) = self.text.redo_transaction(transaction_id) {
1491            self.send_operation(Operation::Buffer(operation), cx);
1492            self.did_edit(&old_version, was_dirty, cx);
1493            true
1494        } else {
1495            false
1496        }
1497    }
1498}
1499
1500#[cfg(any(test, feature = "test-support"))]
1501impl Buffer {
1502    pub fn set_group_interval(&mut self, group_interval: Duration) {
1503        self.text.set_group_interval(group_interval);
1504    }
1505
1506    pub fn randomly_edit<T>(
1507        &mut self,
1508        rng: &mut T,
1509        old_range_count: usize,
1510        cx: &mut ModelContext<Self>,
1511    ) where
1512        T: rand::Rng,
1513    {
1514        let mut old_ranges: Vec<Range<usize>> = Vec::new();
1515        for _ in 0..old_range_count {
1516            let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
1517            if last_end > self.len() {
1518                break;
1519            }
1520            old_ranges.push(self.text.random_byte_range(last_end, rng));
1521        }
1522        let new_text_len = rng.gen_range(0..10);
1523        let new_text: String = crate::random_char_iter::RandomCharIter::new(&mut *rng)
1524            .take(new_text_len)
1525            .collect();
1526        log::info!(
1527            "mutating buffer {} at {:?}: {:?}",
1528            self.replica_id(),
1529            old_ranges,
1530            new_text
1531        );
1532        self.edit(old_ranges.iter().cloned(), new_text.as_str(), cx);
1533    }
1534
1535    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng, cx: &mut ModelContext<Self>) {
1536        let was_dirty = self.is_dirty();
1537        let old_version = self.version.clone();
1538
1539        let ops = self.text.randomly_undo_redo(rng);
1540        if !ops.is_empty() {
1541            for op in ops {
1542                self.send_operation(Operation::Buffer(op), cx);
1543                self.did_edit(&old_version, was_dirty, cx);
1544            }
1545        }
1546    }
1547}
1548
1549impl Entity for Buffer {
1550    type Event = Event;
1551
1552    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
1553        if let Some(file) = self.file.as_ref() {
1554            file.buffer_removed(self.remote_id(), cx);
1555        }
1556    }
1557}
1558
1559impl Deref for Buffer {
1560    type Target = TextBuffer;
1561
1562    fn deref(&self) -> &Self::Target {
1563        &self.text
1564    }
1565}
1566
1567impl BufferSnapshot {
1568    fn suggest_autoindents<'a>(
1569        &'a self,
1570        row_range: Range<u32>,
1571    ) -> Option<impl Iterator<Item = IndentSuggestion> + 'a> {
1572        let mut query_cursor = QueryCursorHandle::new();
1573        if let Some((grammar, tree)) = self.grammar().zip(self.tree.as_ref()) {
1574            let prev_non_blank_row = self.prev_non_blank_row(row_range.start);
1575
1576            // Get the "indentation ranges" that intersect this row range.
1577            let indent_capture_ix = grammar.indents_query.capture_index_for_name("indent");
1578            let end_capture_ix = grammar.indents_query.capture_index_for_name("end");
1579            query_cursor.set_point_range(
1580                Point::new(prev_non_blank_row.unwrap_or(row_range.start), 0).to_ts_point()
1581                    ..Point::new(row_range.end, 0).to_ts_point(),
1582            );
1583            let mut indentation_ranges = Vec::<(Range<Point>, &'static str)>::new();
1584            for mat in query_cursor.matches(
1585                &grammar.indents_query,
1586                tree.root_node(),
1587                TextProvider(self.as_rope()),
1588            ) {
1589                let mut node_kind = "";
1590                let mut start: Option<Point> = None;
1591                let mut end: Option<Point> = None;
1592                for capture in mat.captures {
1593                    if Some(capture.index) == indent_capture_ix {
1594                        node_kind = capture.node.kind();
1595                        start.get_or_insert(Point::from_ts_point(capture.node.start_position()));
1596                        end.get_or_insert(Point::from_ts_point(capture.node.end_position()));
1597                    } else if Some(capture.index) == end_capture_ix {
1598                        end = Some(Point::from_ts_point(capture.node.start_position().into()));
1599                    }
1600                }
1601
1602                if let Some((start, end)) = start.zip(end) {
1603                    if start.row == end.row {
1604                        continue;
1605                    }
1606
1607                    let range = start..end;
1608                    match indentation_ranges.binary_search_by_key(&range.start, |r| r.0.start) {
1609                        Err(ix) => indentation_ranges.insert(ix, (range, node_kind)),
1610                        Ok(ix) => {
1611                            let prev_range = &mut indentation_ranges[ix];
1612                            prev_range.0.end = prev_range.0.end.max(range.end);
1613                        }
1614                    }
1615                }
1616            }
1617
1618            let mut prev_row = prev_non_blank_row.unwrap_or(0);
1619            Some(row_range.map(move |row| {
1620                let row_start = Point::new(row, self.indent_column_for_line(row));
1621
1622                let mut indent_from_prev_row = false;
1623                let mut outdent_to_row = u32::MAX;
1624                for (range, _node_kind) in &indentation_ranges {
1625                    if range.start.row >= row {
1626                        break;
1627                    }
1628
1629                    if range.start.row == prev_row && range.end > row_start {
1630                        indent_from_prev_row = true;
1631                    }
1632                    if range.end.row >= prev_row && range.end <= row_start {
1633                        outdent_to_row = outdent_to_row.min(range.start.row);
1634                    }
1635                }
1636
1637                let suggestion = if outdent_to_row == prev_row {
1638                    IndentSuggestion {
1639                        basis_row: prev_row,
1640                        indent: false,
1641                    }
1642                } else if indent_from_prev_row {
1643                    IndentSuggestion {
1644                        basis_row: prev_row,
1645                        indent: true,
1646                    }
1647                } else if outdent_to_row < prev_row {
1648                    IndentSuggestion {
1649                        basis_row: outdent_to_row,
1650                        indent: false,
1651                    }
1652                } else {
1653                    IndentSuggestion {
1654                        basis_row: prev_row,
1655                        indent: false,
1656                    }
1657                };
1658
1659                prev_row = row;
1660                suggestion
1661            }))
1662        } else {
1663            None
1664        }
1665    }
1666
1667    fn prev_non_blank_row(&self, mut row: u32) -> Option<u32> {
1668        while row > 0 {
1669            row -= 1;
1670            if !self.is_line_blank(row) {
1671                return Some(row);
1672            }
1673        }
1674        None
1675    }
1676
1677    pub fn chunks<'a, T: ToOffset>(
1678        &'a self,
1679        range: Range<T>,
1680        theme: Option<&'a SyntaxTheme>,
1681    ) -> BufferChunks<'a> {
1682        let range = range.start.to_offset(self)..range.end.to_offset(self);
1683
1684        let mut highlights = None;
1685        let mut diagnostic_endpoints = Vec::<DiagnosticEndpoint>::new();
1686        if let Some(theme) = theme {
1687            for entry in self.diagnostics_in_range::<_, usize>(range.clone()) {
1688                diagnostic_endpoints.push(DiagnosticEndpoint {
1689                    offset: entry.range.start,
1690                    is_start: true,
1691                    severity: entry.diagnostic.severity,
1692                });
1693                diagnostic_endpoints.push(DiagnosticEndpoint {
1694                    offset: entry.range.end,
1695                    is_start: false,
1696                    severity: entry.diagnostic.severity,
1697                });
1698            }
1699            diagnostic_endpoints
1700                .sort_unstable_by_key(|endpoint| (endpoint.offset, !endpoint.is_start));
1701
1702            if let Some((grammar, tree)) = self.grammar().zip(self.tree.as_ref()) {
1703                let mut query_cursor = QueryCursorHandle::new();
1704
1705                // TODO - add a Tree-sitter API to remove the need for this.
1706                let cursor = unsafe {
1707                    std::mem::transmute::<_, &'static mut QueryCursor>(query_cursor.deref_mut())
1708                };
1709                let captures = cursor.set_byte_range(range.clone()).captures(
1710                    &grammar.highlights_query,
1711                    tree.root_node(),
1712                    TextProvider(self.text.as_rope()),
1713                );
1714                highlights = Some(BufferChunkHighlights {
1715                    captures,
1716                    next_capture: None,
1717                    stack: Default::default(),
1718                    highlight_map: grammar.highlight_map(),
1719                    _query_cursor: query_cursor,
1720                    theme,
1721                })
1722            }
1723        }
1724
1725        let diagnostic_endpoints = diagnostic_endpoints.into_iter().peekable();
1726        let chunks = self.text.as_rope().chunks_in_range(range.clone());
1727
1728        BufferChunks {
1729            range,
1730            chunks,
1731            diagnostic_endpoints,
1732            error_depth: 0,
1733            warning_depth: 0,
1734            information_depth: 0,
1735            hint_depth: 0,
1736            highlights,
1737        }
1738    }
1739
1740    pub fn language(&self) -> Option<&Arc<Language>> {
1741        self.language.as_ref()
1742    }
1743
1744    fn grammar(&self) -> Option<&Arc<Grammar>> {
1745        self.language
1746            .as_ref()
1747            .and_then(|language| language.grammar.as_ref())
1748    }
1749
1750    pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
1751        if let Some(tree) = self.tree.as_ref() {
1752            let root = tree.root_node();
1753            let range = range.start.to_offset(self)..range.end.to_offset(self);
1754            let mut node = root.descendant_for_byte_range(range.start, range.end);
1755            while node.map_or(false, |n| n.byte_range() == range) {
1756                node = node.unwrap().parent();
1757            }
1758            node.map(|n| n.byte_range())
1759        } else {
1760            None
1761        }
1762    }
1763
1764    pub fn enclosing_bracket_ranges<T: ToOffset>(
1765        &self,
1766        range: Range<T>,
1767    ) -> Option<(Range<usize>, Range<usize>)> {
1768        let (grammar, tree) = self.grammar().zip(self.tree.as_ref())?;
1769        let open_capture_ix = grammar.brackets_query.capture_index_for_name("open")?;
1770        let close_capture_ix = grammar.brackets_query.capture_index_for_name("close")?;
1771
1772        // Find bracket pairs that *inclusively* contain the given range.
1773        let range = range.start.to_offset(self).saturating_sub(1)..range.end.to_offset(self) + 1;
1774        let mut cursor = QueryCursorHandle::new();
1775        let matches = cursor.set_byte_range(range).matches(
1776            &grammar.brackets_query,
1777            tree.root_node(),
1778            TextProvider(self.as_rope()),
1779        );
1780
1781        // Get the ranges of the innermost pair of brackets.
1782        matches
1783            .filter_map(|mat| {
1784                let open = mat.nodes_for_capture_index(open_capture_ix).next()?;
1785                let close = mat.nodes_for_capture_index(close_capture_ix).next()?;
1786                Some((open.byte_range(), close.byte_range()))
1787            })
1788            .min_by_key(|(open_range, close_range)| close_range.end - open_range.start)
1789    }
1790
1791    pub fn remote_selections_in_range<'a>(
1792        &'a self,
1793        range: Range<Anchor>,
1794    ) -> impl 'a + Iterator<Item = (ReplicaId, impl 'a + Iterator<Item = &'a Selection<Anchor>>)>
1795    {
1796        self.remote_selections
1797            .iter()
1798            .filter(|(replica_id, set)| {
1799                **replica_id != self.text.replica_id() && !set.selections.is_empty()
1800            })
1801            .map(move |(replica_id, set)| {
1802                let start_ix = match set.selections.binary_search_by(|probe| {
1803                    probe
1804                        .end
1805                        .cmp(&range.start, self)
1806                        .unwrap()
1807                        .then(Ordering::Greater)
1808                }) {
1809                    Ok(ix) | Err(ix) => ix,
1810                };
1811                let end_ix = match set.selections.binary_search_by(|probe| {
1812                    probe
1813                        .start
1814                        .cmp(&range.end, self)
1815                        .unwrap()
1816                        .then(Ordering::Less)
1817                }) {
1818                    Ok(ix) | Err(ix) => ix,
1819                };
1820
1821                (*replica_id, set.selections[start_ix..end_ix].iter())
1822            })
1823    }
1824
1825    pub fn diagnostics_in_range<'a, T, O>(
1826        &'a self,
1827        search_range: Range<T>,
1828    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
1829    where
1830        T: 'a + Clone + ToOffset,
1831        O: 'a + FromAnchor,
1832    {
1833        self.diagnostics.range(search_range.clone(), self, true)
1834    }
1835
1836    pub fn diagnostic_groups(&self) -> Vec<DiagnosticGroup<Anchor>> {
1837        let mut groups = Vec::new();
1838        self.diagnostics.groups(&mut groups, self);
1839        groups
1840    }
1841
1842    pub fn diagnostic_group<'a, O>(
1843        &'a self,
1844        group_id: usize,
1845    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
1846    where
1847        O: 'a + FromAnchor,
1848    {
1849        self.diagnostics.group(group_id, self)
1850    }
1851
1852    pub fn diagnostics_update_count(&self) -> usize {
1853        self.diagnostics_update_count
1854    }
1855
1856    pub fn parse_count(&self) -> usize {
1857        self.parse_count
1858    }
1859
1860    pub fn selections_update_count(&self) -> usize {
1861        self.selections_update_count
1862    }
1863}
1864
1865impl Clone for BufferSnapshot {
1866    fn clone(&self) -> Self {
1867        Self {
1868            text: self.text.clone(),
1869            tree: self.tree.clone(),
1870            remote_selections: self.remote_selections.clone(),
1871            diagnostics: self.diagnostics.clone(),
1872            selections_update_count: self.selections_update_count,
1873            diagnostics_update_count: self.diagnostics_update_count,
1874            is_parsing: self.is_parsing,
1875            language: self.language.clone(),
1876            parse_count: self.parse_count,
1877        }
1878    }
1879}
1880
1881impl Deref for BufferSnapshot {
1882    type Target = text::BufferSnapshot;
1883
1884    fn deref(&self) -> &Self::Target {
1885        &self.text
1886    }
1887}
1888
1889impl<'a> tree_sitter::TextProvider<'a> for TextProvider<'a> {
1890    type I = ByteChunks<'a>;
1891
1892    fn text(&mut self, node: tree_sitter::Node) -> Self::I {
1893        ByteChunks(self.0.chunks_in_range(node.byte_range()))
1894    }
1895}
1896
1897struct ByteChunks<'a>(rope::Chunks<'a>);
1898
1899impl<'a> Iterator for ByteChunks<'a> {
1900    type Item = &'a [u8];
1901
1902    fn next(&mut self) -> Option<Self::Item> {
1903        self.0.next().map(str::as_bytes)
1904    }
1905}
1906
1907unsafe impl<'a> Send for BufferChunks<'a> {}
1908
1909impl<'a> BufferChunks<'a> {
1910    pub fn seek(&mut self, offset: usize) {
1911        self.range.start = offset;
1912        self.chunks.seek(self.range.start);
1913        if let Some(highlights) = self.highlights.as_mut() {
1914            highlights
1915                .stack
1916                .retain(|(end_offset, _)| *end_offset > offset);
1917            if let Some((mat, capture_ix)) = &highlights.next_capture {
1918                let capture = mat.captures[*capture_ix as usize];
1919                if offset >= capture.node.start_byte() {
1920                    let next_capture_end = capture.node.end_byte();
1921                    if offset < next_capture_end {
1922                        highlights.stack.push((
1923                            next_capture_end,
1924                            highlights.highlight_map.get(capture.index),
1925                        ));
1926                    }
1927                    highlights.next_capture.take();
1928                }
1929            }
1930            highlights.captures.set_byte_range(self.range.clone());
1931        }
1932    }
1933
1934    pub fn offset(&self) -> usize {
1935        self.range.start
1936    }
1937
1938    fn update_diagnostic_depths(&mut self, endpoint: DiagnosticEndpoint) {
1939        let depth = match endpoint.severity {
1940            DiagnosticSeverity::ERROR => &mut self.error_depth,
1941            DiagnosticSeverity::WARNING => &mut self.warning_depth,
1942            DiagnosticSeverity::INFORMATION => &mut self.information_depth,
1943            DiagnosticSeverity::HINT => &mut self.hint_depth,
1944            _ => return,
1945        };
1946        if endpoint.is_start {
1947            *depth += 1;
1948        } else {
1949            *depth -= 1;
1950        }
1951    }
1952
1953    fn current_diagnostic_severity(&mut self) -> Option<DiagnosticSeverity> {
1954        if self.error_depth > 0 {
1955            Some(DiagnosticSeverity::ERROR)
1956        } else if self.warning_depth > 0 {
1957            Some(DiagnosticSeverity::WARNING)
1958        } else if self.information_depth > 0 {
1959            Some(DiagnosticSeverity::INFORMATION)
1960        } else if self.hint_depth > 0 {
1961            Some(DiagnosticSeverity::HINT)
1962        } else {
1963            None
1964        }
1965    }
1966}
1967
1968impl<'a> Iterator for BufferChunks<'a> {
1969    type Item = Chunk<'a>;
1970
1971    fn next(&mut self) -> Option<Self::Item> {
1972        let mut next_capture_start = usize::MAX;
1973        let mut next_diagnostic_endpoint = usize::MAX;
1974
1975        if let Some(highlights) = self.highlights.as_mut() {
1976            while let Some((parent_capture_end, _)) = highlights.stack.last() {
1977                if *parent_capture_end <= self.range.start {
1978                    highlights.stack.pop();
1979                } else {
1980                    break;
1981                }
1982            }
1983
1984            if highlights.next_capture.is_none() {
1985                highlights.next_capture = highlights.captures.next();
1986            }
1987
1988            while let Some((mat, capture_ix)) = highlights.next_capture.as_ref() {
1989                let capture = mat.captures[*capture_ix as usize];
1990                if self.range.start < capture.node.start_byte() {
1991                    next_capture_start = capture.node.start_byte();
1992                    break;
1993                } else {
1994                    let highlight_id = highlights.highlight_map.get(capture.index);
1995                    highlights
1996                        .stack
1997                        .push((capture.node.end_byte(), highlight_id));
1998                    highlights.next_capture = highlights.captures.next();
1999                }
2000            }
2001        }
2002
2003        while let Some(endpoint) = self.diagnostic_endpoints.peek().copied() {
2004            if endpoint.offset <= self.range.start {
2005                self.update_diagnostic_depths(endpoint);
2006                self.diagnostic_endpoints.next();
2007            } else {
2008                next_diagnostic_endpoint = endpoint.offset;
2009                break;
2010            }
2011        }
2012
2013        if let Some(chunk) = self.chunks.peek() {
2014            let chunk_start = self.range.start;
2015            let mut chunk_end = (self.chunks.offset() + chunk.len())
2016                .min(next_capture_start)
2017                .min(next_diagnostic_endpoint);
2018            let mut highlight_style = None;
2019            if let Some(highlights) = self.highlights.as_ref() {
2020                if let Some((parent_capture_end, parent_highlight_id)) = highlights.stack.last() {
2021                    chunk_end = chunk_end.min(*parent_capture_end);
2022                    highlight_style = parent_highlight_id.style(highlights.theme);
2023                }
2024            }
2025
2026            let slice =
2027                &chunk[chunk_start - self.chunks.offset()..chunk_end - self.chunks.offset()];
2028            self.range.start = chunk_end;
2029            if self.range.start == self.chunks.offset() + chunk.len() {
2030                self.chunks.next().unwrap();
2031            }
2032
2033            Some(Chunk {
2034                text: slice,
2035                highlight_style,
2036                diagnostic: self.current_diagnostic_severity(),
2037            })
2038        } else {
2039            None
2040        }
2041    }
2042}
2043
2044impl QueryCursorHandle {
2045    fn new() -> Self {
2046        QueryCursorHandle(Some(
2047            QUERY_CURSORS
2048                .lock()
2049                .pop()
2050                .unwrap_or_else(|| QueryCursor::new()),
2051        ))
2052    }
2053}
2054
2055impl Deref for QueryCursorHandle {
2056    type Target = QueryCursor;
2057
2058    fn deref(&self) -> &Self::Target {
2059        self.0.as_ref().unwrap()
2060    }
2061}
2062
2063impl DerefMut for QueryCursorHandle {
2064    fn deref_mut(&mut self) -> &mut Self::Target {
2065        self.0.as_mut().unwrap()
2066    }
2067}
2068
2069impl Drop for QueryCursorHandle {
2070    fn drop(&mut self) {
2071        let mut cursor = self.0.take().unwrap();
2072        cursor.set_byte_range(0..usize::MAX);
2073        cursor.set_point_range(Point::zero().to_ts_point()..Point::MAX.to_ts_point());
2074        QUERY_CURSORS.lock().push(cursor)
2075    }
2076}
2077
2078trait ToTreeSitterPoint {
2079    fn to_ts_point(self) -> tree_sitter::Point;
2080    fn from_ts_point(point: tree_sitter::Point) -> Self;
2081}
2082
2083impl ToTreeSitterPoint for Point {
2084    fn to_ts_point(self) -> tree_sitter::Point {
2085        tree_sitter::Point::new(self.row as usize, self.column as usize)
2086    }
2087
2088    fn from_ts_point(point: tree_sitter::Point) -> Self {
2089        Point::new(point.row as u32, point.column as u32)
2090    }
2091}
2092
2093impl operation_queue::Operation for Operation {
2094    fn lamport_timestamp(&self) -> clock::Lamport {
2095        match self {
2096            Operation::Buffer(_) => {
2097                unreachable!("buffer operations should never be deferred at this layer")
2098            }
2099            Operation::UpdateDiagnostics {
2100                lamport_timestamp, ..
2101            }
2102            | Operation::UpdateSelections {
2103                lamport_timestamp, ..
2104            } => *lamport_timestamp,
2105        }
2106    }
2107}
2108
2109impl Default for Diagnostic {
2110    fn default() -> Self {
2111        Self {
2112            code: Default::default(),
2113            severity: DiagnosticSeverity::ERROR,
2114            message: Default::default(),
2115            group_id: Default::default(),
2116            is_primary: Default::default(),
2117            is_valid: true,
2118            is_disk_based: false,
2119        }
2120    }
2121}
2122
2123pub fn contiguous_ranges(
2124    values: impl Iterator<Item = u32>,
2125    max_len: usize,
2126) -> impl Iterator<Item = Range<u32>> {
2127    let mut values = values.into_iter();
2128    let mut current_range: Option<Range<u32>> = None;
2129    std::iter::from_fn(move || loop {
2130        if let Some(value) = values.next() {
2131            if let Some(range) = &mut current_range {
2132                if value == range.end && range.len() < max_len {
2133                    range.end += 1;
2134                    continue;
2135                }
2136            }
2137
2138            let prev_range = current_range.clone();
2139            current_range = Some(value..(value + 1));
2140            if prev_range.is_some() {
2141                return prev_range;
2142            }
2143        } else {
2144            return current_range.take();
2145        }
2146    })
2147}