inlay_hint_cache.rs

   1use std::{
   2    cmp,
   3    ops::{ControlFlow, Range},
   4    sync::Arc,
   5    time::Duration,
   6};
   7
   8use crate::{
   9    display_map::Inlay, Anchor, Editor, ExcerptId, InlayId, MultiBuffer, MultiBufferSnapshot,
  10};
  11use anyhow::Context;
  12use clock::Global;
  13use futures::future;
  14use gpui::{Model, ModelContext, Task, ViewContext};
  15use language::{language_settings::InlayHintKind, Buffer, BufferSnapshot};
  16use parking_lot::RwLock;
  17use project::{InlayHint, ResolveState};
  18
  19use collections::{hash_map, HashMap, HashSet};
  20use language::language_settings::InlayHintSettings;
  21use smol::lock::Semaphore;
  22use sum_tree::Bias;
  23use text::{ToOffset, ToPoint};
  24use util::post_inc;
  25
  26pub struct InlayHintCache {
  27    hints: HashMap<ExcerptId, Arc<RwLock<CachedExcerptHints>>>,
  28    allowed_hint_kinds: HashSet<Option<InlayHintKind>>,
  29    version: usize,
  30    pub(super) enabled: bool,
  31    update_tasks: HashMap<ExcerptId, TasksForRanges>,
  32    lsp_request_limiter: Arc<Semaphore>,
  33}
  34
  35#[derive(Debug)]
  36struct TasksForRanges {
  37    tasks: Vec<Task<()>>,
  38    sorted_ranges: Vec<Range<language::Anchor>>,
  39}
  40
  41#[derive(Debug)]
  42pub struct CachedExcerptHints {
  43    version: usize,
  44    buffer_version: Global,
  45    buffer_id: u64,
  46    ordered_hints: Vec<InlayId>,
  47    hints_by_id: HashMap<InlayId, InlayHint>,
  48}
  49
  50#[derive(Debug, Clone, Copy)]
  51pub enum InvalidationStrategy {
  52    RefreshRequested,
  53    BufferEdited,
  54    None,
  55}
  56
  57#[derive(Debug, Default)]
  58pub struct InlaySplice {
  59    pub to_remove: Vec<InlayId>,
  60    pub to_insert: Vec<Inlay>,
  61}
  62
  63#[derive(Debug)]
  64struct ExcerptHintsUpdate {
  65    excerpt_id: ExcerptId,
  66    remove_from_visible: Vec<InlayId>,
  67    remove_from_cache: HashSet<InlayId>,
  68    add_to_cache: Vec<InlayHint>,
  69}
  70
  71#[derive(Debug, Clone, Copy)]
  72struct ExcerptQuery {
  73    buffer_id: u64,
  74    excerpt_id: ExcerptId,
  75    cache_version: usize,
  76    invalidate: InvalidationStrategy,
  77    reason: &'static str,
  78}
  79
  80impl InvalidationStrategy {
  81    fn should_invalidate(&self) -> bool {
  82        matches!(
  83            self,
  84            InvalidationStrategy::RefreshRequested | InvalidationStrategy::BufferEdited
  85        )
  86    }
  87}
  88
  89impl TasksForRanges {
  90    fn new(query_ranges: QueryRanges, task: Task<()>) -> Self {
  91        let mut sorted_ranges = Vec::new();
  92        sorted_ranges.extend(query_ranges.before_visible);
  93        sorted_ranges.extend(query_ranges.visible);
  94        sorted_ranges.extend(query_ranges.after_visible);
  95        Self {
  96            tasks: vec![task],
  97            sorted_ranges,
  98        }
  99    }
 100
 101    fn update_cached_tasks(
 102        &mut self,
 103        buffer_snapshot: &BufferSnapshot,
 104        query_ranges: QueryRanges,
 105        invalidate: InvalidationStrategy,
 106        spawn_task: impl FnOnce(QueryRanges) -> Task<()>,
 107    ) {
 108        let query_ranges = if invalidate.should_invalidate() {
 109            self.tasks.clear();
 110            self.sorted_ranges.clear();
 111            query_ranges
 112        } else {
 113            let mut non_cached_query_ranges = query_ranges;
 114            non_cached_query_ranges.before_visible = non_cached_query_ranges
 115                .before_visible
 116                .into_iter()
 117                .flat_map(|query_range| {
 118                    self.remove_cached_ranges_from_query(buffer_snapshot, query_range)
 119                })
 120                .collect();
 121            non_cached_query_ranges.visible = non_cached_query_ranges
 122                .visible
 123                .into_iter()
 124                .flat_map(|query_range| {
 125                    self.remove_cached_ranges_from_query(buffer_snapshot, query_range)
 126                })
 127                .collect();
 128            non_cached_query_ranges.after_visible = non_cached_query_ranges
 129                .after_visible
 130                .into_iter()
 131                .flat_map(|query_range| {
 132                    self.remove_cached_ranges_from_query(buffer_snapshot, query_range)
 133                })
 134                .collect();
 135            non_cached_query_ranges
 136        };
 137
 138        if !query_ranges.is_empty() {
 139            self.tasks.push(spawn_task(query_ranges));
 140        }
 141    }
 142
 143    fn remove_cached_ranges_from_query(
 144        &mut self,
 145        buffer_snapshot: &BufferSnapshot,
 146        query_range: Range<language::Anchor>,
 147    ) -> Vec<Range<language::Anchor>> {
 148        let mut ranges_to_query = Vec::new();
 149        let mut latest_cached_range = None::<&mut Range<language::Anchor>>;
 150        for cached_range in self
 151            .sorted_ranges
 152            .iter_mut()
 153            .skip_while(|cached_range| {
 154                cached_range
 155                    .end
 156                    .cmp(&query_range.start, buffer_snapshot)
 157                    .is_lt()
 158            })
 159            .take_while(|cached_range| {
 160                cached_range
 161                    .start
 162                    .cmp(&query_range.end, buffer_snapshot)
 163                    .is_le()
 164            })
 165        {
 166            match latest_cached_range {
 167                Some(latest_cached_range) => {
 168                    if latest_cached_range.end.offset.saturating_add(1) < cached_range.start.offset
 169                    {
 170                        ranges_to_query.push(latest_cached_range.end..cached_range.start);
 171                        cached_range.start = latest_cached_range.end;
 172                    }
 173                }
 174                None => {
 175                    if query_range
 176                        .start
 177                        .cmp(&cached_range.start, buffer_snapshot)
 178                        .is_lt()
 179                    {
 180                        ranges_to_query.push(query_range.start..cached_range.start);
 181                        cached_range.start = query_range.start;
 182                    }
 183                }
 184            }
 185            latest_cached_range = Some(cached_range);
 186        }
 187
 188        match latest_cached_range {
 189            Some(latest_cached_range) => {
 190                if latest_cached_range.end.offset.saturating_add(1) < query_range.end.offset {
 191                    ranges_to_query.push(latest_cached_range.end..query_range.end);
 192                    latest_cached_range.end = query_range.end;
 193                }
 194            }
 195            None => {
 196                ranges_to_query.push(query_range.clone());
 197                self.sorted_ranges.push(query_range);
 198                self.sorted_ranges
 199                    .sort_by(|range_a, range_b| range_a.start.cmp(&range_b.start, buffer_snapshot));
 200            }
 201        }
 202
 203        ranges_to_query
 204    }
 205
 206    fn invalidate_range(&mut self, buffer: &BufferSnapshot, range: &Range<language::Anchor>) {
 207        self.sorted_ranges = self
 208            .sorted_ranges
 209            .drain(..)
 210            .filter_map(|mut cached_range| {
 211                if cached_range.start.cmp(&range.end, buffer).is_gt()
 212                    || cached_range.end.cmp(&range.start, buffer).is_lt()
 213                {
 214                    Some(vec![cached_range])
 215                } else if cached_range.start.cmp(&range.start, buffer).is_ge()
 216                    && cached_range.end.cmp(&range.end, buffer).is_le()
 217                {
 218                    None
 219                } else if range.start.cmp(&cached_range.start, buffer).is_ge()
 220                    && range.end.cmp(&cached_range.end, buffer).is_le()
 221                {
 222                    Some(vec![
 223                        cached_range.start..range.start,
 224                        range.end..cached_range.end,
 225                    ])
 226                } else if cached_range.start.cmp(&range.start, buffer).is_ge() {
 227                    cached_range.start = range.end;
 228                    Some(vec![cached_range])
 229                } else {
 230                    cached_range.end = range.start;
 231                    Some(vec![cached_range])
 232                }
 233            })
 234            .flatten()
 235            .collect();
 236    }
 237}
 238
 239impl InlayHintCache {
 240    pub fn new(inlay_hint_settings: InlayHintSettings) -> Self {
 241        Self {
 242            allowed_hint_kinds: inlay_hint_settings.enabled_inlay_hint_kinds(),
 243            enabled: inlay_hint_settings.enabled,
 244            hints: HashMap::default(),
 245            update_tasks: HashMap::default(),
 246            version: 0,
 247            lsp_request_limiter: Arc::new(Semaphore::new(MAX_CONCURRENT_LSP_REQUESTS)),
 248        }
 249    }
 250
 251    pub fn update_settings(
 252        &mut self,
 253        multi_buffer: &Model<MultiBuffer>,
 254        new_hint_settings: InlayHintSettings,
 255        visible_hints: Vec<Inlay>,
 256        cx: &mut ViewContext<Editor>,
 257    ) -> ControlFlow<Option<InlaySplice>> {
 258        let new_allowed_hint_kinds = new_hint_settings.enabled_inlay_hint_kinds();
 259        match (self.enabled, new_hint_settings.enabled) {
 260            (false, false) => {
 261                self.allowed_hint_kinds = new_allowed_hint_kinds;
 262                ControlFlow::Break(None)
 263            }
 264            (true, true) => {
 265                if new_allowed_hint_kinds == self.allowed_hint_kinds {
 266                    ControlFlow::Break(None)
 267                } else {
 268                    let new_splice = self.new_allowed_hint_kinds_splice(
 269                        multi_buffer,
 270                        &visible_hints,
 271                        &new_allowed_hint_kinds,
 272                        cx,
 273                    );
 274                    if new_splice.is_some() {
 275                        self.version += 1;
 276                        self.allowed_hint_kinds = new_allowed_hint_kinds;
 277                    }
 278                    ControlFlow::Break(new_splice)
 279                }
 280            }
 281            (true, false) => {
 282                self.enabled = new_hint_settings.enabled;
 283                self.allowed_hint_kinds = new_allowed_hint_kinds;
 284                if self.hints.is_empty() {
 285                    ControlFlow::Break(None)
 286                } else {
 287                    self.clear();
 288                    ControlFlow::Break(Some(InlaySplice {
 289                        to_remove: visible_hints.iter().map(|inlay| inlay.id).collect(),
 290                        to_insert: Vec::new(),
 291                    }))
 292                }
 293            }
 294            (false, true) => {
 295                self.enabled = new_hint_settings.enabled;
 296                self.allowed_hint_kinds = new_allowed_hint_kinds;
 297                ControlFlow::Continue(())
 298            }
 299        }
 300    }
 301
 302    pub fn spawn_hint_refresh(
 303        &mut self,
 304        reason: &'static str,
 305        excerpts_to_query: HashMap<ExcerptId, (Model<Buffer>, Global, Range<usize>)>,
 306        invalidate: InvalidationStrategy,
 307        cx: &mut ViewContext<Editor>,
 308    ) -> Option<InlaySplice> {
 309        if !self.enabled {
 310            return None;
 311        }
 312
 313        let mut invalidated_hints = Vec::new();
 314        if invalidate.should_invalidate() {
 315            self.update_tasks
 316                .retain(|task_excerpt_id, _| excerpts_to_query.contains_key(task_excerpt_id));
 317            self.hints.retain(|cached_excerpt, cached_hints| {
 318                let retain = excerpts_to_query.contains_key(cached_excerpt);
 319                if !retain {
 320                    invalidated_hints.extend(cached_hints.read().ordered_hints.iter().copied());
 321                }
 322                retain
 323            });
 324        }
 325        if excerpts_to_query.is_empty() && invalidated_hints.is_empty() {
 326            return None;
 327        }
 328
 329        let cache_version = self.version + 1;
 330        cx.spawn(|editor, mut cx| async move {
 331            editor
 332                .update(&mut cx, |editor, cx| {
 333                    spawn_new_update_tasks(
 334                        editor,
 335                        reason,
 336                        excerpts_to_query,
 337                        invalidate,
 338                        cache_version,
 339                        cx,
 340                    )
 341                })
 342                .ok();
 343        })
 344        .detach();
 345
 346        if invalidated_hints.is_empty() {
 347            None
 348        } else {
 349            Some(InlaySplice {
 350                to_remove: invalidated_hints,
 351                to_insert: Vec::new(),
 352            })
 353        }
 354    }
 355
 356    fn new_allowed_hint_kinds_splice(
 357        &self,
 358        multi_buffer: &Model<MultiBuffer>,
 359        visible_hints: &[Inlay],
 360        new_kinds: &HashSet<Option<InlayHintKind>>,
 361        cx: &mut ViewContext<Editor>,
 362    ) -> Option<InlaySplice> {
 363        let old_kinds = &self.allowed_hint_kinds;
 364        if new_kinds == old_kinds {
 365            return None;
 366        }
 367
 368        let mut to_remove = Vec::new();
 369        let mut to_insert = Vec::new();
 370        let mut shown_hints_to_remove = visible_hints.iter().fold(
 371            HashMap::<ExcerptId, Vec<(Anchor, InlayId)>>::default(),
 372            |mut current_hints, inlay| {
 373                current_hints
 374                    .entry(inlay.position.excerpt_id)
 375                    .or_default()
 376                    .push((inlay.position, inlay.id));
 377                current_hints
 378            },
 379        );
 380
 381        let multi_buffer = multi_buffer.read(cx);
 382        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 383
 384        for (excerpt_id, excerpt_cached_hints) in &self.hints {
 385            let shown_excerpt_hints_to_remove =
 386                shown_hints_to_remove.entry(*excerpt_id).or_default();
 387            let excerpt_cached_hints = excerpt_cached_hints.read();
 388            let mut excerpt_cache = excerpt_cached_hints.ordered_hints.iter().fuse().peekable();
 389            shown_excerpt_hints_to_remove.retain(|(shown_anchor, shown_hint_id)| {
 390                let Some(buffer) = shown_anchor
 391                    .buffer_id
 392                    .and_then(|buffer_id| multi_buffer.buffer(buffer_id))
 393                else {
 394                    return false;
 395                };
 396                let buffer_snapshot = buffer.read(cx).snapshot();
 397                loop {
 398                    match excerpt_cache.peek() {
 399                        Some(&cached_hint_id) => {
 400                            let cached_hint = &excerpt_cached_hints.hints_by_id[cached_hint_id];
 401                            if cached_hint_id == shown_hint_id {
 402                                excerpt_cache.next();
 403                                return !new_kinds.contains(&cached_hint.kind);
 404                            }
 405
 406                            match cached_hint
 407                                .position
 408                                .cmp(&shown_anchor.text_anchor, &buffer_snapshot)
 409                            {
 410                                cmp::Ordering::Less | cmp::Ordering::Equal => {
 411                                    if !old_kinds.contains(&cached_hint.kind)
 412                                        && new_kinds.contains(&cached_hint.kind)
 413                                    {
 414                                        to_insert.push(Inlay::hint(
 415                                            cached_hint_id.id(),
 416                                            multi_buffer_snapshot.anchor_in_excerpt(
 417                                                *excerpt_id,
 418                                                cached_hint.position,
 419                                            ),
 420                                            &cached_hint,
 421                                        ));
 422                                    }
 423                                    excerpt_cache.next();
 424                                }
 425                                cmp::Ordering::Greater => return true,
 426                            }
 427                        }
 428                        None => return true,
 429                    }
 430                }
 431            });
 432
 433            for cached_hint_id in excerpt_cache {
 434                let maybe_missed_cached_hint = &excerpt_cached_hints.hints_by_id[cached_hint_id];
 435                let cached_hint_kind = maybe_missed_cached_hint.kind;
 436                if !old_kinds.contains(&cached_hint_kind) && new_kinds.contains(&cached_hint_kind) {
 437                    to_insert.push(Inlay::hint(
 438                        cached_hint_id.id(),
 439                        multi_buffer_snapshot
 440                            .anchor_in_excerpt(*excerpt_id, maybe_missed_cached_hint.position),
 441                        &maybe_missed_cached_hint,
 442                    ));
 443                }
 444            }
 445        }
 446
 447        to_remove.extend(
 448            shown_hints_to_remove
 449                .into_values()
 450                .flatten()
 451                .map(|(_, hint_id)| hint_id),
 452        );
 453        if to_remove.is_empty() && to_insert.is_empty() {
 454            None
 455        } else {
 456            Some(InlaySplice {
 457                to_remove,
 458                to_insert,
 459            })
 460        }
 461    }
 462
 463    pub fn remove_excerpts(&mut self, excerpts_removed: Vec<ExcerptId>) -> Option<InlaySplice> {
 464        let mut to_remove = Vec::new();
 465        for excerpt_to_remove in excerpts_removed {
 466            self.update_tasks.remove(&excerpt_to_remove);
 467            if let Some(cached_hints) = self.hints.remove(&excerpt_to_remove) {
 468                let cached_hints = cached_hints.read();
 469                to_remove.extend(cached_hints.ordered_hints.iter().copied());
 470            }
 471        }
 472        if to_remove.is_empty() {
 473            None
 474        } else {
 475            self.version += 1;
 476            Some(InlaySplice {
 477                to_remove,
 478                to_insert: Vec::new(),
 479            })
 480        }
 481    }
 482
 483    pub fn clear(&mut self) {
 484        if !self.update_tasks.is_empty() || !self.hints.is_empty() {
 485            self.version += 1;
 486        }
 487        self.update_tasks.clear();
 488        self.hints.clear();
 489    }
 490
 491    pub fn hint_by_id(&self, excerpt_id: ExcerptId, hint_id: InlayId) -> Option<InlayHint> {
 492        self.hints
 493            .get(&excerpt_id)?
 494            .read()
 495            .hints_by_id
 496            .get(&hint_id)
 497            .cloned()
 498    }
 499
 500    pub fn hints(&self) -> Vec<InlayHint> {
 501        let mut hints = Vec::new();
 502        for excerpt_hints in self.hints.values() {
 503            let excerpt_hints = excerpt_hints.read();
 504            hints.extend(
 505                excerpt_hints
 506                    .ordered_hints
 507                    .iter()
 508                    .map(|id| &excerpt_hints.hints_by_id[id])
 509                    .cloned(),
 510            );
 511        }
 512        hints
 513    }
 514
 515    pub fn version(&self) -> usize {
 516        self.version
 517    }
 518
 519    pub fn spawn_hint_resolve(
 520        &self,
 521        buffer_id: u64,
 522        excerpt_id: ExcerptId,
 523        id: InlayId,
 524        cx: &mut ViewContext<'_, Editor>,
 525    ) {
 526        if let Some(excerpt_hints) = self.hints.get(&excerpt_id) {
 527            let mut guard = excerpt_hints.write();
 528            if let Some(cached_hint) = guard.hints_by_id.get_mut(&id) {
 529                if let ResolveState::CanResolve(server_id, _) = &cached_hint.resolve_state {
 530                    let hint_to_resolve = cached_hint.clone();
 531                    let server_id = *server_id;
 532                    cached_hint.resolve_state = ResolveState::Resolving;
 533                    drop(guard);
 534                    cx.spawn(|editor, mut cx| async move {
 535                        let resolved_hint_task = editor.update(&mut cx, |editor, cx| {
 536                            editor
 537                                .buffer()
 538                                .read(cx)
 539                                .buffer(buffer_id)
 540                                .and_then(|buffer| {
 541                                    let project = editor.project.as_ref()?;
 542                                    Some(project.update(cx, |project, cx| {
 543                                        project.resolve_inlay_hint(
 544                                            hint_to_resolve,
 545                                            buffer,
 546                                            server_id,
 547                                            cx,
 548                                        )
 549                                    }))
 550                                })
 551                        })?;
 552                        if let Some(resolved_hint_task) = resolved_hint_task {
 553                            let mut resolved_hint =
 554                                resolved_hint_task.await.context("hint resolve task")?;
 555                            editor.update(&mut cx, |editor, _| {
 556                                if let Some(excerpt_hints) =
 557                                    editor.inlay_hint_cache.hints.get(&excerpt_id)
 558                                {
 559                                    let mut guard = excerpt_hints.write();
 560                                    if let Some(cached_hint) = guard.hints_by_id.get_mut(&id) {
 561                                        if cached_hint.resolve_state == ResolveState::Resolving {
 562                                            resolved_hint.resolve_state = ResolveState::Resolved;
 563                                            *cached_hint = resolved_hint;
 564                                        }
 565                                    }
 566                                }
 567                            })?;
 568                        }
 569
 570                        anyhow::Ok(())
 571                    })
 572                    .detach_and_log_err(cx);
 573                }
 574            }
 575        }
 576    }
 577}
 578
 579fn spawn_new_update_tasks(
 580    editor: &mut Editor,
 581    reason: &'static str,
 582    excerpts_to_query: HashMap<ExcerptId, (Model<Buffer>, Global, Range<usize>)>,
 583    invalidate: InvalidationStrategy,
 584    update_cache_version: usize,
 585    cx: &mut ViewContext<'_, Editor>,
 586) {
 587    let visible_hints = Arc::new(editor.visible_inlay_hints(cx));
 588    for (excerpt_id, (excerpt_buffer, new_task_buffer_version, excerpt_visible_range)) in
 589        excerpts_to_query
 590    {
 591        if excerpt_visible_range.is_empty() {
 592            continue;
 593        }
 594        let buffer = excerpt_buffer.read(cx);
 595        let buffer_id = buffer.remote_id();
 596        let buffer_snapshot = buffer.snapshot();
 597        if buffer_snapshot
 598            .version()
 599            .changed_since(&new_task_buffer_version)
 600        {
 601            continue;
 602        }
 603
 604        let cached_excerpt_hints = editor.inlay_hint_cache.hints.get(&excerpt_id).cloned();
 605        if let Some(cached_excerpt_hints) = &cached_excerpt_hints {
 606            let cached_excerpt_hints = cached_excerpt_hints.read();
 607            let cached_buffer_version = &cached_excerpt_hints.buffer_version;
 608            if cached_excerpt_hints.version > update_cache_version
 609                || cached_buffer_version.changed_since(&new_task_buffer_version)
 610            {
 611                continue;
 612            }
 613        };
 614
 615        let (multi_buffer_snapshot, Some(query_ranges)) =
 616            editor.buffer.update(cx, |multi_buffer, cx| {
 617                (
 618                    multi_buffer.snapshot(cx),
 619                    determine_query_ranges(
 620                        multi_buffer,
 621                        excerpt_id,
 622                        &excerpt_buffer,
 623                        excerpt_visible_range,
 624                        cx,
 625                    ),
 626                )
 627            })
 628        else {
 629            return;
 630        };
 631        let query = ExcerptQuery {
 632            buffer_id,
 633            excerpt_id,
 634            cache_version: update_cache_version,
 635            invalidate,
 636            reason,
 637        };
 638
 639        let new_update_task = |query_ranges| {
 640            new_update_task(
 641                query,
 642                query_ranges,
 643                multi_buffer_snapshot,
 644                buffer_snapshot.clone(),
 645                Arc::clone(&visible_hints),
 646                cached_excerpt_hints,
 647                Arc::clone(&editor.inlay_hint_cache.lsp_request_limiter),
 648                cx,
 649            )
 650        };
 651
 652        match editor.inlay_hint_cache.update_tasks.entry(excerpt_id) {
 653            hash_map::Entry::Occupied(mut o) => {
 654                o.get_mut().update_cached_tasks(
 655                    &buffer_snapshot,
 656                    query_ranges,
 657                    invalidate,
 658                    new_update_task,
 659                );
 660            }
 661            hash_map::Entry::Vacant(v) => {
 662                v.insert(TasksForRanges::new(
 663                    query_ranges.clone(),
 664                    new_update_task(query_ranges),
 665                ));
 666            }
 667        }
 668    }
 669}
 670
 671#[derive(Debug, Clone)]
 672struct QueryRanges {
 673    before_visible: Vec<Range<language::Anchor>>,
 674    visible: Vec<Range<language::Anchor>>,
 675    after_visible: Vec<Range<language::Anchor>>,
 676}
 677
 678impl QueryRanges {
 679    fn is_empty(&self) -> bool {
 680        self.before_visible.is_empty() && self.visible.is_empty() && self.after_visible.is_empty()
 681    }
 682}
 683
 684fn determine_query_ranges(
 685    multi_buffer: &mut MultiBuffer,
 686    excerpt_id: ExcerptId,
 687    excerpt_buffer: &Model<Buffer>,
 688    excerpt_visible_range: Range<usize>,
 689    cx: &mut ModelContext<'_, MultiBuffer>,
 690) -> Option<QueryRanges> {
 691    let full_excerpt_range = multi_buffer
 692        .excerpts_for_buffer(excerpt_buffer, cx)
 693        .into_iter()
 694        .find(|(id, _)| id == &excerpt_id)
 695        .map(|(_, range)| range.context)?;
 696    let buffer = excerpt_buffer.read(cx);
 697    let snapshot = buffer.snapshot();
 698    let excerpt_visible_len = excerpt_visible_range.end - excerpt_visible_range.start;
 699
 700    let visible_range = if excerpt_visible_range.start == excerpt_visible_range.end {
 701        return None;
 702    } else {
 703        vec![
 704            buffer.anchor_before(snapshot.clip_offset(excerpt_visible_range.start, Bias::Left))
 705                ..buffer.anchor_after(snapshot.clip_offset(excerpt_visible_range.end, Bias::Right)),
 706        ]
 707    };
 708
 709    let full_excerpt_range_end_offset = full_excerpt_range.end.to_offset(&snapshot);
 710    let after_visible_range_start = excerpt_visible_range
 711        .end
 712        .saturating_add(1)
 713        .min(full_excerpt_range_end_offset)
 714        .min(buffer.len());
 715    let after_visible_range = if after_visible_range_start == full_excerpt_range_end_offset {
 716        Vec::new()
 717    } else {
 718        let after_range_end_offset = after_visible_range_start
 719            .saturating_add(excerpt_visible_len)
 720            .min(full_excerpt_range_end_offset)
 721            .min(buffer.len());
 722        vec![
 723            buffer.anchor_before(snapshot.clip_offset(after_visible_range_start, Bias::Left))
 724                ..buffer.anchor_after(snapshot.clip_offset(after_range_end_offset, Bias::Right)),
 725        ]
 726    };
 727
 728    let full_excerpt_range_start_offset = full_excerpt_range.start.to_offset(&snapshot);
 729    let before_visible_range_end = excerpt_visible_range
 730        .start
 731        .saturating_sub(1)
 732        .max(full_excerpt_range_start_offset);
 733    let before_visible_range = if before_visible_range_end == full_excerpt_range_start_offset {
 734        Vec::new()
 735    } else {
 736        let before_range_start_offset = before_visible_range_end
 737            .saturating_sub(excerpt_visible_len)
 738            .max(full_excerpt_range_start_offset);
 739        vec![
 740            buffer.anchor_before(snapshot.clip_offset(before_range_start_offset, Bias::Left))
 741                ..buffer.anchor_after(snapshot.clip_offset(before_visible_range_end, Bias::Right)),
 742        ]
 743    };
 744
 745    Some(QueryRanges {
 746        before_visible: before_visible_range,
 747        visible: visible_range,
 748        after_visible: after_visible_range,
 749    })
 750}
 751
 752const MAX_CONCURRENT_LSP_REQUESTS: usize = 5;
 753const INVISIBLE_RANGES_HINTS_REQUEST_DELAY_MILLIS: u64 = 400;
 754
 755fn new_update_task(
 756    query: ExcerptQuery,
 757    query_ranges: QueryRanges,
 758    multi_buffer_snapshot: MultiBufferSnapshot,
 759    buffer_snapshot: BufferSnapshot,
 760    visible_hints: Arc<Vec<Inlay>>,
 761    cached_excerpt_hints: Option<Arc<RwLock<CachedExcerptHints>>>,
 762    lsp_request_limiter: Arc<Semaphore>,
 763    cx: &mut ViewContext<'_, Editor>,
 764) -> Task<()> {
 765    cx.spawn(|editor, mut cx| async move {
 766        let closure_cx = cx.clone();
 767        let fetch_and_update_hints = |invalidate, range| {
 768            fetch_and_update_hints(
 769                editor.clone(),
 770                multi_buffer_snapshot.clone(),
 771                buffer_snapshot.clone(),
 772                Arc::clone(&visible_hints),
 773                cached_excerpt_hints.as_ref().map(Arc::clone),
 774                query,
 775                invalidate,
 776                range,
 777                Arc::clone(&lsp_request_limiter),
 778                closure_cx.clone(),
 779            )
 780        };
 781        let visible_range_update_results = future::join_all(query_ranges.visible.into_iter().map(
 782            |visible_range| async move {
 783                (
 784                    visible_range.clone(),
 785                    fetch_and_update_hints(query.invalidate.should_invalidate(), visible_range)
 786                        .await,
 787                )
 788            },
 789        ))
 790        .await;
 791
 792        let hint_delay = cx.background_executor().timer(Duration::from_millis(
 793            INVISIBLE_RANGES_HINTS_REQUEST_DELAY_MILLIS,
 794        ));
 795
 796        let mut query_range_failed = |range: &Range<language::Anchor>, e: anyhow::Error| {
 797            log::error!("inlay hint update task for range {range:?} failed: {e:#}");
 798            editor
 799                .update(&mut cx, |editor, _| {
 800                    if let Some(task_ranges) = editor
 801                        .inlay_hint_cache
 802                        .update_tasks
 803                        .get_mut(&query.excerpt_id)
 804                    {
 805                        task_ranges.invalidate_range(&buffer_snapshot, &range);
 806                    }
 807                })
 808                .ok()
 809        };
 810
 811        for (range, result) in visible_range_update_results {
 812            if let Err(e) = result {
 813                query_range_failed(&range, e);
 814            }
 815        }
 816
 817        hint_delay.await;
 818        let invisible_range_update_results = future::join_all(
 819            query_ranges
 820                .before_visible
 821                .into_iter()
 822                .chain(query_ranges.after_visible.into_iter())
 823                .map(|invisible_range| async move {
 824                    (
 825                        invisible_range.clone(),
 826                        fetch_and_update_hints(false, invisible_range).await,
 827                    )
 828                }),
 829        )
 830        .await;
 831        for (range, result) in invisible_range_update_results {
 832            if let Err(e) = result {
 833                query_range_failed(&range, e);
 834            }
 835        }
 836    })
 837}
 838
 839async fn fetch_and_update_hints(
 840    editor: gpui::WeakView<Editor>,
 841    multi_buffer_snapshot: MultiBufferSnapshot,
 842    buffer_snapshot: BufferSnapshot,
 843    visible_hints: Arc<Vec<Inlay>>,
 844    cached_excerpt_hints: Option<Arc<RwLock<CachedExcerptHints>>>,
 845    query: ExcerptQuery,
 846    invalidate: bool,
 847    fetch_range: Range<language::Anchor>,
 848    lsp_request_limiter: Arc<Semaphore>,
 849    mut cx: gpui::AsyncWindowContext,
 850) -> anyhow::Result<()> {
 851    let (lsp_request_guard, got_throttled) = if query.invalidate.should_invalidate() {
 852        (None, false)
 853    } else {
 854        match lsp_request_limiter.try_acquire() {
 855            Some(guard) => (Some(guard), false),
 856            None => (Some(lsp_request_limiter.acquire().await), true),
 857        }
 858    };
 859    let fetch_range_to_log =
 860        fetch_range.start.to_point(&buffer_snapshot)..fetch_range.end.to_point(&buffer_snapshot);
 861    let inlay_hints_fetch_task = editor
 862        .update(&mut cx, |editor, cx| {
 863            if got_throttled {
 864                let query_not_around_visible_range = match editor.excerpts_for_inlay_hints_query(None, cx).remove(&query.excerpt_id) {
 865                    Some((_, _, current_visible_range)) => {
 866                        let visible_offset_length = current_visible_range.len();
 867                        let double_visible_range = current_visible_range
 868                            .start
 869                            .saturating_sub(visible_offset_length)
 870                            ..current_visible_range
 871                                .end
 872                                .saturating_add(visible_offset_length)
 873                                .min(buffer_snapshot.len());
 874                        !double_visible_range
 875                            .contains(&fetch_range.start.to_offset(&buffer_snapshot))
 876                            && !double_visible_range
 877                                .contains(&fetch_range.end.to_offset(&buffer_snapshot))
 878                    },
 879                    None => true,
 880                };
 881                if query_not_around_visible_range {
 882                    log::trace!("Fetching inlay hints for range {fetch_range_to_log:?} got throttled and fell off the current visible range, skipping.");
 883                    if let Some(task_ranges) = editor
 884                        .inlay_hint_cache
 885                        .update_tasks
 886                        .get_mut(&query.excerpt_id)
 887                    {
 888                        task_ranges.invalidate_range(&buffer_snapshot, &fetch_range);
 889                    }
 890                    return None;
 891                }
 892            }
 893            editor
 894                .buffer()
 895                .read(cx)
 896                .buffer(query.buffer_id)
 897                .and_then(|buffer| {
 898                    let project = editor.project.as_ref()?;
 899                    Some(project.update(cx, |project, cx| {
 900                        project.inlay_hints(buffer, fetch_range.clone(), cx)
 901                    }))
 902                })
 903        })
 904        .ok()
 905        .flatten();
 906    let new_hints = match inlay_hints_fetch_task {
 907        Some(fetch_task) => {
 908            log::debug!(
 909                "Fetching inlay hints for range {fetch_range_to_log:?}, reason: {query_reason}, invalidate: {invalidate}",
 910                query_reason = query.reason,
 911            );
 912            log::trace!(
 913                "Currently visible hints: {visible_hints:?}, cached hints present: {}",
 914                cached_excerpt_hints.is_some(),
 915            );
 916            fetch_task.await.context("inlay hint fetch task")?
 917        }
 918        None => return Ok(()),
 919    };
 920    drop(lsp_request_guard);
 921    log::debug!(
 922        "Fetched {} hints for range {fetch_range_to_log:?}",
 923        new_hints.len()
 924    );
 925    log::trace!("Fetched hints: {new_hints:?}");
 926
 927    let background_task_buffer_snapshot = buffer_snapshot.clone();
 928    let backround_fetch_range = fetch_range.clone();
 929    let new_update = cx
 930        .background_executor()
 931        .spawn(async move {
 932            calculate_hint_updates(
 933                query.excerpt_id,
 934                invalidate,
 935                backround_fetch_range,
 936                new_hints,
 937                &background_task_buffer_snapshot,
 938                cached_excerpt_hints,
 939                &visible_hints,
 940            )
 941        })
 942        .await;
 943    if let Some(new_update) = new_update {
 944        log::debug!(
 945            "Applying update for range {fetch_range_to_log:?}: remove from editor: {}, remove from cache: {}, add to cache: {}",
 946            new_update.remove_from_visible.len(),
 947            new_update.remove_from_cache.len(),
 948            new_update.add_to_cache.len()
 949        );
 950        log::trace!("New update: {new_update:?}");
 951        editor
 952            .update(&mut cx, |editor, cx| {
 953                apply_hint_update(
 954                    editor,
 955                    new_update,
 956                    query,
 957                    invalidate,
 958                    buffer_snapshot,
 959                    multi_buffer_snapshot,
 960                    cx,
 961                );
 962            })
 963            .ok();
 964    }
 965    Ok(())
 966}
 967
 968fn calculate_hint_updates(
 969    excerpt_id: ExcerptId,
 970    invalidate: bool,
 971    fetch_range: Range<language::Anchor>,
 972    new_excerpt_hints: Vec<InlayHint>,
 973    buffer_snapshot: &BufferSnapshot,
 974    cached_excerpt_hints: Option<Arc<RwLock<CachedExcerptHints>>>,
 975    visible_hints: &[Inlay],
 976) -> Option<ExcerptHintsUpdate> {
 977    let mut add_to_cache = Vec::<InlayHint>::new();
 978    let mut excerpt_hints_to_persist = HashMap::default();
 979    for new_hint in new_excerpt_hints {
 980        if !contains_position(&fetch_range, new_hint.position, buffer_snapshot) {
 981            continue;
 982        }
 983        let missing_from_cache = match &cached_excerpt_hints {
 984            Some(cached_excerpt_hints) => {
 985                let cached_excerpt_hints = cached_excerpt_hints.read();
 986                match cached_excerpt_hints
 987                    .ordered_hints
 988                    .binary_search_by(|probe| {
 989                        cached_excerpt_hints.hints_by_id[probe]
 990                            .position
 991                            .cmp(&new_hint.position, buffer_snapshot)
 992                    }) {
 993                    Ok(ix) => {
 994                        let mut missing_from_cache = true;
 995                        for id in &cached_excerpt_hints.ordered_hints[ix..] {
 996                            let cached_hint = &cached_excerpt_hints.hints_by_id[id];
 997                            if new_hint
 998                                .position
 999                                .cmp(&cached_hint.position, buffer_snapshot)
1000                                .is_gt()
1001                            {
1002                                break;
1003                            }
1004                            if cached_hint == &new_hint {
1005                                excerpt_hints_to_persist.insert(*id, cached_hint.kind);
1006                                missing_from_cache = false;
1007                            }
1008                        }
1009                        missing_from_cache
1010                    }
1011                    Err(_) => true,
1012                }
1013            }
1014            None => true,
1015        };
1016        if missing_from_cache {
1017            add_to_cache.push(new_hint);
1018        }
1019    }
1020
1021    let mut remove_from_visible = Vec::new();
1022    let mut remove_from_cache = HashSet::default();
1023    if invalidate {
1024        remove_from_visible.extend(
1025            visible_hints
1026                .iter()
1027                .filter(|hint| hint.position.excerpt_id == excerpt_id)
1028                .map(|inlay_hint| inlay_hint.id)
1029                .filter(|hint_id| !excerpt_hints_to_persist.contains_key(hint_id)),
1030        );
1031
1032        if let Some(cached_excerpt_hints) = &cached_excerpt_hints {
1033            let cached_excerpt_hints = cached_excerpt_hints.read();
1034            remove_from_cache.extend(
1035                cached_excerpt_hints
1036                    .ordered_hints
1037                    .iter()
1038                    .filter(|cached_inlay_id| {
1039                        !excerpt_hints_to_persist.contains_key(cached_inlay_id)
1040                    })
1041                    .copied(),
1042            );
1043        }
1044    }
1045
1046    if remove_from_visible.is_empty() && remove_from_cache.is_empty() && add_to_cache.is_empty() {
1047        None
1048    } else {
1049        Some(ExcerptHintsUpdate {
1050            excerpt_id,
1051            remove_from_visible,
1052            remove_from_cache,
1053            add_to_cache,
1054        })
1055    }
1056}
1057
1058fn contains_position(
1059    range: &Range<language::Anchor>,
1060    position: language::Anchor,
1061    buffer_snapshot: &BufferSnapshot,
1062) -> bool {
1063    range.start.cmp(&position, buffer_snapshot).is_le()
1064        && range.end.cmp(&position, buffer_snapshot).is_ge()
1065}
1066
1067fn apply_hint_update(
1068    editor: &mut Editor,
1069    new_update: ExcerptHintsUpdate,
1070    query: ExcerptQuery,
1071    invalidate: bool,
1072    buffer_snapshot: BufferSnapshot,
1073    multi_buffer_snapshot: MultiBufferSnapshot,
1074    cx: &mut ViewContext<'_, Editor>,
1075) {
1076    let cached_excerpt_hints = editor
1077        .inlay_hint_cache
1078        .hints
1079        .entry(new_update.excerpt_id)
1080        .or_insert_with(|| {
1081            Arc::new(RwLock::new(CachedExcerptHints {
1082                version: query.cache_version,
1083                buffer_version: buffer_snapshot.version().clone(),
1084                buffer_id: query.buffer_id,
1085                ordered_hints: Vec::new(),
1086                hints_by_id: HashMap::default(),
1087            }))
1088        });
1089    let mut cached_excerpt_hints = cached_excerpt_hints.write();
1090    match query.cache_version.cmp(&cached_excerpt_hints.version) {
1091        cmp::Ordering::Less => return,
1092        cmp::Ordering::Greater | cmp::Ordering::Equal => {
1093            cached_excerpt_hints.version = query.cache_version;
1094        }
1095    }
1096
1097    let mut cached_inlays_changed = !new_update.remove_from_cache.is_empty();
1098    cached_excerpt_hints
1099        .ordered_hints
1100        .retain(|hint_id| !new_update.remove_from_cache.contains(hint_id));
1101    cached_excerpt_hints
1102        .hints_by_id
1103        .retain(|hint_id, _| !new_update.remove_from_cache.contains(hint_id));
1104    let mut splice = InlaySplice {
1105        to_remove: new_update.remove_from_visible,
1106        to_insert: Vec::new(),
1107    };
1108    for new_hint in new_update.add_to_cache {
1109        let insert_position = match cached_excerpt_hints
1110            .ordered_hints
1111            .binary_search_by(|probe| {
1112                cached_excerpt_hints.hints_by_id[probe]
1113                    .position
1114                    .cmp(&new_hint.position, &buffer_snapshot)
1115            }) {
1116            Ok(i) => {
1117                let mut insert_position = Some(i);
1118                for id in &cached_excerpt_hints.ordered_hints[i..] {
1119                    let cached_hint = &cached_excerpt_hints.hints_by_id[id];
1120                    if new_hint
1121                        .position
1122                        .cmp(&cached_hint.position, &buffer_snapshot)
1123                        .is_gt()
1124                    {
1125                        break;
1126                    }
1127                    if cached_hint.text() == new_hint.text() {
1128                        insert_position = None;
1129                        break;
1130                    }
1131                }
1132                insert_position
1133            }
1134            Err(i) => Some(i),
1135        };
1136
1137        if let Some(insert_position) = insert_position {
1138            let new_inlay_id = post_inc(&mut editor.next_inlay_id);
1139            if editor
1140                .inlay_hint_cache
1141                .allowed_hint_kinds
1142                .contains(&new_hint.kind)
1143            {
1144                let new_hint_position =
1145                    multi_buffer_snapshot.anchor_in_excerpt(query.excerpt_id, new_hint.position);
1146                splice
1147                    .to_insert
1148                    .push(Inlay::hint(new_inlay_id, new_hint_position, &new_hint));
1149            }
1150            let new_id = InlayId::Hint(new_inlay_id);
1151            cached_excerpt_hints.hints_by_id.insert(new_id, new_hint);
1152            cached_excerpt_hints
1153                .ordered_hints
1154                .insert(insert_position, new_id);
1155            cached_inlays_changed = true;
1156        }
1157    }
1158    cached_excerpt_hints.buffer_version = buffer_snapshot.version().clone();
1159    drop(cached_excerpt_hints);
1160
1161    if invalidate {
1162        let mut outdated_excerpt_caches = HashSet::default();
1163        for (excerpt_id, excerpt_hints) in &editor.inlay_hint_cache().hints {
1164            let excerpt_hints = excerpt_hints.read();
1165            if excerpt_hints.buffer_id == query.buffer_id
1166                && excerpt_id != &query.excerpt_id
1167                && buffer_snapshot
1168                    .version()
1169                    .changed_since(&excerpt_hints.buffer_version)
1170            {
1171                outdated_excerpt_caches.insert(*excerpt_id);
1172                splice
1173                    .to_remove
1174                    .extend(excerpt_hints.ordered_hints.iter().copied());
1175            }
1176        }
1177        cached_inlays_changed |= !outdated_excerpt_caches.is_empty();
1178        editor
1179            .inlay_hint_cache
1180            .hints
1181            .retain(|excerpt_id, _| !outdated_excerpt_caches.contains(excerpt_id));
1182    }
1183
1184    let InlaySplice {
1185        to_remove,
1186        to_insert,
1187    } = splice;
1188    let displayed_inlays_changed = !to_remove.is_empty() || !to_insert.is_empty();
1189    if cached_inlays_changed || displayed_inlays_changed {
1190        editor.inlay_hint_cache.version += 1;
1191    }
1192    if displayed_inlays_changed {
1193        editor.splice_inlay_hints(to_remove, to_insert, cx)
1194    }
1195}
1196
1197#[cfg(test)]
1198pub mod tests {
1199    use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
1200
1201    use crate::{
1202        scroll::{autoscroll::Autoscroll, scroll_amount::ScrollAmount},
1203        ExcerptRange,
1204    };
1205    use futures::StreamExt;
1206    use gpui::{Context, TestAppContext, WindowHandle};
1207    use itertools::Itertools;
1208    use language::{
1209        language_settings::AllLanguageSettingsContent, FakeLspAdapter, Language, LanguageConfig,
1210    };
1211    use lsp::FakeLanguageServer;
1212    use parking_lot::Mutex;
1213    use project::{FakeFs, Project};
1214    use serde_json::json;
1215    use settings::SettingsStore;
1216    use text::{Point, ToPoint};
1217
1218    use crate::editor_tests::update_test_language_settings;
1219
1220    use super::*;
1221
1222    #[gpui::test]
1223    async fn test_basic_cache_update_with_duplicate_hints(cx: &mut gpui::TestAppContext) {
1224        let allowed_hint_kinds = HashSet::from_iter([None, Some(InlayHintKind::Type)]);
1225        init_test(cx, |settings| {
1226            settings.defaults.inlay_hints = Some(InlayHintSettings {
1227                enabled: true,
1228                show_type_hints: allowed_hint_kinds.contains(&Some(InlayHintKind::Type)),
1229                show_parameter_hints: allowed_hint_kinds.contains(&Some(InlayHintKind::Parameter)),
1230                show_other_hints: allowed_hint_kinds.contains(&None),
1231            })
1232        });
1233
1234        let (file_with_hints, editor, fake_server) = prepare_test_objects(cx).await;
1235        let lsp_request_count = Arc::new(AtomicU32::new(0));
1236        fake_server
1237            .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1238                let task_lsp_request_count = Arc::clone(&lsp_request_count);
1239                async move {
1240                    assert_eq!(
1241                        params.text_document.uri,
1242                        lsp::Url::from_file_path(file_with_hints).unwrap(),
1243                    );
1244                    let current_call_id =
1245                        Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::SeqCst);
1246                    let mut new_hints = Vec::with_capacity(2 * current_call_id as usize);
1247                    for _ in 0..2 {
1248                        let mut i = current_call_id;
1249                        loop {
1250                            new_hints.push(lsp::InlayHint {
1251                                position: lsp::Position::new(0, i),
1252                                label: lsp::InlayHintLabel::String(i.to_string()),
1253                                kind: None,
1254                                text_edits: None,
1255                                tooltip: None,
1256                                padding_left: None,
1257                                padding_right: None,
1258                                data: None,
1259                            });
1260                            if i == 0 {
1261                                break;
1262                            }
1263                            i -= 1;
1264                        }
1265                    }
1266
1267                    Ok(Some(new_hints))
1268                }
1269            })
1270            .next()
1271            .await;
1272        cx.executor().run_until_parked();
1273
1274        let mut edits_made = 1;
1275        _ = editor.update(cx, |editor, cx| {
1276            let expected_hints = vec!["0".to_string()];
1277            assert_eq!(
1278                expected_hints,
1279                cached_hint_labels(editor),
1280                "Should get its first hints when opening the editor"
1281            );
1282            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1283            let inlay_cache = editor.inlay_hint_cache();
1284            assert_eq!(
1285                inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
1286                "Cache should use editor settings to get the allowed hint kinds"
1287            );
1288            assert_eq!(
1289                inlay_cache.version, edits_made,
1290                "The editor update the cache version after every cache/view change"
1291            );
1292        });
1293
1294        _ = editor.update(cx, |editor, cx| {
1295            editor.change_selections(None, cx, |s| s.select_ranges([13..13]));
1296            editor.handle_input("some change", cx);
1297            edits_made += 1;
1298        });
1299        cx.executor().run_until_parked();
1300        _ = editor.update(cx, |editor, cx| {
1301            let expected_hints = vec!["0".to_string(), "1".to_string()];
1302            assert_eq!(
1303                expected_hints,
1304                cached_hint_labels(editor),
1305                "Should get new hints after an edit"
1306            );
1307            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1308            let inlay_cache = editor.inlay_hint_cache();
1309            assert_eq!(
1310                inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
1311                "Cache should use editor settings to get the allowed hint kinds"
1312            );
1313            assert_eq!(
1314                inlay_cache.version, edits_made,
1315                "The editor update the cache version after every cache/view change"
1316            );
1317        });
1318
1319        fake_server
1320            .request::<lsp::request::InlayHintRefreshRequest>(())
1321            .await
1322            .expect("inlay refresh request failed");
1323        edits_made += 1;
1324        cx.executor().run_until_parked();
1325        _ = editor.update(cx, |editor, cx| {
1326            let expected_hints = vec!["0".to_string(), "1".to_string(), "2".to_string()];
1327            assert_eq!(
1328                expected_hints,
1329                cached_hint_labels(editor),
1330                "Should get new hints after hint refresh/ request"
1331            );
1332            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1333            let inlay_cache = editor.inlay_hint_cache();
1334            assert_eq!(
1335                inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
1336                "Cache should use editor settings to get the allowed hint kinds"
1337            );
1338            assert_eq!(
1339                inlay_cache.version, edits_made,
1340                "The editor update the cache version after every cache/view change"
1341            );
1342        });
1343    }
1344
1345    #[gpui::test]
1346    async fn test_cache_update_on_lsp_completion_tasks(cx: &mut gpui::TestAppContext) {
1347        init_test(cx, |settings| {
1348            settings.defaults.inlay_hints = Some(InlayHintSettings {
1349                enabled: true,
1350                show_type_hints: true,
1351                show_parameter_hints: true,
1352                show_other_hints: true,
1353            })
1354        });
1355
1356        let (file_with_hints, editor, fake_server) = prepare_test_objects(cx).await;
1357        let lsp_request_count = Arc::new(AtomicU32::new(0));
1358        fake_server
1359            .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1360                let task_lsp_request_count = Arc::clone(&lsp_request_count);
1361                async move {
1362                    assert_eq!(
1363                        params.text_document.uri,
1364                        lsp::Url::from_file_path(file_with_hints).unwrap(),
1365                    );
1366                    let current_call_id =
1367                        Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::SeqCst);
1368                    Ok(Some(vec![lsp::InlayHint {
1369                        position: lsp::Position::new(0, current_call_id),
1370                        label: lsp::InlayHintLabel::String(current_call_id.to_string()),
1371                        kind: None,
1372                        text_edits: None,
1373                        tooltip: None,
1374                        padding_left: None,
1375                        padding_right: None,
1376                        data: None,
1377                    }]))
1378                }
1379            })
1380            .next()
1381            .await;
1382        cx.executor().run_until_parked();
1383
1384        let mut edits_made = 1;
1385        _ = editor.update(cx, |editor, cx| {
1386            let expected_hints = vec!["0".to_string()];
1387            assert_eq!(
1388                expected_hints,
1389                cached_hint_labels(editor),
1390                "Should get its first hints when opening the editor"
1391            );
1392            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1393            assert_eq!(
1394                editor.inlay_hint_cache().version,
1395                edits_made,
1396                "The editor update the cache version after every cache/view change"
1397            );
1398        });
1399
1400        let progress_token = "test_progress_token";
1401        fake_server
1402            .request::<lsp::request::WorkDoneProgressCreate>(lsp::WorkDoneProgressCreateParams {
1403                token: lsp::ProgressToken::String(progress_token.to_string()),
1404            })
1405            .await
1406            .expect("work done progress create request failed");
1407        cx.executor().run_until_parked();
1408        fake_server.notify::<lsp::notification::Progress>(lsp::ProgressParams {
1409            token: lsp::ProgressToken::String(progress_token.to_string()),
1410            value: lsp::ProgressParamsValue::WorkDone(lsp::WorkDoneProgress::Begin(
1411                lsp::WorkDoneProgressBegin::default(),
1412            )),
1413        });
1414        cx.executor().run_until_parked();
1415
1416        _ = editor.update(cx, |editor, cx| {
1417            let expected_hints = vec!["0".to_string()];
1418            assert_eq!(
1419                expected_hints,
1420                cached_hint_labels(editor),
1421                "Should not update hints while the work task is running"
1422            );
1423            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1424            assert_eq!(
1425                editor.inlay_hint_cache().version,
1426                edits_made,
1427                "Should not update the cache while the work task is running"
1428            );
1429        });
1430
1431        fake_server.notify::<lsp::notification::Progress>(lsp::ProgressParams {
1432            token: lsp::ProgressToken::String(progress_token.to_string()),
1433            value: lsp::ProgressParamsValue::WorkDone(lsp::WorkDoneProgress::End(
1434                lsp::WorkDoneProgressEnd::default(),
1435            )),
1436        });
1437        cx.executor().run_until_parked();
1438
1439        edits_made += 1;
1440        _ = editor.update(cx, |editor, cx| {
1441            let expected_hints = vec!["1".to_string()];
1442            assert_eq!(
1443                expected_hints,
1444                cached_hint_labels(editor),
1445                "New hints should be queried after the work task is done"
1446            );
1447            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1448            assert_eq!(
1449                editor.inlay_hint_cache().version,
1450                edits_made,
1451                "Cache version should udpate once after the work task is done"
1452            );
1453        });
1454    }
1455
1456    #[gpui::test]
1457    async fn test_no_hint_updates_for_unrelated_language_files(cx: &mut gpui::TestAppContext) {
1458        init_test(cx, |settings| {
1459            settings.defaults.inlay_hints = Some(InlayHintSettings {
1460                enabled: true,
1461                show_type_hints: true,
1462                show_parameter_hints: true,
1463                show_other_hints: true,
1464            })
1465        });
1466
1467        let fs = FakeFs::new(cx.background_executor.clone());
1468        fs.insert_tree(
1469                    "/a",
1470                    json!({
1471                        "main.rs": "fn main() { a } // and some long comment to ensure inlays are not trimmed out",
1472                        "other.md": "Test md file with some text",
1473                    }),
1474                )
1475                .await;
1476        let project = Project::test(fs, ["/a".as_ref()], cx).await;
1477
1478        let mut rs_fake_servers = None;
1479        let mut md_fake_servers = None;
1480        for (name, path_suffix) in [("Rust", "rs"), ("Markdown", "md")] {
1481            let mut language = Language::new(
1482                LanguageConfig {
1483                    name: name.into(),
1484                    path_suffixes: vec![path_suffix.to_string()],
1485                    ..Default::default()
1486                },
1487                Some(tree_sitter_rust::language()),
1488            );
1489            let fake_servers = language
1490                .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
1491                    name,
1492                    capabilities: lsp::ServerCapabilities {
1493                        inlay_hint_provider: Some(lsp::OneOf::Left(true)),
1494                        ..Default::default()
1495                    },
1496                    ..Default::default()
1497                }))
1498                .await;
1499            match name {
1500                "Rust" => rs_fake_servers = Some(fake_servers),
1501                "Markdown" => md_fake_servers = Some(fake_servers),
1502                _ => unreachable!(),
1503            }
1504            project.update(cx, |project, _| {
1505                project.languages().add(Arc::new(language));
1506            });
1507        }
1508
1509        let rs_buffer = project
1510            .update(cx, |project, cx| {
1511                project.open_local_buffer("/a/main.rs", cx)
1512            })
1513            .await
1514            .unwrap();
1515        cx.executor().run_until_parked();
1516        cx.executor().start_waiting();
1517        let rs_fake_server = rs_fake_servers.unwrap().next().await.unwrap();
1518        let rs_editor =
1519            cx.add_window(|cx| Editor::for_buffer(rs_buffer, Some(project.clone()), cx));
1520        let rs_lsp_request_count = Arc::new(AtomicU32::new(0));
1521        rs_fake_server
1522            .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1523                let task_lsp_request_count = Arc::clone(&rs_lsp_request_count);
1524                async move {
1525                    assert_eq!(
1526                        params.text_document.uri,
1527                        lsp::Url::from_file_path("/a/main.rs").unwrap(),
1528                    );
1529                    let i = Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::SeqCst);
1530                    Ok(Some(vec![lsp::InlayHint {
1531                        position: lsp::Position::new(0, i),
1532                        label: lsp::InlayHintLabel::String(i.to_string()),
1533                        kind: None,
1534                        text_edits: None,
1535                        tooltip: None,
1536                        padding_left: None,
1537                        padding_right: None,
1538                        data: None,
1539                    }]))
1540                }
1541            })
1542            .next()
1543            .await;
1544        cx.executor().run_until_parked();
1545        _ = rs_editor.update(cx, |editor, cx| {
1546            let expected_hints = vec!["0".to_string()];
1547            assert_eq!(
1548                expected_hints,
1549                cached_hint_labels(editor),
1550                "Should get its first hints when opening the editor"
1551            );
1552            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1553            assert_eq!(
1554                editor.inlay_hint_cache().version,
1555                1,
1556                "Rust editor update the cache version after every cache/view change"
1557            );
1558        });
1559
1560        cx.executor().run_until_parked();
1561        let md_buffer = project
1562            .update(cx, |project, cx| {
1563                project.open_local_buffer("/a/other.md", cx)
1564            })
1565            .await
1566            .unwrap();
1567        cx.executor().run_until_parked();
1568        cx.executor().start_waiting();
1569        let md_fake_server = md_fake_servers.unwrap().next().await.unwrap();
1570        let md_editor = cx.add_window(|cx| Editor::for_buffer(md_buffer, Some(project), cx));
1571        let md_lsp_request_count = Arc::new(AtomicU32::new(0));
1572        md_fake_server
1573            .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1574                let task_lsp_request_count = Arc::clone(&md_lsp_request_count);
1575                async move {
1576                    assert_eq!(
1577                        params.text_document.uri,
1578                        lsp::Url::from_file_path("/a/other.md").unwrap(),
1579                    );
1580                    let i = Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::SeqCst);
1581                    Ok(Some(vec![lsp::InlayHint {
1582                        position: lsp::Position::new(0, i),
1583                        label: lsp::InlayHintLabel::String(i.to_string()),
1584                        kind: None,
1585                        text_edits: None,
1586                        tooltip: None,
1587                        padding_left: None,
1588                        padding_right: None,
1589                        data: None,
1590                    }]))
1591                }
1592            })
1593            .next()
1594            .await;
1595        cx.executor().run_until_parked();
1596        _ = md_editor.update(cx, |editor, cx| {
1597            let expected_hints = vec!["0".to_string()];
1598            assert_eq!(
1599                expected_hints,
1600                cached_hint_labels(editor),
1601                "Markdown editor should have a separate verison, repeating Rust editor rules"
1602            );
1603            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1604            assert_eq!(editor.inlay_hint_cache().version, 1);
1605        });
1606
1607        _ = rs_editor.update(cx, |editor, cx| {
1608            editor.change_selections(None, cx, |s| s.select_ranges([13..13]));
1609            editor.handle_input("some rs change", cx);
1610        });
1611        cx.executor().run_until_parked();
1612        _ = rs_editor.update(cx, |editor, cx| {
1613            let expected_hints = vec!["1".to_string()];
1614            assert_eq!(
1615                expected_hints,
1616                cached_hint_labels(editor),
1617                "Rust inlay cache should change after the edit"
1618            );
1619            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1620            assert_eq!(
1621                editor.inlay_hint_cache().version,
1622                2,
1623                "Every time hint cache changes, cache version should be incremented"
1624            );
1625        });
1626        _ = md_editor.update(cx, |editor, cx| {
1627            let expected_hints = vec!["0".to_string()];
1628            assert_eq!(
1629                expected_hints,
1630                cached_hint_labels(editor),
1631                "Markdown editor should not be affected by Rust editor changes"
1632            );
1633            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1634            assert_eq!(editor.inlay_hint_cache().version, 1);
1635        });
1636
1637        _ = md_editor.update(cx, |editor, cx| {
1638            editor.change_selections(None, cx, |s| s.select_ranges([13..13]));
1639            editor.handle_input("some md change", cx);
1640        });
1641        cx.executor().run_until_parked();
1642        _ = md_editor.update(cx, |editor, cx| {
1643            let expected_hints = vec!["1".to_string()];
1644            assert_eq!(
1645                expected_hints,
1646                cached_hint_labels(editor),
1647                "Rust editor should not be affected by Markdown editor changes"
1648            );
1649            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1650            assert_eq!(editor.inlay_hint_cache().version, 2);
1651        });
1652        _ = rs_editor.update(cx, |editor, cx| {
1653            let expected_hints = vec!["1".to_string()];
1654            assert_eq!(
1655                expected_hints,
1656                cached_hint_labels(editor),
1657                "Markdown editor should also change independently"
1658            );
1659            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1660            assert_eq!(editor.inlay_hint_cache().version, 2);
1661        });
1662    }
1663
1664    #[gpui::test]
1665    async fn test_hint_setting_changes(cx: &mut gpui::TestAppContext) {
1666        let allowed_hint_kinds = HashSet::from_iter([None, Some(InlayHintKind::Type)]);
1667        init_test(cx, |settings| {
1668            settings.defaults.inlay_hints = Some(InlayHintSettings {
1669                enabled: true,
1670                show_type_hints: allowed_hint_kinds.contains(&Some(InlayHintKind::Type)),
1671                show_parameter_hints: allowed_hint_kinds.contains(&Some(InlayHintKind::Parameter)),
1672                show_other_hints: allowed_hint_kinds.contains(&None),
1673            })
1674        });
1675
1676        let (file_with_hints, editor, fake_server) = prepare_test_objects(cx).await;
1677        let lsp_request_count = Arc::new(AtomicU32::new(0));
1678        let another_lsp_request_count = Arc::clone(&lsp_request_count);
1679        fake_server
1680            .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1681                let task_lsp_request_count = Arc::clone(&another_lsp_request_count);
1682                async move {
1683                    Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::SeqCst);
1684                    assert_eq!(
1685                        params.text_document.uri,
1686                        lsp::Url::from_file_path(file_with_hints).unwrap(),
1687                    );
1688                    Ok(Some(vec![
1689                        lsp::InlayHint {
1690                            position: lsp::Position::new(0, 1),
1691                            label: lsp::InlayHintLabel::String("type hint".to_string()),
1692                            kind: Some(lsp::InlayHintKind::TYPE),
1693                            text_edits: None,
1694                            tooltip: None,
1695                            padding_left: None,
1696                            padding_right: None,
1697                            data: None,
1698                        },
1699                        lsp::InlayHint {
1700                            position: lsp::Position::new(0, 2),
1701                            label: lsp::InlayHintLabel::String("parameter hint".to_string()),
1702                            kind: Some(lsp::InlayHintKind::PARAMETER),
1703                            text_edits: None,
1704                            tooltip: None,
1705                            padding_left: None,
1706                            padding_right: None,
1707                            data: None,
1708                        },
1709                        lsp::InlayHint {
1710                            position: lsp::Position::new(0, 3),
1711                            label: lsp::InlayHintLabel::String("other hint".to_string()),
1712                            kind: None,
1713                            text_edits: None,
1714                            tooltip: None,
1715                            padding_left: None,
1716                            padding_right: None,
1717                            data: None,
1718                        },
1719                    ]))
1720                }
1721            })
1722            .next()
1723            .await;
1724        cx.executor().run_until_parked();
1725
1726        let mut edits_made = 1;
1727        _ = editor.update(cx, |editor, cx| {
1728            assert_eq!(
1729                lsp_request_count.load(Ordering::Relaxed),
1730                1,
1731                "Should query new hints once"
1732            );
1733            assert_eq!(
1734                vec![
1735                    "other hint".to_string(),
1736                    "parameter hint".to_string(),
1737                    "type hint".to_string(),
1738                ],
1739                cached_hint_labels(editor),
1740                "Should get its first hints when opening the editor"
1741            );
1742            assert_eq!(
1743                vec!["other hint".to_string(), "type hint".to_string()],
1744                visible_hint_labels(editor, cx)
1745            );
1746            let inlay_cache = editor.inlay_hint_cache();
1747            assert_eq!(
1748                inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
1749                "Cache should use editor settings to get the allowed hint kinds"
1750            );
1751            assert_eq!(
1752                inlay_cache.version, edits_made,
1753                "The editor update the cache version after every cache/view change"
1754            );
1755        });
1756
1757        fake_server
1758            .request::<lsp::request::InlayHintRefreshRequest>(())
1759            .await
1760            .expect("inlay refresh request failed");
1761        cx.executor().run_until_parked();
1762        _ = editor.update(cx, |editor, cx| {
1763            assert_eq!(
1764                lsp_request_count.load(Ordering::Relaxed),
1765                2,
1766                "Should load new hints twice"
1767            );
1768            assert_eq!(
1769                vec![
1770                    "other hint".to_string(),
1771                    "parameter hint".to_string(),
1772                    "type hint".to_string(),
1773                ],
1774                cached_hint_labels(editor),
1775                "Cached hints should not change due to allowed hint kinds settings update"
1776            );
1777            assert_eq!(
1778                vec!["other hint".to_string(), "type hint".to_string()],
1779                visible_hint_labels(editor, cx)
1780            );
1781            assert_eq!(
1782                editor.inlay_hint_cache().version,
1783                edits_made,
1784                "Should not update cache version due to new loaded hints being the same"
1785            );
1786        });
1787
1788        for (new_allowed_hint_kinds, expected_visible_hints) in [
1789            (HashSet::from_iter([None]), vec!["other hint".to_string()]),
1790            (
1791                HashSet::from_iter([Some(InlayHintKind::Type)]),
1792                vec!["type hint".to_string()],
1793            ),
1794            (
1795                HashSet::from_iter([Some(InlayHintKind::Parameter)]),
1796                vec!["parameter hint".to_string()],
1797            ),
1798            (
1799                HashSet::from_iter([None, Some(InlayHintKind::Type)]),
1800                vec!["other hint".to_string(), "type hint".to_string()],
1801            ),
1802            (
1803                HashSet::from_iter([None, Some(InlayHintKind::Parameter)]),
1804                vec!["other hint".to_string(), "parameter hint".to_string()],
1805            ),
1806            (
1807                HashSet::from_iter([Some(InlayHintKind::Type), Some(InlayHintKind::Parameter)]),
1808                vec!["parameter hint".to_string(), "type hint".to_string()],
1809            ),
1810            (
1811                HashSet::from_iter([
1812                    None,
1813                    Some(InlayHintKind::Type),
1814                    Some(InlayHintKind::Parameter),
1815                ]),
1816                vec![
1817                    "other hint".to_string(),
1818                    "parameter hint".to_string(),
1819                    "type hint".to_string(),
1820                ],
1821            ),
1822        ] {
1823            edits_made += 1;
1824            update_test_language_settings(cx, |settings| {
1825                settings.defaults.inlay_hints = Some(InlayHintSettings {
1826                    enabled: true,
1827                    show_type_hints: new_allowed_hint_kinds.contains(&Some(InlayHintKind::Type)),
1828                    show_parameter_hints: new_allowed_hint_kinds
1829                        .contains(&Some(InlayHintKind::Parameter)),
1830                    show_other_hints: new_allowed_hint_kinds.contains(&None),
1831                })
1832            });
1833            cx.executor().run_until_parked();
1834            _ = editor.update(cx, |editor, cx| {
1835                assert_eq!(
1836                    lsp_request_count.load(Ordering::Relaxed),
1837                    2,
1838                    "Should not load new hints on allowed hint kinds change for hint kinds {new_allowed_hint_kinds:?}"
1839                );
1840                assert_eq!(
1841                    vec![
1842                        "other hint".to_string(),
1843                        "parameter hint".to_string(),
1844                        "type hint".to_string(),
1845                    ],
1846                    cached_hint_labels(editor),
1847                    "Should get its cached hints unchanged after the settings change for hint kinds {new_allowed_hint_kinds:?}"
1848                );
1849                assert_eq!(
1850                    expected_visible_hints,
1851                    visible_hint_labels(editor, cx),
1852                    "Should get its visible hints filtered after the settings change for hint kinds {new_allowed_hint_kinds:?}"
1853                );
1854                let inlay_cache = editor.inlay_hint_cache();
1855                assert_eq!(
1856                    inlay_cache.allowed_hint_kinds, new_allowed_hint_kinds,
1857                    "Cache should use editor settings to get the allowed hint kinds for hint kinds {new_allowed_hint_kinds:?}"
1858                );
1859                assert_eq!(
1860                    inlay_cache.version, edits_made,
1861                    "The editor should update the cache version after every cache/view change for hint kinds {new_allowed_hint_kinds:?} due to visible hints change"
1862                );
1863            });
1864        }
1865
1866        edits_made += 1;
1867        let another_allowed_hint_kinds = HashSet::from_iter([Some(InlayHintKind::Type)]);
1868        update_test_language_settings(cx, |settings| {
1869            settings.defaults.inlay_hints = Some(InlayHintSettings {
1870                enabled: false,
1871                show_type_hints: another_allowed_hint_kinds.contains(&Some(InlayHintKind::Type)),
1872                show_parameter_hints: another_allowed_hint_kinds
1873                    .contains(&Some(InlayHintKind::Parameter)),
1874                show_other_hints: another_allowed_hint_kinds.contains(&None),
1875            })
1876        });
1877        cx.executor().run_until_parked();
1878        _ = editor.update(cx, |editor, cx| {
1879            assert_eq!(
1880                lsp_request_count.load(Ordering::Relaxed),
1881                2,
1882                "Should not load new hints when hints got disabled"
1883            );
1884            assert!(
1885                cached_hint_labels(editor).is_empty(),
1886                "Should clear the cache when hints got disabled"
1887            );
1888            assert!(
1889                visible_hint_labels(editor, cx).is_empty(),
1890                "Should clear visible hints when hints got disabled"
1891            );
1892            let inlay_cache = editor.inlay_hint_cache();
1893            assert_eq!(
1894                inlay_cache.allowed_hint_kinds, another_allowed_hint_kinds,
1895                "Should update its allowed hint kinds even when hints got disabled"
1896            );
1897            assert_eq!(
1898                inlay_cache.version, edits_made,
1899                "The editor should update the cache version after hints got disabled"
1900            );
1901        });
1902
1903        fake_server
1904            .request::<lsp::request::InlayHintRefreshRequest>(())
1905            .await
1906            .expect("inlay refresh request failed");
1907        cx.executor().run_until_parked();
1908        _ = editor.update(cx, |editor, cx| {
1909            assert_eq!(
1910                lsp_request_count.load(Ordering::Relaxed),
1911                2,
1912                "Should not load new hints when they got disabled"
1913            );
1914            assert!(cached_hint_labels(editor).is_empty());
1915            assert!(visible_hint_labels(editor, cx).is_empty());
1916            assert_eq!(
1917                editor.inlay_hint_cache().version, edits_made,
1918                "The editor should not update the cache version after /refresh query without updates"
1919            );
1920        });
1921
1922        let final_allowed_hint_kinds = HashSet::from_iter([Some(InlayHintKind::Parameter)]);
1923        edits_made += 1;
1924        update_test_language_settings(cx, |settings| {
1925            settings.defaults.inlay_hints = Some(InlayHintSettings {
1926                enabled: true,
1927                show_type_hints: final_allowed_hint_kinds.contains(&Some(InlayHintKind::Type)),
1928                show_parameter_hints: final_allowed_hint_kinds
1929                    .contains(&Some(InlayHintKind::Parameter)),
1930                show_other_hints: final_allowed_hint_kinds.contains(&None),
1931            })
1932        });
1933        cx.executor().run_until_parked();
1934        _ = editor.update(cx, |editor, cx| {
1935            assert_eq!(
1936                lsp_request_count.load(Ordering::Relaxed),
1937                3,
1938                "Should query for new hints when they got reenabled"
1939            );
1940            assert_eq!(
1941                vec![
1942                    "other hint".to_string(),
1943                    "parameter hint".to_string(),
1944                    "type hint".to_string(),
1945                ],
1946                cached_hint_labels(editor),
1947                "Should get its cached hints fully repopulated after the hints got reenabled"
1948            );
1949            assert_eq!(
1950                vec!["parameter hint".to_string()],
1951                visible_hint_labels(editor, cx),
1952                "Should get its visible hints repopulated and filtered after the h"
1953            );
1954            let inlay_cache = editor.inlay_hint_cache();
1955            assert_eq!(
1956                inlay_cache.allowed_hint_kinds, final_allowed_hint_kinds,
1957                "Cache should update editor settings when hints got reenabled"
1958            );
1959            assert_eq!(
1960                inlay_cache.version, edits_made,
1961                "Cache should update its version after hints got reenabled"
1962            );
1963        });
1964
1965        fake_server
1966            .request::<lsp::request::InlayHintRefreshRequest>(())
1967            .await
1968            .expect("inlay refresh request failed");
1969        cx.executor().run_until_parked();
1970        _ = editor.update(cx, |editor, cx| {
1971            assert_eq!(
1972                lsp_request_count.load(Ordering::Relaxed),
1973                4,
1974                "Should query for new hints again"
1975            );
1976            assert_eq!(
1977                vec![
1978                    "other hint".to_string(),
1979                    "parameter hint".to_string(),
1980                    "type hint".to_string(),
1981                ],
1982                cached_hint_labels(editor),
1983            );
1984            assert_eq!(
1985                vec!["parameter hint".to_string()],
1986                visible_hint_labels(editor, cx),
1987            );
1988            assert_eq!(editor.inlay_hint_cache().version, edits_made);
1989        });
1990    }
1991
1992    #[gpui::test]
1993    async fn test_hint_request_cancellation(cx: &mut gpui::TestAppContext) {
1994        init_test(cx, |settings| {
1995            settings.defaults.inlay_hints = Some(InlayHintSettings {
1996                enabled: true,
1997                show_type_hints: true,
1998                show_parameter_hints: true,
1999                show_other_hints: true,
2000            })
2001        });
2002
2003        let (file_with_hints, editor, fake_server) = prepare_test_objects(cx).await;
2004        let fake_server = Arc::new(fake_server);
2005        let lsp_request_count = Arc::new(AtomicU32::new(0));
2006        let another_lsp_request_count = Arc::clone(&lsp_request_count);
2007        fake_server
2008            .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
2009                let task_lsp_request_count = Arc::clone(&another_lsp_request_count);
2010                async move {
2011                    let i = Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::SeqCst) + 1;
2012                    assert_eq!(
2013                        params.text_document.uri,
2014                        lsp::Url::from_file_path(file_with_hints).unwrap(),
2015                    );
2016                    Ok(Some(vec![lsp::InlayHint {
2017                        position: lsp::Position::new(0, i),
2018                        label: lsp::InlayHintLabel::String(i.to_string()),
2019                        kind: None,
2020                        text_edits: None,
2021                        tooltip: None,
2022                        padding_left: None,
2023                        padding_right: None,
2024                        data: None,
2025                    }]))
2026                }
2027            })
2028            .next()
2029            .await;
2030
2031        let mut expected_changes = Vec::new();
2032        for change_after_opening in [
2033            "initial change #1",
2034            "initial change #2",
2035            "initial change #3",
2036        ] {
2037            _ = editor.update(cx, |editor, cx| {
2038                editor.change_selections(None, cx, |s| s.select_ranges([13..13]));
2039                editor.handle_input(change_after_opening, cx);
2040            });
2041            expected_changes.push(change_after_opening);
2042        }
2043
2044        cx.executor().run_until_parked();
2045
2046        _ = editor.update(cx, |editor, cx| {
2047            let current_text = editor.text(cx);
2048            for change in &expected_changes {
2049                assert!(
2050                    current_text.contains(change),
2051                    "Should apply all changes made"
2052                );
2053            }
2054            assert_eq!(
2055                lsp_request_count.load(Ordering::Relaxed),
2056                2,
2057                "Should query new hints twice: for editor init and for the last edit that interrupted all others"
2058            );
2059            let expected_hints = vec!["2".to_string()];
2060            assert_eq!(
2061                expected_hints,
2062                cached_hint_labels(editor),
2063                "Should get hints from the last edit landed only"
2064            );
2065            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2066            assert_eq!(
2067                editor.inlay_hint_cache().version, 1,
2068                "Only one update should be registered in the cache after all cancellations"
2069            );
2070        });
2071
2072        let mut edits = Vec::new();
2073        for async_later_change in [
2074            "another change #1",
2075            "another change #2",
2076            "another change #3",
2077        ] {
2078            expected_changes.push(async_later_change);
2079            let task_editor = editor.clone();
2080            edits.push(cx.spawn(|mut cx| async move {
2081                _ = task_editor.update(&mut cx, |editor, cx| {
2082                    editor.change_selections(None, cx, |s| s.select_ranges([13..13]));
2083                    editor.handle_input(async_later_change, cx);
2084                });
2085            }));
2086        }
2087        let _ = future::join_all(edits).await;
2088        cx.executor().run_until_parked();
2089
2090        _ = editor.update(cx, |editor, cx| {
2091            let current_text = editor.text(cx);
2092            for change in &expected_changes {
2093                assert!(
2094                    current_text.contains(change),
2095                    "Should apply all changes made"
2096                );
2097            }
2098            assert_eq!(
2099                lsp_request_count.load(Ordering::SeqCst),
2100                3,
2101                "Should query new hints one more time, for the last edit only"
2102            );
2103            let expected_hints = vec!["3".to_string()];
2104            assert_eq!(
2105                expected_hints,
2106                cached_hint_labels(editor),
2107                "Should get hints from the last edit landed only"
2108            );
2109            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2110            assert_eq!(
2111                editor.inlay_hint_cache().version,
2112                2,
2113                "Should update the cache version once more, for the new change"
2114            );
2115        });
2116    }
2117
2118    #[gpui::test(iterations = 10)]
2119    async fn test_large_buffer_inlay_requests_split(cx: &mut gpui::TestAppContext) {
2120        init_test(cx, |settings| {
2121            settings.defaults.inlay_hints = Some(InlayHintSettings {
2122                enabled: true,
2123                show_type_hints: true,
2124                show_parameter_hints: true,
2125                show_other_hints: true,
2126            })
2127        });
2128
2129        let mut language = Language::new(
2130            LanguageConfig {
2131                name: "Rust".into(),
2132                path_suffixes: vec!["rs".to_string()],
2133                ..Default::default()
2134            },
2135            Some(tree_sitter_rust::language()),
2136        );
2137        let mut fake_servers = language
2138            .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
2139                capabilities: lsp::ServerCapabilities {
2140                    inlay_hint_provider: Some(lsp::OneOf::Left(true)),
2141                    ..Default::default()
2142                },
2143                ..Default::default()
2144            }))
2145            .await;
2146        let fs = FakeFs::new(cx.background_executor.clone());
2147        fs.insert_tree(
2148            "/a",
2149            json!({
2150                "main.rs": format!("fn main() {{\n{}\n}}", "let i = 5;\n".repeat(500)),
2151                "other.rs": "// Test file",
2152            }),
2153        )
2154        .await;
2155        let project = Project::test(fs, ["/a".as_ref()], cx).await;
2156        project.update(cx, |project, _| project.languages().add(Arc::new(language)));
2157        let buffer = project
2158            .update(cx, |project, cx| {
2159                project.open_local_buffer("/a/main.rs", cx)
2160            })
2161            .await
2162            .unwrap();
2163        cx.executor().run_until_parked();
2164        cx.executor().start_waiting();
2165        let fake_server = fake_servers.next().await.unwrap();
2166        let editor = cx.add_window(|cx| Editor::for_buffer(buffer, Some(project), cx));
2167        let lsp_request_ranges = Arc::new(Mutex::new(Vec::new()));
2168        let lsp_request_count = Arc::new(AtomicUsize::new(0));
2169        let closure_lsp_request_ranges = Arc::clone(&lsp_request_ranges);
2170        let closure_lsp_request_count = Arc::clone(&lsp_request_count);
2171        fake_server
2172            .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
2173                let task_lsp_request_ranges = Arc::clone(&closure_lsp_request_ranges);
2174                let task_lsp_request_count = Arc::clone(&closure_lsp_request_count);
2175                async move {
2176                    assert_eq!(
2177                        params.text_document.uri,
2178                        lsp::Url::from_file_path("/a/main.rs").unwrap(),
2179                    );
2180
2181                    task_lsp_request_ranges.lock().push(params.range);
2182                    let i = Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::Release) + 1;
2183                    Ok(Some(vec![lsp::InlayHint {
2184                        position: params.range.end,
2185                        label: lsp::InlayHintLabel::String(i.to_string()),
2186                        kind: None,
2187                        text_edits: None,
2188                        tooltip: None,
2189                        padding_left: None,
2190                        padding_right: None,
2191                        data: None,
2192                    }]))
2193                }
2194            })
2195            .next()
2196            .await;
2197
2198        fn editor_visible_range(
2199            editor: &WindowHandle<Editor>,
2200            cx: &mut gpui::TestAppContext,
2201        ) -> Range<Point> {
2202            let ranges = editor
2203                .update(cx, |editor, cx| {
2204                    editor.excerpts_for_inlay_hints_query(None, cx)
2205                })
2206                .unwrap();
2207            assert_eq!(
2208                ranges.len(),
2209                1,
2210                "Single buffer should produce a single excerpt with visible range"
2211            );
2212            let (_, (excerpt_buffer, _, excerpt_visible_range)) =
2213                ranges.into_iter().next().unwrap();
2214            excerpt_buffer.update(cx, |buffer, _| {
2215                let snapshot = buffer.snapshot();
2216                let start = buffer
2217                    .anchor_before(excerpt_visible_range.start)
2218                    .to_point(&snapshot);
2219                let end = buffer
2220                    .anchor_after(excerpt_visible_range.end)
2221                    .to_point(&snapshot);
2222                start..end
2223            })
2224        }
2225
2226        // in large buffers, requests are made for more than visible range of a buffer.
2227        // invisible parts are queried later, to avoid excessive requests on quick typing.
2228        // wait the timeout needed to get all requests.
2229        cx.executor().advance_clock(Duration::from_millis(
2230            INVISIBLE_RANGES_HINTS_REQUEST_DELAY_MILLIS + 100,
2231        ));
2232        cx.executor().run_until_parked();
2233        let initial_visible_range = editor_visible_range(&editor, cx);
2234        let lsp_initial_visible_range = lsp::Range::new(
2235            lsp::Position::new(
2236                initial_visible_range.start.row,
2237                initial_visible_range.start.column,
2238            ),
2239            lsp::Position::new(
2240                initial_visible_range.end.row,
2241                initial_visible_range.end.column,
2242            ),
2243        );
2244        let expected_initial_query_range_end =
2245            lsp::Position::new(initial_visible_range.end.row * 2, 2);
2246        let mut expected_invisible_query_start = lsp_initial_visible_range.end;
2247        expected_invisible_query_start.character += 1;
2248        _ = editor.update(cx, |editor, cx| {
2249            let ranges = lsp_request_ranges.lock().drain(..).collect::<Vec<_>>();
2250            assert_eq!(ranges.len(), 2,
2251                "When scroll is at the edge of a big document, its visible part and the same range further should be queried in order, but got: {ranges:?}");
2252            let visible_query_range = &ranges[0];
2253            assert_eq!(visible_query_range.start, lsp_initial_visible_range.start);
2254            assert_eq!(visible_query_range.end, lsp_initial_visible_range.end);
2255            let invisible_query_range = &ranges[1];
2256
2257            assert_eq!(invisible_query_range.start, expected_invisible_query_start, "Should initially query visible edge of the document");
2258            assert_eq!(invisible_query_range.end, expected_initial_query_range_end, "Should initially query visible edge of the document");
2259
2260            let requests_count = lsp_request_count.load(Ordering::Acquire);
2261            assert_eq!(requests_count, 2, "Visible + invisible request");
2262            let expected_hints = vec!["1".to_string(), "2".to_string()];
2263            assert_eq!(
2264                expected_hints,
2265                cached_hint_labels(editor),
2266                "Should have hints from both LSP requests made for a big file"
2267            );
2268            assert_eq!(expected_hints, visible_hint_labels(editor, cx), "Should display only hints from the visible range");
2269            assert_eq!(
2270                editor.inlay_hint_cache().version, requests_count,
2271                "LSP queries should've bumped the cache version"
2272            );
2273        });
2274
2275        _ = editor.update(cx, |editor, cx| {
2276            editor.scroll_screen(&ScrollAmount::Page(1.0), cx);
2277            editor.scroll_screen(&ScrollAmount::Page(1.0), cx);
2278        });
2279        cx.executor().advance_clock(Duration::from_millis(
2280            INVISIBLE_RANGES_HINTS_REQUEST_DELAY_MILLIS + 100,
2281        ));
2282        cx.executor().run_until_parked();
2283        let visible_range_after_scrolls = editor_visible_range(&editor, cx);
2284        let visible_line_count = editor
2285            .update(cx, |editor, _| editor.visible_line_count().unwrap())
2286            .unwrap();
2287        let selection_in_cached_range = editor
2288            .update(cx, |editor, cx| {
2289                let ranges = lsp_request_ranges
2290                    .lock()
2291                    .drain(..)
2292                    .sorted_by_key(|r| r.start)
2293                    .collect::<Vec<_>>();
2294                assert_eq!(
2295                    ranges.len(),
2296                    2,
2297                    "Should query 2 ranges after both scrolls, but got: {ranges:?}"
2298                );
2299                let first_scroll = &ranges[0];
2300                let second_scroll = &ranges[1];
2301                assert_eq!(
2302                    first_scroll.end, second_scroll.start,
2303                    "Should query 2 adjacent ranges after the scrolls, but got: {ranges:?}"
2304                );
2305                assert_eq!(
2306                first_scroll.start, expected_initial_query_range_end,
2307                "First scroll should start the query right after the end of the original scroll",
2308            );
2309                assert_eq!(
2310                second_scroll.end,
2311                lsp::Position::new(
2312                    visible_range_after_scrolls.end.row
2313                        + visible_line_count.ceil() as u32,
2314                    1,
2315                ),
2316                "Second scroll should query one more screen down after the end of the visible range"
2317            );
2318
2319                let lsp_requests = lsp_request_count.load(Ordering::Acquire);
2320                assert_eq!(lsp_requests, 4, "Should query for hints after every scroll");
2321                let expected_hints = vec![
2322                    "1".to_string(),
2323                    "2".to_string(),
2324                    "3".to_string(),
2325                    "4".to_string(),
2326                ];
2327                assert_eq!(
2328                    expected_hints,
2329                    cached_hint_labels(editor),
2330                    "Should have hints from the new LSP response after the edit"
2331                );
2332                assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2333                assert_eq!(
2334                    editor.inlay_hint_cache().version,
2335                    lsp_requests,
2336                    "Should update the cache for every LSP response with hints added"
2337                );
2338
2339                let mut selection_in_cached_range = visible_range_after_scrolls.end;
2340                selection_in_cached_range.row -= visible_line_count.ceil() as u32;
2341                selection_in_cached_range
2342            })
2343            .unwrap();
2344
2345        _ = editor.update(cx, |editor, cx| {
2346            editor.change_selections(Some(Autoscroll::center()), cx, |s| {
2347                s.select_ranges([selection_in_cached_range..selection_in_cached_range])
2348            });
2349        });
2350        cx.executor().advance_clock(Duration::from_millis(
2351            INVISIBLE_RANGES_HINTS_REQUEST_DELAY_MILLIS + 100,
2352        ));
2353        cx.executor().run_until_parked();
2354        _ = editor.update(cx, |_, _| {
2355            let ranges = lsp_request_ranges
2356                .lock()
2357                .drain(..)
2358                .sorted_by_key(|r| r.start)
2359                .collect::<Vec<_>>();
2360            assert!(ranges.is_empty(), "No new ranges or LSP queries should be made after returning to the selection with cached hints");
2361            assert_eq!(lsp_request_count.load(Ordering::Acquire), 4);
2362        });
2363
2364        _ = editor.update(cx, |editor, cx| {
2365            editor.handle_input("++++more text++++", cx);
2366        });
2367        cx.executor().advance_clock(Duration::from_millis(
2368            INVISIBLE_RANGES_HINTS_REQUEST_DELAY_MILLIS + 100,
2369        ));
2370        cx.executor().run_until_parked();
2371        _ = editor.update(cx, |editor, cx| {
2372            let mut ranges = lsp_request_ranges.lock().drain(..).collect::<Vec<_>>();
2373            ranges.sort_by_key(|r| r.start);
2374
2375            assert_eq!(ranges.len(), 3,
2376                "On edit, should scroll to selection and query a range around it: visible + same range above and below. Instead, got query ranges {ranges:?}");
2377            let above_query_range = &ranges[0];
2378            let visible_query_range = &ranges[1];
2379            let below_query_range = &ranges[2];
2380            assert!(above_query_range.end.character < visible_query_range.start.character || above_query_range.end.line + 1 == visible_query_range.start.line,
2381                "Above range {above_query_range:?} should be before visible range {visible_query_range:?}");
2382            assert!(visible_query_range.end.character < below_query_range.start.character || visible_query_range.end.line  + 1 == below_query_range.start.line,
2383                "Visible range {visible_query_range:?} should be before below range {below_query_range:?}");
2384            assert!(above_query_range.start.line < selection_in_cached_range.row,
2385                "Hints should be queried with the selected range after the query range start");
2386            assert!(below_query_range.end.line > selection_in_cached_range.row,
2387                "Hints should be queried with the selected range before the query range end");
2388            assert!(above_query_range.start.line <= selection_in_cached_range.row - (visible_line_count * 3.0 / 2.0) as u32,
2389                "Hints query range should contain one more screen before");
2390            assert!(below_query_range.end.line >= selection_in_cached_range.row + (visible_line_count * 3.0 / 2.0) as u32,
2391                "Hints query range should contain one more screen after");
2392
2393            let lsp_requests = lsp_request_count.load(Ordering::Acquire);
2394            assert_eq!(lsp_requests, 7, "There should be a visible range and two ranges above and below it queried");
2395            let expected_hints = vec!["5".to_string(), "6".to_string(), "7".to_string()];
2396            assert_eq!(expected_hints, cached_hint_labels(editor),
2397                "Should have hints from the new LSP response after the edit");
2398            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2399            assert_eq!(editor.inlay_hint_cache().version, lsp_requests, "Should update the cache for every LSP response with hints added");
2400        });
2401    }
2402
2403    #[gpui::test(iterations = 10)]
2404    async fn test_multiple_excerpts_large_multibuffer(cx: &mut gpui::TestAppContext) {
2405        init_test(cx, |settings| {
2406            settings.defaults.inlay_hints = Some(InlayHintSettings {
2407                enabled: true,
2408                show_type_hints: true,
2409                show_parameter_hints: true,
2410                show_other_hints: true,
2411            })
2412        });
2413
2414        let mut language = Language::new(
2415            LanguageConfig {
2416                name: "Rust".into(),
2417                path_suffixes: vec!["rs".to_string()],
2418                ..Default::default()
2419            },
2420            Some(tree_sitter_rust::language()),
2421        );
2422        let mut fake_servers = language
2423            .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
2424                capabilities: lsp::ServerCapabilities {
2425                    inlay_hint_provider: Some(lsp::OneOf::Left(true)),
2426                    ..Default::default()
2427                },
2428                ..Default::default()
2429            }))
2430            .await;
2431        let language = Arc::new(language);
2432        let fs = FakeFs::new(cx.background_executor.clone());
2433        fs.insert_tree(
2434                "/a",
2435                json!({
2436                    "main.rs": format!("fn main() {{\n{}\n}}", (0..501).map(|i| format!("let i = {i};\n")).collect::<Vec<_>>().join("")),
2437                    "other.rs": format!("fn main() {{\n{}\n}}", (0..501).map(|j| format!("let j = {j};\n")).collect::<Vec<_>>().join("")),
2438                }),
2439            )
2440            .await;
2441        let project = Project::test(fs, ["/a".as_ref()], cx).await;
2442        project.update(cx, |project, _| {
2443            project.languages().add(Arc::clone(&language))
2444        });
2445        let worktree_id = project.update(cx, |project, cx| {
2446            project.worktrees().next().unwrap().read(cx).id()
2447        });
2448
2449        let buffer_1 = project
2450            .update(cx, |project, cx| {
2451                project.open_buffer((worktree_id, "main.rs"), cx)
2452            })
2453            .await
2454            .unwrap();
2455        let buffer_2 = project
2456            .update(cx, |project, cx| {
2457                project.open_buffer((worktree_id, "other.rs"), cx)
2458            })
2459            .await
2460            .unwrap();
2461        let multibuffer = cx.new_model(|cx| {
2462            let mut multibuffer = MultiBuffer::new(0);
2463            multibuffer.push_excerpts(
2464                buffer_1.clone(),
2465                [
2466                    ExcerptRange {
2467                        context: Point::new(0, 0)..Point::new(2, 0),
2468                        primary: None,
2469                    },
2470                    ExcerptRange {
2471                        context: Point::new(4, 0)..Point::new(11, 0),
2472                        primary: None,
2473                    },
2474                    ExcerptRange {
2475                        context: Point::new(22, 0)..Point::new(33, 0),
2476                        primary: None,
2477                    },
2478                    ExcerptRange {
2479                        context: Point::new(44, 0)..Point::new(55, 0),
2480                        primary: None,
2481                    },
2482                    ExcerptRange {
2483                        context: Point::new(56, 0)..Point::new(66, 0),
2484                        primary: None,
2485                    },
2486                    ExcerptRange {
2487                        context: Point::new(67, 0)..Point::new(77, 0),
2488                        primary: None,
2489                    },
2490                ],
2491                cx,
2492            );
2493            multibuffer.push_excerpts(
2494                buffer_2.clone(),
2495                [
2496                    ExcerptRange {
2497                        context: Point::new(0, 1)..Point::new(2, 1),
2498                        primary: None,
2499                    },
2500                    ExcerptRange {
2501                        context: Point::new(4, 1)..Point::new(11, 1),
2502                        primary: None,
2503                    },
2504                    ExcerptRange {
2505                        context: Point::new(22, 1)..Point::new(33, 1),
2506                        primary: None,
2507                    },
2508                    ExcerptRange {
2509                        context: Point::new(44, 1)..Point::new(55, 1),
2510                        primary: None,
2511                    },
2512                    ExcerptRange {
2513                        context: Point::new(56, 1)..Point::new(66, 1),
2514                        primary: None,
2515                    },
2516                    ExcerptRange {
2517                        context: Point::new(67, 1)..Point::new(77, 1),
2518                        primary: None,
2519                    },
2520                ],
2521                cx,
2522            );
2523            multibuffer
2524        });
2525
2526        cx.executor().run_until_parked();
2527        let editor =
2528            cx.add_window(|cx| Editor::for_multibuffer(multibuffer, Some(project.clone()), cx));
2529        let editor_edited = Arc::new(AtomicBool::new(false));
2530        let fake_server = fake_servers.next().await.unwrap();
2531        let closure_editor_edited = Arc::clone(&editor_edited);
2532        fake_server
2533            .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
2534                let task_editor_edited = Arc::clone(&closure_editor_edited);
2535                async move {
2536                    let hint_text = if params.text_document.uri
2537                        == lsp::Url::from_file_path("/a/main.rs").unwrap()
2538                    {
2539                        "main hint"
2540                    } else if params.text_document.uri
2541                        == lsp::Url::from_file_path("/a/other.rs").unwrap()
2542                    {
2543                        "other hint"
2544                    } else {
2545                        panic!("unexpected uri: {:?}", params.text_document.uri);
2546                    };
2547
2548                    // one hint per excerpt
2549                    let positions = [
2550                        lsp::Position::new(0, 2),
2551                        lsp::Position::new(4, 2),
2552                        lsp::Position::new(22, 2),
2553                        lsp::Position::new(44, 2),
2554                        lsp::Position::new(56, 2),
2555                        lsp::Position::new(67, 2),
2556                    ];
2557                    let out_of_range_hint = lsp::InlayHint {
2558                        position: lsp::Position::new(
2559                            params.range.start.line + 99,
2560                            params.range.start.character + 99,
2561                        ),
2562                        label: lsp::InlayHintLabel::String(
2563                            "out of excerpt range, should be ignored".to_string(),
2564                        ),
2565                        kind: None,
2566                        text_edits: None,
2567                        tooltip: None,
2568                        padding_left: None,
2569                        padding_right: None,
2570                        data: None,
2571                    };
2572
2573                    let edited = task_editor_edited.load(Ordering::Acquire);
2574                    Ok(Some(
2575                        std::iter::once(out_of_range_hint)
2576                            .chain(positions.into_iter().enumerate().map(|(i, position)| {
2577                                lsp::InlayHint {
2578                                    position,
2579                                    label: lsp::InlayHintLabel::String(format!(
2580                                        "{hint_text}{} #{i}",
2581                                        if edited { "(edited)" } else { "" },
2582                                    )),
2583                                    kind: None,
2584                                    text_edits: None,
2585                                    tooltip: None,
2586                                    padding_left: None,
2587                                    padding_right: None,
2588                                    data: None,
2589                                }
2590                            }))
2591                            .collect(),
2592                    ))
2593                }
2594            })
2595            .next()
2596            .await;
2597        cx.executor().run_until_parked();
2598
2599        _ = editor.update(cx, |editor, cx| {
2600                let expected_hints = vec![
2601                    "main hint #0".to_string(),
2602                    "main hint #1".to_string(),
2603                    "main hint #2".to_string(),
2604                    "main hint #3".to_string(),
2605                    "main hint #4".to_string(),
2606                    "main hint #5".to_string(),
2607                ];
2608                assert_eq!(
2609                    expected_hints,
2610                    cached_hint_labels(editor),
2611                    "When scroll is at the edge of a multibuffer, its visible excerpts only should be queried for inlay hints"
2612                );
2613                assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2614                assert_eq!(editor.inlay_hint_cache().version, expected_hints.len(), "Every visible excerpt hints should bump the verison");
2615            });
2616
2617        _ = editor.update(cx, |editor, cx| {
2618            editor.change_selections(Some(Autoscroll::Next), cx, |s| {
2619                s.select_ranges([Point::new(4, 0)..Point::new(4, 0)])
2620            });
2621            editor.change_selections(Some(Autoscroll::Next), cx, |s| {
2622                s.select_ranges([Point::new(22, 0)..Point::new(22, 0)])
2623            });
2624            editor.change_selections(Some(Autoscroll::Next), cx, |s| {
2625                s.select_ranges([Point::new(50, 0)..Point::new(50, 0)])
2626            });
2627        });
2628        cx.executor().run_until_parked();
2629        _ = editor.update(cx, |editor, cx| {
2630                let expected_hints = vec![
2631                    "main hint #0".to_string(),
2632                    "main hint #1".to_string(),
2633                    "main hint #2".to_string(),
2634                    "main hint #3".to_string(),
2635                    "main hint #4".to_string(),
2636                    "main hint #5".to_string(),
2637                    "other hint #0".to_string(),
2638                    "other hint #1".to_string(),
2639                    "other hint #2".to_string(),
2640                ];
2641                assert_eq!(expected_hints, cached_hint_labels(editor),
2642                    "With more scrolls of the multibuffer, more hints should be added into the cache and nothing invalidated without edits");
2643                assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2644                assert_eq!(editor.inlay_hint_cache().version, expected_hints.len(),
2645                    "Due to every excerpt having one hint, we update cache per new excerpt scrolled");
2646            });
2647
2648        _ = editor.update(cx, |editor, cx| {
2649            editor.change_selections(Some(Autoscroll::Next), cx, |s| {
2650                s.select_ranges([Point::new(100, 0)..Point::new(100, 0)])
2651            });
2652        });
2653        cx.executor().advance_clock(Duration::from_millis(
2654            INVISIBLE_RANGES_HINTS_REQUEST_DELAY_MILLIS + 100,
2655        ));
2656        cx.executor().run_until_parked();
2657        let last_scroll_update_version = editor.update(cx, |editor, cx| {
2658                let expected_hints = vec![
2659                    "main hint #0".to_string(),
2660                    "main hint #1".to_string(),
2661                    "main hint #2".to_string(),
2662                    "main hint #3".to_string(),
2663                    "main hint #4".to_string(),
2664                    "main hint #5".to_string(),
2665                    "other hint #0".to_string(),
2666                    "other hint #1".to_string(),
2667                    "other hint #2".to_string(),
2668                    "other hint #3".to_string(),
2669                    "other hint #4".to_string(),
2670                    "other hint #5".to_string(),
2671                ];
2672                assert_eq!(expected_hints, cached_hint_labels(editor),
2673                    "After multibuffer was scrolled to the end, all hints for all excerpts should be fetched");
2674                assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2675                assert_eq!(editor.inlay_hint_cache().version, expected_hints.len());
2676                expected_hints.len()
2677            }).unwrap();
2678
2679        _ = editor.update(cx, |editor, cx| {
2680            editor.change_selections(Some(Autoscroll::Next), cx, |s| {
2681                s.select_ranges([Point::new(4, 0)..Point::new(4, 0)])
2682            });
2683        });
2684        cx.executor().run_until_parked();
2685        _ = editor.update(cx, |editor, cx| {
2686                let expected_hints = vec![
2687                    "main hint #0".to_string(),
2688                    "main hint #1".to_string(),
2689                    "main hint #2".to_string(),
2690                    "main hint #3".to_string(),
2691                    "main hint #4".to_string(),
2692                    "main hint #5".to_string(),
2693                    "other hint #0".to_string(),
2694                    "other hint #1".to_string(),
2695                    "other hint #2".to_string(),
2696                    "other hint #3".to_string(),
2697                    "other hint #4".to_string(),
2698                    "other hint #5".to_string(),
2699                ];
2700                assert_eq!(expected_hints, cached_hint_labels(editor),
2701                    "After multibuffer was scrolled to the end, further scrolls up should not bring more hints");
2702                assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2703                assert_eq!(editor.inlay_hint_cache().version, last_scroll_update_version, "No updates should happen during scrolling already scolled buffer");
2704            });
2705
2706        editor_edited.store(true, Ordering::Release);
2707        _ = editor.update(cx, |editor, cx| {
2708            editor.change_selections(None, cx, |s| {
2709                // TODO if this gets set to hint boundary (e.g. 56) we sometimes get an extra cache version bump, why?
2710                s.select_ranges([Point::new(57, 0)..Point::new(57, 0)])
2711            });
2712            editor.handle_input("++++more text++++", cx);
2713        });
2714        cx.executor().run_until_parked();
2715        _ = editor.update(cx, |editor, cx| {
2716            let expected_hints = vec![
2717                "main hint(edited) #0".to_string(),
2718                "main hint(edited) #1".to_string(),
2719                "main hint(edited) #2".to_string(),
2720                "main hint(edited) #3".to_string(),
2721                "main hint(edited) #4".to_string(),
2722                "main hint(edited) #5".to_string(),
2723                "other hint(edited) #0".to_string(),
2724                "other hint(edited) #1".to_string(),
2725            ];
2726            assert_eq!(
2727                expected_hints,
2728                cached_hint_labels(editor),
2729                "After multibuffer edit, editor gets scolled back to the last selection; \
2730    all hints should be invalidated and requeried for all of its visible excerpts"
2731            );
2732            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2733
2734            let current_cache_version = editor.inlay_hint_cache().version;
2735            assert_eq!(
2736                current_cache_version,
2737                last_scroll_update_version + expected_hints.len(),
2738                "We should have updated cache N times == N of new hints arrived (separately from each excerpt)"
2739            );
2740        });
2741    }
2742
2743    #[gpui::test]
2744    async fn test_excerpts_removed(cx: &mut gpui::TestAppContext) {
2745        init_test(cx, |settings| {
2746            settings.defaults.inlay_hints = Some(InlayHintSettings {
2747                enabled: true,
2748                show_type_hints: false,
2749                show_parameter_hints: false,
2750                show_other_hints: false,
2751            })
2752        });
2753
2754        let mut language = Language::new(
2755            LanguageConfig {
2756                name: "Rust".into(),
2757                path_suffixes: vec!["rs".to_string()],
2758                ..Default::default()
2759            },
2760            Some(tree_sitter_rust::language()),
2761        );
2762        let mut fake_servers = language
2763            .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
2764                capabilities: lsp::ServerCapabilities {
2765                    inlay_hint_provider: Some(lsp::OneOf::Left(true)),
2766                    ..Default::default()
2767                },
2768                ..Default::default()
2769            }))
2770            .await;
2771        let language = Arc::new(language);
2772        let fs = FakeFs::new(cx.background_executor.clone());
2773        fs.insert_tree(
2774            "/a",
2775            json!({
2776                "main.rs": format!("fn main() {{\n{}\n}}", (0..501).map(|i| format!("let i = {i};\n")).collect::<Vec<_>>().join("")),
2777                "other.rs": format!("fn main() {{\n{}\n}}", (0..501).map(|j| format!("let j = {j};\n")).collect::<Vec<_>>().join("")),
2778            }),
2779        )
2780        .await;
2781        let project = Project::test(fs, ["/a".as_ref()], cx).await;
2782        project.update(cx, |project, _| {
2783            project.languages().add(Arc::clone(&language))
2784        });
2785        let worktree_id = project.update(cx, |project, cx| {
2786            project.worktrees().next().unwrap().read(cx).id()
2787        });
2788
2789        let buffer_1 = project
2790            .update(cx, |project, cx| {
2791                project.open_buffer((worktree_id, "main.rs"), cx)
2792            })
2793            .await
2794            .unwrap();
2795        let buffer_2 = project
2796            .update(cx, |project, cx| {
2797                project.open_buffer((worktree_id, "other.rs"), cx)
2798            })
2799            .await
2800            .unwrap();
2801        let multibuffer = cx.new_model(|_| MultiBuffer::new(0));
2802        let (buffer_1_excerpts, buffer_2_excerpts) = multibuffer.update(cx, |multibuffer, cx| {
2803            let buffer_1_excerpts = multibuffer.push_excerpts(
2804                buffer_1.clone(),
2805                [ExcerptRange {
2806                    context: Point::new(0, 0)..Point::new(2, 0),
2807                    primary: None,
2808                }],
2809                cx,
2810            );
2811            let buffer_2_excerpts = multibuffer.push_excerpts(
2812                buffer_2.clone(),
2813                [ExcerptRange {
2814                    context: Point::new(0, 1)..Point::new(2, 1),
2815                    primary: None,
2816                }],
2817                cx,
2818            );
2819            (buffer_1_excerpts, buffer_2_excerpts)
2820        });
2821
2822        assert!(!buffer_1_excerpts.is_empty());
2823        assert!(!buffer_2_excerpts.is_empty());
2824
2825        cx.executor().run_until_parked();
2826        let editor =
2827            cx.add_window(|cx| Editor::for_multibuffer(multibuffer, Some(project.clone()), cx));
2828        let editor_edited = Arc::new(AtomicBool::new(false));
2829        let fake_server = fake_servers.next().await.unwrap();
2830        let closure_editor_edited = Arc::clone(&editor_edited);
2831        fake_server
2832            .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
2833                let task_editor_edited = Arc::clone(&closure_editor_edited);
2834                async move {
2835                    let hint_text = if params.text_document.uri
2836                        == lsp::Url::from_file_path("/a/main.rs").unwrap()
2837                    {
2838                        "main hint"
2839                    } else if params.text_document.uri
2840                        == lsp::Url::from_file_path("/a/other.rs").unwrap()
2841                    {
2842                        "other hint"
2843                    } else {
2844                        panic!("unexpected uri: {:?}", params.text_document.uri);
2845                    };
2846
2847                    let positions = [
2848                        lsp::Position::new(0, 2),
2849                        lsp::Position::new(4, 2),
2850                        lsp::Position::new(22, 2),
2851                        lsp::Position::new(44, 2),
2852                        lsp::Position::new(56, 2),
2853                        lsp::Position::new(67, 2),
2854                    ];
2855                    let out_of_range_hint = lsp::InlayHint {
2856                        position: lsp::Position::new(
2857                            params.range.start.line + 99,
2858                            params.range.start.character + 99,
2859                        ),
2860                        label: lsp::InlayHintLabel::String(
2861                            "out of excerpt range, should be ignored".to_string(),
2862                        ),
2863                        kind: None,
2864                        text_edits: None,
2865                        tooltip: None,
2866                        padding_left: None,
2867                        padding_right: None,
2868                        data: None,
2869                    };
2870
2871                    let edited = task_editor_edited.load(Ordering::Acquire);
2872                    Ok(Some(
2873                        std::iter::once(out_of_range_hint)
2874                            .chain(positions.into_iter().enumerate().map(|(i, position)| {
2875                                lsp::InlayHint {
2876                                    position,
2877                                    label: lsp::InlayHintLabel::String(format!(
2878                                        "{hint_text}{} #{i}",
2879                                        if edited { "(edited)" } else { "" },
2880                                    )),
2881                                    kind: None,
2882                                    text_edits: None,
2883                                    tooltip: None,
2884                                    padding_left: None,
2885                                    padding_right: None,
2886                                    data: None,
2887                                }
2888                            }))
2889                            .collect(),
2890                    ))
2891                }
2892            })
2893            .next()
2894            .await;
2895        cx.executor().run_until_parked();
2896
2897        _ = editor.update(cx, |editor, cx| {
2898            assert_eq!(
2899                vec!["main hint #0".to_string(), "other hint #0".to_string()],
2900                cached_hint_labels(editor),
2901                "Cache should update for both excerpts despite hints display was disabled"
2902            );
2903            assert!(
2904                visible_hint_labels(editor, cx).is_empty(),
2905                "All hints are disabled and should not be shown despite being present in the cache"
2906            );
2907            assert_eq!(
2908                editor.inlay_hint_cache().version,
2909                2,
2910                "Cache should update once per excerpt query"
2911            );
2912        });
2913
2914        _ = editor.update(cx, |editor, cx| {
2915            editor.buffer().update(cx, |multibuffer, cx| {
2916                multibuffer.remove_excerpts(buffer_2_excerpts, cx)
2917            })
2918        });
2919        cx.executor().run_until_parked();
2920        _ = editor.update(cx, |editor, cx| {
2921            assert_eq!(
2922                vec!["main hint #0".to_string()],
2923                cached_hint_labels(editor),
2924                "For the removed excerpt, should clean corresponding cached hints"
2925            );
2926            assert!(
2927                visible_hint_labels(editor, cx).is_empty(),
2928                "All hints are disabled and should not be shown despite being present in the cache"
2929            );
2930            assert_eq!(
2931                editor.inlay_hint_cache().version,
2932                3,
2933                "Excerpt removal should trigger a cache update"
2934            );
2935        });
2936
2937        update_test_language_settings(cx, |settings| {
2938            settings.defaults.inlay_hints = Some(InlayHintSettings {
2939                enabled: true,
2940                show_type_hints: true,
2941                show_parameter_hints: true,
2942                show_other_hints: true,
2943            })
2944        });
2945        cx.executor().run_until_parked();
2946        _ = editor.update(cx, |editor, cx| {
2947            let expected_hints = vec!["main hint #0".to_string()];
2948            assert_eq!(
2949                expected_hints,
2950                cached_hint_labels(editor),
2951                "Hint display settings change should not change the cache"
2952            );
2953            assert_eq!(
2954                expected_hints,
2955                visible_hint_labels(editor, cx),
2956                "Settings change should make cached hints visible"
2957            );
2958            assert_eq!(
2959                editor.inlay_hint_cache().version,
2960                4,
2961                "Settings change should trigger a cache update"
2962            );
2963        });
2964    }
2965
2966    #[gpui::test]
2967    async fn test_inside_char_boundary_range_hints(cx: &mut gpui::TestAppContext) {
2968        init_test(cx, |settings| {
2969            settings.defaults.inlay_hints = Some(InlayHintSettings {
2970                enabled: true,
2971                show_type_hints: true,
2972                show_parameter_hints: true,
2973                show_other_hints: true,
2974            })
2975        });
2976
2977        let mut language = Language::new(
2978            LanguageConfig {
2979                name: "Rust".into(),
2980                path_suffixes: vec!["rs".to_string()],
2981                ..Default::default()
2982            },
2983            Some(tree_sitter_rust::language()),
2984        );
2985        let mut fake_servers = language
2986            .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
2987                capabilities: lsp::ServerCapabilities {
2988                    inlay_hint_provider: Some(lsp::OneOf::Left(true)),
2989                    ..Default::default()
2990                },
2991                ..Default::default()
2992            }))
2993            .await;
2994        let fs = FakeFs::new(cx.background_executor.clone());
2995        fs.insert_tree(
2996            "/a",
2997            json!({
2998                "main.rs": format!(r#"fn main() {{\n{}\n}}"#, format!("let i = {};\n", "".repeat(10)).repeat(500)),
2999                "other.rs": "// Test file",
3000            }),
3001        )
3002        .await;
3003        let project = Project::test(fs, ["/a".as_ref()], cx).await;
3004        project.update(cx, |project, _| project.languages().add(Arc::new(language)));
3005        let buffer = project
3006            .update(cx, |project, cx| {
3007                project.open_local_buffer("/a/main.rs", cx)
3008            })
3009            .await
3010            .unwrap();
3011        cx.executor().run_until_parked();
3012        cx.executor().start_waiting();
3013        let fake_server = fake_servers.next().await.unwrap();
3014        let editor = cx.add_window(|cx| Editor::for_buffer(buffer, Some(project), cx));
3015        let lsp_request_count = Arc::new(AtomicU32::new(0));
3016        let closure_lsp_request_count = Arc::clone(&lsp_request_count);
3017        fake_server
3018            .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
3019                let task_lsp_request_count = Arc::clone(&closure_lsp_request_count);
3020                async move {
3021                    assert_eq!(
3022                        params.text_document.uri,
3023                        lsp::Url::from_file_path("/a/main.rs").unwrap(),
3024                    );
3025                    let query_start = params.range.start;
3026                    let i = Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::Release) + 1;
3027                    Ok(Some(vec![lsp::InlayHint {
3028                        position: query_start,
3029                        label: lsp::InlayHintLabel::String(i.to_string()),
3030                        kind: None,
3031                        text_edits: None,
3032                        tooltip: None,
3033                        padding_left: None,
3034                        padding_right: None,
3035                        data: None,
3036                    }]))
3037                }
3038            })
3039            .next()
3040            .await;
3041
3042        cx.executor().run_until_parked();
3043        _ = editor.update(cx, |editor, cx| {
3044            editor.change_selections(None, cx, |s| {
3045                s.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
3046            })
3047        });
3048        cx.executor().run_until_parked();
3049        _ = editor.update(cx, |editor, cx| {
3050            let expected_hints = vec!["1".to_string()];
3051            assert_eq!(expected_hints, cached_hint_labels(editor));
3052            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
3053            assert_eq!(editor.inlay_hint_cache().version, 1);
3054        });
3055    }
3056
3057    #[gpui::test]
3058    async fn test_toggle_inlay_hints(cx: &mut gpui::TestAppContext) {
3059        init_test(cx, |settings| {
3060            settings.defaults.inlay_hints = Some(InlayHintSettings {
3061                enabled: false,
3062                show_type_hints: true,
3063                show_parameter_hints: true,
3064                show_other_hints: true,
3065            })
3066        });
3067
3068        let (file_with_hints, editor, fake_server) = prepare_test_objects(cx).await;
3069
3070        _ = editor.update(cx, |editor, cx| {
3071            editor.toggle_inlay_hints(&crate::ToggleInlayHints, cx)
3072        });
3073        cx.executor().start_waiting();
3074        let lsp_request_count = Arc::new(AtomicU32::new(0));
3075        let closure_lsp_request_count = Arc::clone(&lsp_request_count);
3076        fake_server
3077            .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
3078                let task_lsp_request_count = Arc::clone(&closure_lsp_request_count);
3079                async move {
3080                    assert_eq!(
3081                        params.text_document.uri,
3082                        lsp::Url::from_file_path(file_with_hints).unwrap(),
3083                    );
3084
3085                    let i = Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::SeqCst) + 1;
3086                    Ok(Some(vec![lsp::InlayHint {
3087                        position: lsp::Position::new(0, i),
3088                        label: lsp::InlayHintLabel::String(i.to_string()),
3089                        kind: None,
3090                        text_edits: None,
3091                        tooltip: None,
3092                        padding_left: None,
3093                        padding_right: None,
3094                        data: None,
3095                    }]))
3096                }
3097            })
3098            .next()
3099            .await;
3100        cx.executor().run_until_parked();
3101        _ = editor.update(cx, |editor, cx| {
3102            let expected_hints = vec!["1".to_string()];
3103            assert_eq!(
3104                expected_hints,
3105                cached_hint_labels(editor),
3106                "Should display inlays after toggle despite them disabled in settings"
3107            );
3108            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
3109            assert_eq!(
3110                editor.inlay_hint_cache().version,
3111                1,
3112                "First toggle should be cache's first update"
3113            );
3114        });
3115
3116        _ = editor.update(cx, |editor, cx| {
3117            editor.toggle_inlay_hints(&crate::ToggleInlayHints, cx)
3118        });
3119        cx.executor().run_until_parked();
3120        _ = editor.update(cx, |editor, cx| {
3121            assert!(
3122                cached_hint_labels(editor).is_empty(),
3123                "Should clear hints after 2nd toggle"
3124            );
3125            assert!(visible_hint_labels(editor, cx).is_empty());
3126            assert_eq!(editor.inlay_hint_cache().version, 2);
3127        });
3128
3129        update_test_language_settings(cx, |settings| {
3130            settings.defaults.inlay_hints = Some(InlayHintSettings {
3131                enabled: true,
3132                show_type_hints: true,
3133                show_parameter_hints: true,
3134                show_other_hints: true,
3135            })
3136        });
3137        cx.executor().run_until_parked();
3138        _ = editor.update(cx, |editor, cx| {
3139            let expected_hints = vec!["2".to_string()];
3140            assert_eq!(
3141                expected_hints,
3142                cached_hint_labels(editor),
3143                "Should query LSP hints for the 2nd time after enabling hints in settings"
3144            );
3145            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
3146            assert_eq!(editor.inlay_hint_cache().version, 3);
3147        });
3148
3149        _ = editor.update(cx, |editor, cx| {
3150            editor.toggle_inlay_hints(&crate::ToggleInlayHints, cx)
3151        });
3152        cx.executor().run_until_parked();
3153        _ = editor.update(cx, |editor, cx| {
3154            assert!(
3155                cached_hint_labels(editor).is_empty(),
3156                "Should clear hints after enabling in settings and a 3rd toggle"
3157            );
3158            assert!(visible_hint_labels(editor, cx).is_empty());
3159            assert_eq!(editor.inlay_hint_cache().version, 4);
3160        });
3161
3162        _ = editor.update(cx, |editor, cx| {
3163            editor.toggle_inlay_hints(&crate::ToggleInlayHints, cx)
3164        });
3165        cx.executor().run_until_parked();
3166        _ = editor.update(cx, |editor, cx| {
3167            let expected_hints = vec!["3".to_string()];
3168            assert_eq!(
3169                expected_hints,
3170                cached_hint_labels(editor),
3171                "Should query LSP hints for the 3rd time after enabling hints in settings and toggling them back on"
3172            );
3173            assert_eq!(expected_hints, visible_hint_labels(editor, cx));
3174            assert_eq!(editor.inlay_hint_cache().version, 5);
3175        });
3176    }
3177
3178    pub(crate) fn init_test(cx: &mut TestAppContext, f: impl Fn(&mut AllLanguageSettingsContent)) {
3179        cx.update(|cx| {
3180            let settings_store = SettingsStore::test(cx);
3181            cx.set_global(settings_store);
3182            theme::init(theme::LoadThemes::JustBase, cx);
3183            client::init_settings(cx);
3184            language::init(cx);
3185            Project::init_settings(cx);
3186            workspace::init_settings(cx);
3187            crate::init(cx);
3188        });
3189
3190        update_test_language_settings(cx, f);
3191    }
3192
3193    async fn prepare_test_objects(
3194        cx: &mut TestAppContext,
3195    ) -> (&'static str, WindowHandle<Editor>, FakeLanguageServer) {
3196        let mut language = Language::new(
3197            LanguageConfig {
3198                name: "Rust".into(),
3199                path_suffixes: vec!["rs".to_string()],
3200                ..Default::default()
3201            },
3202            Some(tree_sitter_rust::language()),
3203        );
3204        let mut fake_servers = language
3205            .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
3206                capabilities: lsp::ServerCapabilities {
3207                    inlay_hint_provider: Some(lsp::OneOf::Left(true)),
3208                    ..Default::default()
3209                },
3210                ..Default::default()
3211            }))
3212            .await;
3213
3214        let fs = FakeFs::new(cx.background_executor.clone());
3215        fs.insert_tree(
3216            "/a",
3217            json!({
3218                "main.rs": "fn main() { a } // and some long comment to ensure inlays are not trimmed out",
3219                "other.rs": "// Test file",
3220            }),
3221        )
3222        .await;
3223
3224        let project = Project::test(fs, ["/a".as_ref()], cx).await;
3225        _ = project.update(cx, |project, _| project.languages().add(Arc::new(language)));
3226        let buffer = project
3227            .update(cx, |project, cx| {
3228                project.open_local_buffer("/a/main.rs", cx)
3229            })
3230            .await
3231            .unwrap();
3232        cx.executor().run_until_parked();
3233        cx.executor().start_waiting();
3234        let fake_server = fake_servers.next().await.unwrap();
3235        let editor = cx.add_window(|cx| Editor::for_buffer(buffer, Some(project), cx));
3236
3237        _ = editor.update(cx, |editor, cx| {
3238            assert!(cached_hint_labels(editor).is_empty());
3239            assert!(visible_hint_labels(editor, cx).is_empty());
3240            assert_eq!(editor.inlay_hint_cache().version, 0);
3241        });
3242
3243        ("/a/main.rs", editor, fake_server)
3244    }
3245
3246    pub fn cached_hint_labels(editor: &Editor) -> Vec<String> {
3247        let mut labels = Vec::new();
3248        for (_, excerpt_hints) in &editor.inlay_hint_cache().hints {
3249            let excerpt_hints = excerpt_hints.read();
3250            for id in &excerpt_hints.ordered_hints {
3251                labels.push(excerpt_hints.hints_by_id[id].text());
3252            }
3253        }
3254
3255        labels.sort();
3256        labels
3257    }
3258
3259    pub fn visible_hint_labels(editor: &Editor, cx: &ViewContext<'_, Editor>) -> Vec<String> {
3260        let mut hints = editor
3261            .visible_inlay_hints(cx)
3262            .into_iter()
3263            .map(|hint| hint.text.to_string())
3264            .collect::<Vec<_>>();
3265        hints.sort();
3266        hints
3267    }
3268}