tests.rs

   1use super::*;
   2use gpui::{ModelHandle, MutableAppContext, Task};
   3use std::{
   4    any::Any,
   5    cell::RefCell,
   6    ffi::OsString,
   7    iter::FromIterator,
   8    ops::Range,
   9    path::PathBuf,
  10    rc::Rc,
  11    time::{Duration, Instant, SystemTime},
  12};
  13use unindent::Unindent as _;
  14
  15#[cfg(test)]
  16#[ctor::ctor]
  17fn init_logger() {
  18    // std::env::set_var("RUST_LOG", "info");
  19    env_logger::init();
  20}
  21
  22#[test]
  23fn test_select_language() {
  24    let registry = LanguageRegistry {
  25        languages: vec![
  26            Arc::new(Language::new(
  27                LanguageConfig {
  28                    name: "Rust".to_string(),
  29                    path_suffixes: vec!["rs".to_string()],
  30                    ..Default::default()
  31                },
  32                Some(tree_sitter_rust::language()),
  33            )),
  34            Arc::new(Language::new(
  35                LanguageConfig {
  36                    name: "Make".to_string(),
  37                    path_suffixes: vec!["Makefile".to_string(), "mk".to_string()],
  38                    ..Default::default()
  39                },
  40                Some(tree_sitter_rust::language()),
  41            )),
  42        ],
  43    };
  44
  45    // matching file extension
  46    assert_eq!(
  47        registry.select_language("zed/lib.rs").map(|l| l.name()),
  48        Some("Rust")
  49    );
  50    assert_eq!(
  51        registry.select_language("zed/lib.mk").map(|l| l.name()),
  52        Some("Make")
  53    );
  54
  55    // matching filename
  56    assert_eq!(
  57        registry.select_language("zed/Makefile").map(|l| l.name()),
  58        Some("Make")
  59    );
  60
  61    // matching suffix that is not the full file extension or filename
  62    assert_eq!(registry.select_language("zed/cars").map(|l| l.name()), None);
  63    assert_eq!(
  64        registry.select_language("zed/a.cars").map(|l| l.name()),
  65        None
  66    );
  67    assert_eq!(registry.select_language("zed/sumk").map(|l| l.name()), None);
  68}
  69
  70#[gpui::test]
  71fn test_edit_events(cx: &mut gpui::MutableAppContext) {
  72    let mut now = Instant::now();
  73    let buffer_1_events = Rc::new(RefCell::new(Vec::new()));
  74    let buffer_2_events = Rc::new(RefCell::new(Vec::new()));
  75
  76    let buffer1 = cx.add_model(|cx| Buffer::new(0, "abcdef", cx));
  77    let buffer2 = cx.add_model(|cx| Buffer::new(1, "abcdef", cx));
  78    let buffer_ops = buffer1.update(cx, |buffer, cx| {
  79        let buffer_1_events = buffer_1_events.clone();
  80        cx.subscribe(&buffer1, move |_, _, event, _| {
  81            buffer_1_events.borrow_mut().push(event.clone())
  82        })
  83        .detach();
  84        let buffer_2_events = buffer_2_events.clone();
  85        cx.subscribe(&buffer2, move |_, _, event, _| {
  86            buffer_2_events.borrow_mut().push(event.clone())
  87        })
  88        .detach();
  89
  90        // An edit emits an edited event, followed by a dirtied event,
  91        // since the buffer was previously in a clean state.
  92        buffer.edit(Some(2..4), "XYZ", cx);
  93
  94        // An empty transaction does not emit any events.
  95        buffer.start_transaction(None).unwrap();
  96        buffer.end_transaction(None, cx).unwrap();
  97
  98        // A transaction containing two edits emits one edited event.
  99        now += Duration::from_secs(1);
 100        buffer.start_transaction_at(None, now).unwrap();
 101        buffer.edit(Some(5..5), "u", cx);
 102        buffer.edit(Some(6..6), "w", cx);
 103        buffer.end_transaction_at(None, now, cx).unwrap();
 104
 105        // Undoing a transaction emits one edited event.
 106        buffer.undo(cx);
 107
 108        buffer.operations.clone()
 109    });
 110
 111    // Incorporating a set of remote ops emits a single edited event,
 112    // followed by a dirtied event.
 113    buffer2.update(cx, |buffer, cx| {
 114        buffer.apply_ops(buffer_ops, cx).unwrap();
 115    });
 116
 117    let buffer_1_events = buffer_1_events.borrow();
 118    assert_eq!(
 119        *buffer_1_events,
 120        vec![Event::Edited, Event::Dirtied, Event::Edited, Event::Edited]
 121    );
 122
 123    let buffer_2_events = buffer_2_events.borrow();
 124    assert_eq!(*buffer_2_events, vec![Event::Edited, Event::Dirtied]);
 125}
 126
 127#[gpui::test]
 128async fn test_apply_diff(mut cx: gpui::TestAppContext) {
 129    let text = "a\nbb\nccc\ndddd\neeeee\nffffff\n";
 130    let buffer = cx.add_model(|cx| Buffer::new(0, text, cx));
 131
 132    let text = "a\nccc\ndddd\nffffff\n";
 133    let diff = buffer.read_with(&cx, |b, cx| b.diff(text.into(), cx)).await;
 134    buffer.update(&mut cx, |b, cx| b.apply_diff(diff, cx));
 135    cx.read(|cx| assert_eq!(buffer.read(cx).text(), text));
 136
 137    let text = "a\n1\n\nccc\ndd2dd\nffffff\n";
 138    let diff = buffer.read_with(&cx, |b, cx| b.diff(text.into(), cx)).await;
 139    buffer.update(&mut cx, |b, cx| b.apply_diff(diff, cx));
 140    cx.read(|cx| assert_eq!(buffer.read(cx).text(), text));
 141}
 142
 143#[gpui::test]
 144async fn test_reparse(mut cx: gpui::TestAppContext) {
 145    let text = "fn a() {}";
 146    let buffer = cx.add_model(|cx| {
 147        Buffer::new(0, text, cx).with_language(Some(Arc::new(rust_lang())), None, cx)
 148    });
 149
 150    // Wait for the initial text to parse
 151    buffer
 152        .condition(&cx, |buffer, _| !buffer.is_parsing())
 153        .await;
 154    assert_eq!(
 155        get_tree_sexp(&buffer, &cx),
 156        concat!(
 157            "(source_file (function_item name: (identifier) ",
 158            "parameters: (parameters) ",
 159            "body: (block)))"
 160        )
 161    );
 162
 163    buffer.update(&mut cx, |buffer, _| {
 164        buffer.set_sync_parse_timeout(Duration::ZERO)
 165    });
 166
 167    // Perform some edits (add parameter and variable reference)
 168    // Parsing doesn't begin until the transaction is complete
 169    buffer.update(&mut cx, |buf, cx| {
 170        buf.start_transaction(None).unwrap();
 171
 172        let offset = buf.text().find(")").unwrap();
 173        buf.edit(vec![offset..offset], "b: C", cx);
 174        assert!(!buf.is_parsing());
 175
 176        let offset = buf.text().find("}").unwrap();
 177        buf.edit(vec![offset..offset], " d; ", cx);
 178        assert!(!buf.is_parsing());
 179
 180        buf.end_transaction(None, cx).unwrap();
 181        assert_eq!(buf.text(), "fn a(b: C) { d; }");
 182        assert!(buf.is_parsing());
 183    });
 184    buffer
 185        .condition(&cx, |buffer, _| !buffer.is_parsing())
 186        .await;
 187    assert_eq!(
 188        get_tree_sexp(&buffer, &cx),
 189        concat!(
 190            "(source_file (function_item name: (identifier) ",
 191            "parameters: (parameters (parameter pattern: (identifier) type: (type_identifier))) ",
 192            "body: (block (identifier))))"
 193        )
 194    );
 195
 196    // Perform a series of edits without waiting for the current parse to complete:
 197    // * turn identifier into a field expression
 198    // * turn field expression into a method call
 199    // * add a turbofish to the method call
 200    buffer.update(&mut cx, |buf, cx| {
 201        let offset = buf.text().find(";").unwrap();
 202        buf.edit(vec![offset..offset], ".e", cx);
 203        assert_eq!(buf.text(), "fn a(b: C) { d.e; }");
 204        assert!(buf.is_parsing());
 205    });
 206    buffer.update(&mut cx, |buf, cx| {
 207        let offset = buf.text().find(";").unwrap();
 208        buf.edit(vec![offset..offset], "(f)", cx);
 209        assert_eq!(buf.text(), "fn a(b: C) { d.e(f); }");
 210        assert!(buf.is_parsing());
 211    });
 212    buffer.update(&mut cx, |buf, cx| {
 213        let offset = buf.text().find("(f)").unwrap();
 214        buf.edit(vec![offset..offset], "::<G>", cx);
 215        assert_eq!(buf.text(), "fn a(b: C) { d.e::<G>(f); }");
 216        assert!(buf.is_parsing());
 217    });
 218    buffer
 219        .condition(&cx, |buffer, _| !buffer.is_parsing())
 220        .await;
 221    assert_eq!(
 222        get_tree_sexp(&buffer, &cx),
 223        concat!(
 224            "(source_file (function_item name: (identifier) ",
 225            "parameters: (parameters (parameter pattern: (identifier) type: (type_identifier))) ",
 226            "body: (block (call_expression ",
 227            "function: (generic_function ",
 228            "function: (field_expression value: (identifier) field: (field_identifier)) ",
 229            "type_arguments: (type_arguments (type_identifier))) ",
 230            "arguments: (arguments (identifier))))))",
 231        )
 232    );
 233
 234    buffer.update(&mut cx, |buf, cx| {
 235        buf.undo(cx);
 236        assert_eq!(buf.text(), "fn a() {}");
 237        assert!(buf.is_parsing());
 238    });
 239    buffer
 240        .condition(&cx, |buffer, _| !buffer.is_parsing())
 241        .await;
 242    assert_eq!(
 243        get_tree_sexp(&buffer, &cx),
 244        concat!(
 245            "(source_file (function_item name: (identifier) ",
 246            "parameters: (parameters) ",
 247            "body: (block)))"
 248        )
 249    );
 250
 251    buffer.update(&mut cx, |buf, cx| {
 252        buf.redo(cx);
 253        assert_eq!(buf.text(), "fn a(b: C) { d.e::<G>(f); }");
 254        assert!(buf.is_parsing());
 255    });
 256    buffer
 257        .condition(&cx, |buffer, _| !buffer.is_parsing())
 258        .await;
 259    assert_eq!(
 260        get_tree_sexp(&buffer, &cx),
 261        concat!(
 262            "(source_file (function_item name: (identifier) ",
 263            "parameters: (parameters (parameter pattern: (identifier) type: (type_identifier))) ",
 264            "body: (block (call_expression ",
 265            "function: (generic_function ",
 266            "function: (field_expression value: (identifier) field: (field_identifier)) ",
 267            "type_arguments: (type_arguments (type_identifier))) ",
 268            "arguments: (arguments (identifier))))))",
 269        )
 270    );
 271
 272    fn get_tree_sexp(buffer: &ModelHandle<Buffer>, cx: &gpui::TestAppContext) -> String {
 273        buffer.read_with(cx, |buffer, _| {
 274            buffer.syntax_tree().unwrap().root_node().to_sexp()
 275        })
 276    }
 277}
 278
 279#[gpui::test]
 280fn test_enclosing_bracket_ranges(cx: &mut MutableAppContext) {
 281    let buffer = cx.add_model(|cx| {
 282        let text = "
 283            mod x {
 284                mod y {
 285
 286                }
 287            }
 288        "
 289        .unindent();
 290        Buffer::new(0, text, cx).with_language(Some(Arc::new(rust_lang())), None, cx)
 291    });
 292    let buffer = buffer.read(cx);
 293    assert_eq!(
 294        buffer.enclosing_bracket_point_ranges(Point::new(1, 6)..Point::new(1, 6)),
 295        Some((
 296            Point::new(0, 6)..Point::new(0, 7),
 297            Point::new(4, 0)..Point::new(4, 1)
 298        ))
 299    );
 300    assert_eq!(
 301        buffer.enclosing_bracket_point_ranges(Point::new(1, 10)..Point::new(1, 10)),
 302        Some((
 303            Point::new(1, 10)..Point::new(1, 11),
 304            Point::new(3, 4)..Point::new(3, 5)
 305        ))
 306    );
 307    assert_eq!(
 308        buffer.enclosing_bracket_point_ranges(Point::new(3, 5)..Point::new(3, 5)),
 309        Some((
 310            Point::new(1, 10)..Point::new(1, 11),
 311            Point::new(3, 4)..Point::new(3, 5)
 312        ))
 313    );
 314}
 315
 316#[gpui::test]
 317fn test_edit_with_autoindent(cx: &mut MutableAppContext) {
 318    cx.add_model(|cx| {
 319        let text = "fn a() {}";
 320        let mut buffer =
 321            Buffer::new(0, text, cx).with_language(Some(Arc::new(rust_lang())), None, cx);
 322
 323        buffer.edit_with_autoindent([8..8], "\n\n", cx);
 324        assert_eq!(buffer.text(), "fn a() {\n    \n}");
 325
 326        buffer.edit_with_autoindent([Point::new(1, 4)..Point::new(1, 4)], "b()\n", cx);
 327        assert_eq!(buffer.text(), "fn a() {\n    b()\n    \n}");
 328
 329        buffer.edit_with_autoindent([Point::new(2, 4)..Point::new(2, 4)], ".c", cx);
 330        assert_eq!(buffer.text(), "fn a() {\n    b()\n        .c\n}");
 331
 332        buffer
 333    });
 334}
 335
 336#[gpui::test]
 337fn test_autoindent_moves_selections(cx: &mut MutableAppContext) {
 338    cx.add_model(|cx| {
 339        let text = "fn a() {}";
 340
 341        let mut buffer =
 342            Buffer::new(0, text, cx).with_language(Some(Arc::new(rust_lang())), None, cx);
 343
 344        let selection_set_id = buffer.add_selection_set::<usize>(&[], cx);
 345        buffer.start_transaction(Some(selection_set_id)).unwrap();
 346        buffer.edit_with_autoindent([5..5, 9..9], "\n\n", cx);
 347        buffer
 348            .update_selection_set(
 349                selection_set_id,
 350                &[
 351                    Selection {
 352                        id: 0,
 353                        start: Point::new(1, 0),
 354                        end: Point::new(1, 0),
 355                        reversed: false,
 356                        goal: SelectionGoal::None,
 357                    },
 358                    Selection {
 359                        id: 1,
 360                        start: Point::new(4, 0),
 361                        end: Point::new(4, 0),
 362                        reversed: false,
 363                        goal: SelectionGoal::None,
 364                    },
 365                ],
 366                cx,
 367            )
 368            .unwrap();
 369        assert_eq!(buffer.text(), "fn a(\n\n) {}\n\n");
 370
 371        // Ending the transaction runs the auto-indent. The selection
 372        // at the start of the auto-indented row is pushed to the right.
 373        buffer.end_transaction(Some(selection_set_id), cx).unwrap();
 374        assert_eq!(buffer.text(), "fn a(\n    \n) {}\n\n");
 375        let selection_ranges = buffer
 376            .selection_set(selection_set_id)
 377            .unwrap()
 378            .selections::<Point>(&buffer)
 379            .map(|selection| selection.start.to_point(&buffer)..selection.end.to_point(&buffer))
 380            .collect::<Vec<_>>();
 381
 382        assert_eq!(selection_ranges[0], empty(Point::new(1, 4)));
 383        assert_eq!(selection_ranges[1], empty(Point::new(4, 0)));
 384
 385        buffer
 386    });
 387}
 388
 389#[gpui::test]
 390fn test_autoindent_does_not_adjust_lines_with_unchanged_suggestion(cx: &mut MutableAppContext) {
 391    cx.add_model(|cx| {
 392        let text = "
 393            fn a() {
 394            c;
 395            d;
 396            }
 397        "
 398        .unindent();
 399
 400        let mut buffer =
 401            Buffer::new(0, text, cx).with_language(Some(Arc::new(rust_lang())), None, cx);
 402
 403        // Lines 2 and 3 don't match the indentation suggestion. When editing these lines,
 404        // their indentation is not adjusted.
 405        buffer.edit_with_autoindent([empty(Point::new(1, 1)), empty(Point::new(2, 1))], "()", cx);
 406        assert_eq!(
 407            buffer.text(),
 408            "
 409            fn a() {
 410            c();
 411            d();
 412            }
 413            "
 414            .unindent()
 415        );
 416
 417        // When appending new content after these lines, the indentation is based on the
 418        // preceding lines' actual indentation.
 419        buffer.edit_with_autoindent(
 420            [empty(Point::new(1, 1)), empty(Point::new(2, 1))],
 421            "\n.f\n.g",
 422            cx,
 423        );
 424        assert_eq!(
 425            buffer.text(),
 426            "
 427            fn a() {
 428            c
 429                .f
 430                .g();
 431            d
 432                .f
 433                .g();
 434            }
 435            "
 436            .unindent()
 437        );
 438        buffer
 439    });
 440}
 441
 442#[gpui::test]
 443fn test_autoindent_adjusts_lines_when_only_text_changes(cx: &mut MutableAppContext) {
 444    cx.add_model(|cx| {
 445        let text = "
 446            fn a() {}
 447        "
 448        .unindent();
 449
 450        let mut buffer =
 451            Buffer::new(0, text, cx).with_language(Some(Arc::new(rust_lang())), None, cx);
 452
 453        buffer.edit_with_autoindent([5..5], "\nb", cx);
 454        assert_eq!(
 455            buffer.text(),
 456            "
 457                fn a(
 458                    b) {}
 459            "
 460            .unindent()
 461        );
 462
 463        // The indentation suggestion changed because `@end` node (a close paren)
 464        // is now at the beginning of the line.
 465        buffer.edit_with_autoindent([Point::new(1, 4)..Point::new(1, 5)], "", cx);
 466        assert_eq!(
 467            buffer.text(),
 468            "
 469                fn a(
 470                ) {}
 471            "
 472            .unindent()
 473        );
 474
 475        buffer
 476    });
 477}
 478
 479#[gpui::test]
 480async fn test_diagnostics(mut cx: gpui::TestAppContext) {
 481    let (language_server, mut fake) = lsp::LanguageServer::fake(cx.background()).await;
 482    let mut rust_lang = rust_lang();
 483    rust_lang.config.language_server = Some(LanguageServerConfig {
 484        disk_based_diagnostic_sources: HashSet::from_iter(["disk".to_string()]),
 485        ..Default::default()
 486    });
 487
 488    let text = "
 489        fn a() { A }
 490        fn b() { BB }
 491        fn c() { CCC }
 492    "
 493    .unindent();
 494
 495    let buffer = cx.add_model(|cx| {
 496        Buffer::new(0, text, cx).with_language(Some(Arc::new(rust_lang)), Some(language_server), cx)
 497    });
 498
 499    let open_notification = fake
 500        .receive_notification::<lsp::notification::DidOpenTextDocument>()
 501        .await;
 502
 503    // Edit the buffer, moving the content down
 504    buffer.update(&mut cx, |buffer, cx| buffer.edit([0..0], "\n\n", cx));
 505    let change_notification_1 = fake
 506        .receive_notification::<lsp::notification::DidChangeTextDocument>()
 507        .await;
 508    assert!(change_notification_1.text_document.version > open_notification.text_document.version);
 509
 510    buffer.update(&mut cx, |buffer, cx| {
 511        // Receive diagnostics for an earlier version of the buffer.
 512        buffer
 513            .update_diagnostics(
 514                Some(open_notification.text_document.version),
 515                vec![
 516                    lsp::Diagnostic {
 517                        range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
 518                        severity: Some(lsp::DiagnosticSeverity::ERROR),
 519                        message: "undefined variable 'A'".to_string(),
 520                        ..Default::default()
 521                    },
 522                    lsp::Diagnostic {
 523                        range: lsp::Range::new(lsp::Position::new(1, 9), lsp::Position::new(1, 11)),
 524                        severity: Some(lsp::DiagnosticSeverity::ERROR),
 525                        message: "undefined variable 'BB'".to_string(),
 526                        ..Default::default()
 527                    },
 528                    lsp::Diagnostic {
 529                        range: lsp::Range::new(lsp::Position::new(2, 9), lsp::Position::new(2, 12)),
 530                        severity: Some(lsp::DiagnosticSeverity::ERROR),
 531                        message: "undefined variable 'CCC'".to_string(),
 532                        ..Default::default()
 533                    },
 534                ],
 535                cx,
 536            )
 537            .unwrap();
 538
 539        // The diagnostics have moved down since they were created.
 540        assert_eq!(
 541            buffer
 542                .diagnostics_in_range(Point::new(3, 0)..Point::new(5, 0))
 543                .collect::<Vec<_>>(),
 544            &[
 545                (
 546                    Point::new(3, 9)..Point::new(3, 11),
 547                    &Diagnostic {
 548                        severity: DiagnosticSeverity::ERROR,
 549                        message: "undefined variable 'BB'".to_string(),
 550                        group_id: 1,
 551                        is_primary: true,
 552                    },
 553                ),
 554                (
 555                    Point::new(4, 9)..Point::new(4, 12),
 556                    &Diagnostic {
 557                        severity: DiagnosticSeverity::ERROR,
 558                        message: "undefined variable 'CCC'".to_string(),
 559                        group_id: 2,
 560                        is_primary: true,
 561                    }
 562                )
 563            ]
 564        );
 565        assert_eq!(
 566            chunks_with_diagnostics(buffer, 0..buffer.len()),
 567            [
 568                ("\n\nfn a() { ".to_string(), None),
 569                ("A".to_string(), Some(DiagnosticSeverity::ERROR)),
 570                (" }\nfn b() { ".to_string(), None),
 571                ("BB".to_string(), Some(DiagnosticSeverity::ERROR)),
 572                (" }\nfn c() { ".to_string(), None),
 573                ("CCC".to_string(), Some(DiagnosticSeverity::ERROR)),
 574                (" }\n".to_string(), None),
 575            ]
 576        );
 577        assert_eq!(
 578            chunks_with_diagnostics(buffer, Point::new(3, 10)..Point::new(4, 11)),
 579            [
 580                ("B".to_string(), Some(DiagnosticSeverity::ERROR)),
 581                (" }\nfn c() { ".to_string(), None),
 582                ("CC".to_string(), Some(DiagnosticSeverity::ERROR)),
 583            ]
 584        );
 585
 586        // Ensure overlapping diagnostics are highlighted correctly.
 587        buffer
 588            .update_diagnostics(
 589                Some(open_notification.text_document.version),
 590                vec![
 591                    lsp::Diagnostic {
 592                        range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
 593                        severity: Some(lsp::DiagnosticSeverity::ERROR),
 594                        message: "undefined variable 'A'".to_string(),
 595                        ..Default::default()
 596                    },
 597                    lsp::Diagnostic {
 598                        range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 12)),
 599                        severity: Some(lsp::DiagnosticSeverity::WARNING),
 600                        message: "unreachable statement".to_string(),
 601                        ..Default::default()
 602                    },
 603                ],
 604                cx,
 605            )
 606            .unwrap();
 607        assert_eq!(
 608            buffer
 609                .diagnostics_in_range(Point::new(2, 0)..Point::new(3, 0))
 610                .collect::<Vec<_>>(),
 611            &[
 612                (
 613                    Point::new(2, 9)..Point::new(2, 12),
 614                    &Diagnostic {
 615                        severity: DiagnosticSeverity::WARNING,
 616                        message: "unreachable statement".to_string(),
 617                        group_id: 1,
 618                        is_primary: true,
 619                    }
 620                ),
 621                (
 622                    Point::new(2, 9)..Point::new(2, 10),
 623                    &Diagnostic {
 624                        severity: DiagnosticSeverity::ERROR,
 625                        message: "undefined variable 'A'".to_string(),
 626                        group_id: 0,
 627                        is_primary: true,
 628                    },
 629                )
 630            ]
 631        );
 632        assert_eq!(
 633            chunks_with_diagnostics(buffer, Point::new(2, 0)..Point::new(3, 0)),
 634            [
 635                ("fn a() { ".to_string(), None),
 636                ("A".to_string(), Some(DiagnosticSeverity::ERROR)),
 637                (" }".to_string(), Some(DiagnosticSeverity::WARNING)),
 638                ("\n".to_string(), None),
 639            ]
 640        );
 641        assert_eq!(
 642            chunks_with_diagnostics(buffer, Point::new(2, 10)..Point::new(3, 0)),
 643            [
 644                (" }".to_string(), Some(DiagnosticSeverity::WARNING)),
 645                ("\n".to_string(), None),
 646            ]
 647        );
 648    });
 649
 650    // Keep editing the buffer and ensure disk-based diagnostics get translated according to the
 651    // changes since the last save.
 652    buffer.update(&mut cx, |buffer, cx| {
 653        buffer.edit(Some(Point::new(2, 0)..Point::new(2, 0)), "    ", cx);
 654        buffer.edit(Some(Point::new(2, 8)..Point::new(2, 10)), "(x: usize)", cx);
 655    });
 656    let change_notification_2 = fake
 657        .receive_notification::<lsp::notification::DidChangeTextDocument>()
 658        .await;
 659    assert!(
 660        change_notification_2.text_document.version > change_notification_1.text_document.version
 661    );
 662
 663    buffer.update(&mut cx, |buffer, cx| {
 664        buffer
 665            .update_diagnostics(
 666                Some(change_notification_2.text_document.version),
 667                vec![
 668                    lsp::Diagnostic {
 669                        range: lsp::Range::new(lsp::Position::new(1, 9), lsp::Position::new(1, 11)),
 670                        severity: Some(lsp::DiagnosticSeverity::ERROR),
 671                        message: "undefined variable 'BB'".to_string(),
 672                        source: Some("disk".to_string()),
 673                        ..Default::default()
 674                    },
 675                    lsp::Diagnostic {
 676                        range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
 677                        severity: Some(lsp::DiagnosticSeverity::ERROR),
 678                        message: "undefined variable 'A'".to_string(),
 679                        source: Some("disk".to_string()),
 680                        ..Default::default()
 681                    },
 682                ],
 683                cx,
 684            )
 685            .unwrap();
 686        assert_eq!(
 687            buffer
 688                .diagnostics_in_range(0..buffer.len())
 689                .collect::<Vec<_>>(),
 690            &[
 691                (
 692                    Point::new(2, 21)..Point::new(2, 22),
 693                    &Diagnostic {
 694                        severity: DiagnosticSeverity::ERROR,
 695                        message: "undefined variable 'A'".to_string(),
 696                        group_id: 0,
 697                        is_primary: true,
 698                    }
 699                ),
 700                (
 701                    Point::new(3, 9)..Point::new(3, 11),
 702                    &Diagnostic {
 703                        severity: DiagnosticSeverity::ERROR,
 704                        message: "undefined variable 'BB'".to_string(),
 705                        group_id: 1,
 706                        is_primary: true,
 707                    },
 708                )
 709            ]
 710        );
 711    });
 712}
 713
 714#[gpui::test]
 715async fn test_empty_diagnostic_ranges(mut cx: gpui::TestAppContext) {
 716    cx.add_model(|cx| {
 717        let text = concat!(
 718            "let one = ;\n", //
 719            "let two = \n",
 720            "let three = 3;\n",
 721        );
 722
 723        let mut buffer = Buffer::new(0, text, cx);
 724        buffer.set_language(Some(Arc::new(rust_lang())), None, cx);
 725        buffer
 726            .update_diagnostics(
 727                None,
 728                vec![
 729                    lsp::Diagnostic {
 730                        range: lsp::Range::new(
 731                            lsp::Position::new(0, 10),
 732                            lsp::Position::new(0, 10),
 733                        ),
 734                        severity: Some(lsp::DiagnosticSeverity::ERROR),
 735                        message: "syntax error 1".to_string(),
 736                        ..Default::default()
 737                    },
 738                    lsp::Diagnostic {
 739                        range: lsp::Range::new(
 740                            lsp::Position::new(1, 10),
 741                            lsp::Position::new(1, 10),
 742                        ),
 743                        severity: Some(lsp::DiagnosticSeverity::ERROR),
 744                        message: "syntax error 2".to_string(),
 745                        ..Default::default()
 746                    },
 747                ],
 748                cx,
 749            )
 750            .unwrap();
 751
 752        // An empty range is extended forward to include the following character.
 753        // At the end of a line, an empty range is extended backward to include
 754        // the preceding character.
 755        let chunks = chunks_with_diagnostics(&buffer, 0..buffer.len());
 756        assert_eq!(
 757            chunks
 758                .iter()
 759                .map(|(s, d)| (s.as_str(), *d))
 760                .collect::<Vec<_>>(),
 761            &[
 762                ("let one = ", None),
 763                (";", Some(lsp::DiagnosticSeverity::ERROR)),
 764                ("\nlet two =", None),
 765                (" ", Some(lsp::DiagnosticSeverity::ERROR)),
 766                ("\nlet three = 3;\n", None)
 767            ]
 768        );
 769        buffer
 770    });
 771}
 772
 773#[gpui::test]
 774async fn test_grouped_diagnostics(mut cx: gpui::TestAppContext) {
 775    cx.add_model(|cx| {
 776        let text = "
 777            fn foo(mut v: Vec<usize>) {
 778                for x in &v {
 779                    v.push(1);
 780                }
 781            }
 782        "
 783        .unindent();
 784
 785        let file = FakeFile::new("/example.rs");
 786        let mut buffer = Buffer::from_file(0, text, Box::new(file.clone()), cx);
 787        buffer.set_language(Some(Arc::new(rust_lang())), None, cx);
 788        let diagnostics = vec![
 789            lsp::Diagnostic {
 790                range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
 791                severity: Some(DiagnosticSeverity::WARNING),
 792                message: "error 1".to_string(),
 793                related_information: Some(vec![lsp::DiagnosticRelatedInformation {
 794                    location: lsp::Location {
 795                        uri: lsp::Url::from_file_path(&file.abs_path).unwrap(),
 796                        range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
 797                    },
 798                    message: "error 1 hint 1".to_string(),
 799                }]),
 800                ..Default::default()
 801            },
 802            lsp::Diagnostic {
 803                range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
 804                severity: Some(DiagnosticSeverity::HINT),
 805                message: "error 1 hint 1".to_string(),
 806                related_information: Some(vec![lsp::DiagnosticRelatedInformation {
 807                    location: lsp::Location {
 808                        uri: lsp::Url::from_file_path(&file.abs_path).unwrap(),
 809                        range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
 810                    },
 811                    message: "original diagnostic".to_string(),
 812                }]),
 813                ..Default::default()
 814            },
 815            lsp::Diagnostic {
 816                range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
 817                severity: Some(DiagnosticSeverity::ERROR),
 818                message: "error 2".to_string(),
 819                related_information: Some(vec![
 820                    lsp::DiagnosticRelatedInformation {
 821                        location: lsp::Location {
 822                            uri: lsp::Url::from_file_path(&file.abs_path).unwrap(),
 823                            range: lsp::Range::new(
 824                                lsp::Position::new(1, 13),
 825                                lsp::Position::new(1, 15),
 826                            ),
 827                        },
 828                        message: "error 2 hint 1".to_string(),
 829                    },
 830                    lsp::DiagnosticRelatedInformation {
 831                        location: lsp::Location {
 832                            uri: lsp::Url::from_file_path(&file.abs_path).unwrap(),
 833                            range: lsp::Range::new(
 834                                lsp::Position::new(1, 13),
 835                                lsp::Position::new(1, 15),
 836                            ),
 837                        },
 838                        message: "error 2 hint 2".to_string(),
 839                    },
 840                ]),
 841                ..Default::default()
 842            },
 843            lsp::Diagnostic {
 844                range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
 845                severity: Some(DiagnosticSeverity::HINT),
 846                message: "error 2 hint 1".to_string(),
 847                related_information: Some(vec![lsp::DiagnosticRelatedInformation {
 848                    location: lsp::Location {
 849                        uri: lsp::Url::from_file_path(&file.abs_path).unwrap(),
 850                        range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
 851                    },
 852                    message: "original diagnostic".to_string(),
 853                }]),
 854                ..Default::default()
 855            },
 856            lsp::Diagnostic {
 857                range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
 858                severity: Some(DiagnosticSeverity::HINT),
 859                message: "error 2 hint 2".to_string(),
 860                related_information: Some(vec![lsp::DiagnosticRelatedInformation {
 861                    location: lsp::Location {
 862                        uri: lsp::Url::from_file_path(&file.abs_path).unwrap(),
 863                        range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
 864                    },
 865                    message: "original diagnostic".to_string(),
 866                }]),
 867                ..Default::default()
 868            },
 869        ];
 870        buffer.update_diagnostics(None, diagnostics, cx).unwrap();
 871        assert_eq!(
 872            buffer
 873                .diagnostics_in_range::<_, Point>(0..buffer.len())
 874                .collect::<Vec<_>>(),
 875            &[
 876                (
 877                    Point::new(1, 8)..Point::new(1, 9),
 878                    &Diagnostic {
 879                        severity: DiagnosticSeverity::WARNING,
 880                        message: "error 1".to_string(),
 881                        group_id: 0,
 882                        is_primary: true,
 883                    }
 884                ),
 885                (
 886                    Point::new(1, 8)..Point::new(1, 9),
 887                    &Diagnostic {
 888                        severity: DiagnosticSeverity::HINT,
 889                        message: "error 1 hint 1".to_string(),
 890                        group_id: 0,
 891                        is_primary: false,
 892                    }
 893                ),
 894                (
 895                    Point::new(1, 13)..Point::new(1, 15),
 896                    &Diagnostic {
 897                        severity: DiagnosticSeverity::HINT,
 898                        message: "error 2 hint 1".to_string(),
 899                        group_id: 1,
 900                        is_primary: false,
 901                    }
 902                ),
 903                (
 904                    Point::new(1, 13)..Point::new(1, 15),
 905                    &Diagnostic {
 906                        severity: DiagnosticSeverity::HINT,
 907                        message: "error 2 hint 2".to_string(),
 908                        group_id: 1,
 909                        is_primary: false,
 910                    }
 911                ),
 912                (
 913                    Point::new(2, 8)..Point::new(2, 17),
 914                    &Diagnostic {
 915                        severity: DiagnosticSeverity::ERROR,
 916                        message: "error 2".to_string(),
 917                        group_id: 1,
 918                        is_primary: true,
 919                    }
 920                )
 921            ]
 922        );
 923
 924        assert_eq!(
 925            buffer.diagnostic_group(0).collect::<Vec<_>>(),
 926            &[
 927                (
 928                    Point::new(1, 8)..Point::new(1, 9),
 929                    &Diagnostic {
 930                        severity: DiagnosticSeverity::WARNING,
 931                        message: "error 1".to_string(),
 932                        group_id: 0,
 933                        is_primary: true,
 934                    }
 935                ),
 936                (
 937                    Point::new(1, 8)..Point::new(1, 9),
 938                    &Diagnostic {
 939                        severity: DiagnosticSeverity::HINT,
 940                        message: "error 1 hint 1".to_string(),
 941                        group_id: 0,
 942                        is_primary: false,
 943                    }
 944                ),
 945            ]
 946        );
 947        assert_eq!(
 948            buffer.diagnostic_group(1).collect::<Vec<_>>(),
 949            &[
 950                (
 951                    Point::new(1, 13)..Point::new(1, 15),
 952                    &Diagnostic {
 953                        severity: DiagnosticSeverity::HINT,
 954                        message: "error 2 hint 1".to_string(),
 955                        group_id: 1,
 956                        is_primary: false,
 957                    }
 958                ),
 959                (
 960                    Point::new(1, 13)..Point::new(1, 15),
 961                    &Diagnostic {
 962                        severity: DiagnosticSeverity::HINT,
 963                        message: "error 2 hint 2".to_string(),
 964                        group_id: 1,
 965                        is_primary: false,
 966                    }
 967                ),
 968                (
 969                    Point::new(2, 8)..Point::new(2, 17),
 970                    &Diagnostic {
 971                        severity: DiagnosticSeverity::ERROR,
 972                        message: "error 2".to_string(),
 973                        group_id: 1,
 974                        is_primary: true,
 975                    }
 976                )
 977            ]
 978        );
 979
 980        buffer
 981    });
 982}
 983
 984fn chunks_with_diagnostics<T: ToOffset + ToPoint>(
 985    buffer: &Buffer,
 986    range: Range<T>,
 987) -> Vec<(String, Option<DiagnosticSeverity>)> {
 988    let mut chunks: Vec<(String, Option<DiagnosticSeverity>)> = Vec::new();
 989    for chunk in buffer.snapshot().chunks(range, Some(&Default::default())) {
 990        if chunks
 991            .last()
 992            .map_or(false, |prev_chunk| prev_chunk.1 == chunk.diagnostic)
 993        {
 994            chunks.last_mut().unwrap().0.push_str(chunk.text);
 995        } else {
 996            chunks.push((chunk.text.to_string(), chunk.diagnostic));
 997        }
 998    }
 999    chunks
1000}
1001
1002#[test]
1003fn test_contiguous_ranges() {
1004    assert_eq!(
1005        contiguous_ranges([1, 2, 3, 5, 6, 9, 10, 11, 12], 100).collect::<Vec<_>>(),
1006        &[1..4, 5..7, 9..13]
1007    );
1008
1009    // Respects the `max_len` parameter
1010    assert_eq!(
1011        contiguous_ranges([2, 3, 4, 5, 6, 7, 8, 9, 23, 24, 25, 26, 30, 31], 3).collect::<Vec<_>>(),
1012        &[2..5, 5..8, 8..10, 23..26, 26..27, 30..32],
1013    );
1014}
1015
1016impl Buffer {
1017    pub fn enclosing_bracket_point_ranges<T: ToOffset>(
1018        &self,
1019        range: Range<T>,
1020    ) -> Option<(Range<Point>, Range<Point>)> {
1021        self.enclosing_bracket_ranges(range).map(|(start, end)| {
1022            let point_start = start.start.to_point(self)..start.end.to_point(self);
1023            let point_end = end.start.to_point(self)..end.end.to_point(self);
1024            (point_start, point_end)
1025        })
1026    }
1027}
1028
1029fn rust_lang() -> Language {
1030    Language::new(
1031        LanguageConfig {
1032            name: "Rust".to_string(),
1033            path_suffixes: vec!["rs".to_string()],
1034            language_server: None,
1035            ..Default::default()
1036        },
1037        Some(tree_sitter_rust::language()),
1038    )
1039    .with_indents_query(
1040        r#"
1041                (call_expression) @indent
1042                (field_expression) @indent
1043                (_ "(" ")" @end) @indent
1044                (_ "{" "}" @end) @indent
1045            "#,
1046    )
1047    .unwrap()
1048    .with_brackets_query(r#" ("{" @open "}" @close) "#)
1049    .unwrap()
1050}
1051
1052fn empty(point: Point) -> Range<Point> {
1053    point..point
1054}
1055
1056#[derive(Clone)]
1057struct FakeFile {
1058    abs_path: PathBuf,
1059}
1060
1061impl FakeFile {
1062    fn new(abs_path: impl Into<PathBuf>) -> Self {
1063        Self {
1064            abs_path: abs_path.into(),
1065        }
1066    }
1067}
1068
1069impl File for FakeFile {
1070    fn worktree_id(&self) -> usize {
1071        todo!()
1072    }
1073
1074    fn entry_id(&self) -> Option<usize> {
1075        todo!()
1076    }
1077
1078    fn mtime(&self) -> SystemTime {
1079        SystemTime::now()
1080    }
1081
1082    fn path(&self) -> &Arc<Path> {
1083        todo!()
1084    }
1085
1086    fn abs_path(&self) -> Option<PathBuf> {
1087        Some(self.abs_path.clone())
1088    }
1089
1090    fn full_path(&self) -> PathBuf {
1091        todo!()
1092    }
1093
1094    fn file_name(&self) -> Option<OsString> {
1095        todo!()
1096    }
1097
1098    fn is_deleted(&self) -> bool {
1099        todo!()
1100    }
1101
1102    fn save(
1103        &self,
1104        _: u64,
1105        _: Rope,
1106        _: clock::Global,
1107        _: &mut MutableAppContext,
1108    ) -> Task<Result<(clock::Global, SystemTime)>> {
1109        todo!()
1110    }
1111
1112    fn load_local(&self, _: &AppContext) -> Option<Task<Result<String>>> {
1113        todo!()
1114    }
1115
1116    fn buffer_updated(&self, _: u64, _: super::Operation, _: &mut MutableAppContext) {
1117        todo!()
1118    }
1119
1120    fn buffer_removed(&self, _: u64, _: &mut MutableAppContext) {
1121        todo!()
1122    }
1123
1124    fn boxed_clone(&self) -> Box<dyn File> {
1125        todo!()
1126    }
1127
1128    fn as_any(&self) -> &dyn Any {
1129        todo!()
1130    }
1131}