tests.rs

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