Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
((comment) @injection.content
	(#set! injection.language "comment"))

; There are 3 ways to define a regex
;    - "[abc]?".toRegex()
((call_expression
	(navigation_expression
		([(line_string_literal) (multi_line_string_literal)] @injection.content)
		(navigation_suffix
			((simple_identifier) @_function
			(#eq? @_function "toRegex")))))
	(#set! injection.language "regex"))

;    - Regex("[abc]?")
((call_expression
	((simple_identifier) @_function
	(#eq? @_function "Regex"))
	(call_suffix
		(value_arguments
			(value_argument
				[ (line_string_literal) (multi_line_string_literal) ] @injection.content))))
	(#set! injection.language "regex"))

;    - Regex.fromLiteral("[abc]?")
((call_expression
	(navigation_expression
		((simple_identifier) @_class
		(#eq? @_class "Regex"))
		(navigation_suffix
			((simple_identifier) @_function
			(#eq? @_function "fromLiteral"))))
	(call_suffix
		(value_arguments
			(value_argument
				[ (line_string_literal) (multi_line_string_literal) ] @injection.content))))
	(#set! injection.language "regex"))
11' href='#n111'>111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
use either::Either;
use hir::{
    db::{ExpandDatabase, HirDatabase},
    known, AssocItem, HirDisplay, HirFileIdExt, InFile, Type,
};
use ide_db::{
    assists::Assist, famous_defs::FamousDefs, imports::import_assets::item_for_path_search,
    source_change::SourceChange, use_trivial_constructor::use_trivial_constructor, FxHashMap,
};
use stdx::format_to;
use syntax::{
    algo,
    ast::{self, make},
    AstNode, SyntaxNode, SyntaxNodePtr,
};
use text_edit::TextEdit;

use crate::{fix, Diagnostic, DiagnosticCode, DiagnosticsContext};

// Diagnostic: missing-fields
//
// This diagnostic is triggered if record lacks some fields that exist in the corresponding structure.
//
// Example:
//
// ```rust
// struct A { a: u8, b: u8 }
//
// let a = A { a: 10 };
// ```
pub(crate) fn missing_fields(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Diagnostic {
    let mut message = String::from("missing structure fields:\n");
    for field in &d.missed_fields {
        format_to!(message, "- {}\n", field.display(ctx.sema.db));
    }

    let ptr = InFile::new(
        d.file,
        d.field_list_parent_path
            .clone()
            .map(SyntaxNodePtr::from)
            .unwrap_or_else(|| d.field_list_parent.clone().into()),
    );

    Diagnostic::new_with_syntax_node_ptr(ctx, DiagnosticCode::RustcHardError("E0063"), message, ptr)
        .with_fixes(fixes(ctx, d))
}

fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option<Vec<Assist>> {
    // Note that although we could add a diagnostics to
    // fill the missing tuple field, e.g :
    // `struct A(usize);`
    // `let a = A { 0: () }`
    // but it is uncommon usage and it should not be encouraged.
    if d.missed_fields.iter().any(|it| it.as_tuple_index().is_some()) {
        return None;
    }

    let root = ctx.sema.db.parse_or_expand(d.file);

    let current_module =
        ctx.sema.scope(d.field_list_parent.to_node(&root).syntax()).map(|it| it.module());

    let build_text_edit = |parent_syntax, new_syntax: &SyntaxNode, old_syntax| {
        let edit = {
            let mut builder = TextEdit::builder();
            if d.file.is_macro() {
                // we can't map the diff up into the macro input unfortunately, as the macro loses all
                // whitespace information so the diff wouldn't be applicable no matter what
                // This has the downside that the cursor will be moved in macros by doing it without a diff
                // but that is a trade off we can make.
                // FIXME: this also currently discards a lot of whitespace in the input... we really need a formatter here
                let range = ctx.sema.original_range_opt(old_syntax)?;
                builder.replace(range.range, new_syntax.to_string());
            } else {
                algo::diff(old_syntax, new_syntax).into_text_edit(&mut builder);
            }
            builder.finish()
        };
        Some(vec![fix(
            "fill_missing_fields",
            "Fill struct fields",
            SourceChange::from_text_edit(d.file.original_file(ctx.sema.db), edit),
            ctx.sema.original_range(parent_syntax).range,
        )])
    };

    match &d.field_list_parent.to_node(&root) {
        Either::Left(field_list_parent) => {
            let missing_fields = ctx.sema.record_literal_missing_fields(&field_list_parent);

            let mut locals = FxHashMap::default();
            ctx.sema.scope(field_list_parent.syntax())?.process_all_names(&mut |name, def| {
                if let hir::ScopeDef::Local(local) = def {
                    locals.insert(name, local);
                }
            });

            let generate_fill_expr = |ty: &Type| match ctx.config.expr_fill_default {
                crate::ExprFillDefaultMode::Todo => make::ext::expr_todo(),
                crate::ExprFillDefaultMode::Default => {
                    get_default_constructor(ctx, d, ty).unwrap_or_else(|| make::ext::expr_todo())
                }
            };

            let old_field_list = field_list_parent.record_expr_field_list()?;
            let new_field_list = old_field_list.clone_for_update();
            for (f, ty) in missing_fields.iter() {
                let field_expr = if let Some(local_candidate) = locals.get(&f.name(ctx.sema.db)) {
                    cov_mark::hit!(field_shorthand);
                    let candidate_ty = local_candidate.ty(ctx.sema.db);
                    if ty.could_unify_with(ctx.sema.db, &candidate_ty) {
                        None
                    } else {
                        Some(generate_fill_expr(ty))
                    }
                } else {
                    let expr = (|| -> Option<ast::Expr> {
                        let item_in_ns = hir::ItemInNs::from(hir::ModuleDef::from(ty.as_adt()?));

                        let type_path = current_module?.find_use_path(
                            ctx.sema.db,
                            item_for_path_search(ctx.sema.db, item_in_ns)?,
                            ctx.config.prefer_no_std,
                            ctx.config.prefer_prelude,
                        )?;

                        use_trivial_constructor(
                            ctx.sema.db,
                            ide_db::helpers::mod_path_to_ast(&type_path),
                            ty,
                        )
                    })();

                    if expr.is_some() {
                        expr
                    } else {
                        Some(generate_fill_expr(ty))
                    }
                };
                let field = make::record_expr_field(
                    make::name_ref(&f.name(ctx.sema.db).to_smol_str()),
                    field_expr,
                );
                new_field_list.add_field(field.clone_for_update());
            }
            build_text_edit(
                field_list_parent.syntax(),
                new_field_list.syntax(),
                old_field_list.syntax(),
            )
        }
        Either::Right(field_list_parent) => {
            let missing_fields = ctx.sema.record_pattern_missing_fields(&field_list_parent);

            let old_field_list = field_list_parent.record_pat_field_list()?;
            let new_field_list = old_field_list.clone_for_update();
            for (f, _) in missing_fields.iter() {
                let field = make::record_pat_field_shorthand(make::name_ref(
                    &f.name(ctx.sema.db).to_smol_str(),
                ));
                new_field_list.add_field(field.clone_for_update());
            }
            build_text_edit(
                field_list_parent.syntax(),
                new_field_list.syntax(),
                old_field_list.syntax(),
            )
        }
    }
}

fn make_ty(ty: &hir::Type, db: &dyn HirDatabase, module: hir::Module) -> ast::Type {
    let ty_str = match ty.as_adt() {
        Some(adt) => adt.name(db).display(db.upcast()).to_string(),
        None => {
            ty.display_source_code(db, module.into(), false).ok().unwrap_or_else(|| "_".to_string())
        }
    };

    make::ty(&ty_str)
}

fn get_default_constructor(
    ctx: &DiagnosticsContext<'_>,
    d: &hir::MissingFields,
    ty: &Type,
) -> Option<ast::Expr> {
    if let Some(builtin_ty) = ty.as_builtin() {
        if builtin_ty.is_int() || builtin_ty.is_uint() {
            return Some(make::ext::zero_number());
        }
        if builtin_ty.is_float() {
            return Some(make::ext::zero_float());
        }
        if builtin_ty.is_char() {
            return Some(make::ext::empty_char());
        }
        if builtin_ty.is_str() {
            return Some(make::ext::empty_str());
        }
        if builtin_ty.is_bool() {
            return Some(make::ext::default_bool());
        }
    }

    let krate = ctx.sema.to_module_def(d.file.original_file(ctx.sema.db))?.krate();
    let module = krate.root_module();

    // Look for a ::new() associated function
    let has_new_func = ty
        .iterate_assoc_items(ctx.sema.db, krate, |assoc_item| {
            if let AssocItem::Function(func) = assoc_item {
                if func.name(ctx.sema.db) == known::new
                    && func.assoc_fn_params(ctx.sema.db).is_empty()
                {
                    return Some(());
                }
            }

            None
        })
        .is_some();

    let famous_defs = FamousDefs(&ctx.sema, krate);
    if has_new_func {
        Some(make::ext::expr_ty_new(&make_ty(ty, ctx.sema.db, module)))
    } else if ty.as_adt() == famous_defs.core_option_Option()?.ty(ctx.sema.db).as_adt() {
        Some(make::ext::option_none())
    } else if !ty.is_array()
        && ty.impls_trait(ctx.sema.db, famous_defs.core_default_Default()?, &[])
    {
        Some(make::ext::expr_ty_default(&make_ty(ty, ctx.sema.db, module)))
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use crate::tests::{check_diagnostics, check_fix};

    #[test]
    fn missing_record_pat_field_diagnostic() {
        check_diagnostics(
            r#"
struct S { foo: i32, bar: () }
fn baz(s: S) {
    let S { foo: _ } = s;
      //^ 💡 error: missing structure fields:
      //| - bar
}
"#,
        );
    }

    #[test]
    fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
        check_diagnostics(
            r"
struct S { foo: i32, bar: () }
fn baz(s: S) -> i32 {
    match s {
        S { foo, .. } => foo,
    }
}
",
        )
    }

    #[test]
    fn missing_record_pat_field_box() {
        check_diagnostics(
            r"
struct S { s: Box<u32> }
fn x(a: S) {
    let S { box s } = a;
}
",
        )
    }

    #[test]
    fn missing_record_pat_field_ref() {
        check_diagnostics(
            r"
struct S { s: u32 }
fn x(a: S) {
    let S { ref s } = a;
    _ = s;
}
",
        )
    }

    #[test]
    fn missing_record_expr_in_assignee_expr() {
        check_diagnostics(
            r"
struct S { s: usize, t: usize }
struct S2 { s: S, t: () }
struct T(S);
fn regular(a: S) {
    let s;
    S { s, .. } = a;
}
fn nested(a: S2) {
    let s;
    S2 { s: S { s, .. }, .. } = a;
}
fn in_tuple(a: (S,)) {
    let s;
    (S { s, .. },) = a;
}
fn in_array(a: [S;1]) {
    let s;
    [S { s, .. },] = a;
}
fn in_tuple_struct(a: T) {
    let s;
    T(S { s, .. }) = a;
}
            ",
        );
    }

    #[test]
    fn range_mapping_out_of_macros() {
        check_fix(
            r#"
fn some() {}
fn items() {}
fn here() {}

macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }

fn main() {
    let _x = id![Foo { a: $042 }];
}

pub struct Foo { pub a: i32, pub b: i32 }
"#,
            r#"
fn some() {}
fn items() {}
fn here() {}

macro_rules! id { ($($tt:tt)*) => { $($tt)*}; }

fn main() {
    let _x = id![Foo {a:42, b: 0 }];
}

pub struct Foo { pub a: i32, pub b: i32 }
"#,
        );
    }

    #[test]
    fn test_fill_struct_fields_empty() {
        check_fix(
            r#"
//- minicore: option
struct TestStruct { one: i32, two: i64, three: Option<i32>, four: bool }

fn test_fn() {
    let s = TestStruct {$0};
}
"#,
            r#"
struct TestStruct { one: i32, two: i64, three: Option<i32>, four: bool }

fn test_fn() {
    let s = TestStruct { one: 0, two: 0, three: None, four: false };
}
"#,
        );
    }

    #[test]
    fn test_fill_struct_zst_fields() {
        check_fix(
            r#"
struct Empty;

struct TestStruct { one: i32, two: Empty }

fn test_fn() {
    let s = TestStruct {$0};
}
"#,
            r#"
struct Empty;

struct TestStruct { one: i32, two: Empty }

fn test_fn() {
    let s = TestStruct { one: 0, two: Empty };
}
"#,
        );
        check_fix(
            r#"
enum Empty { Foo };

struct TestStruct { one: i32, two: Empty }

fn test_fn() {
    let s = TestStruct {$0};
}
"#,
            r#"
enum Empty { Foo };

struct TestStruct { one: i32, two: Empty }

fn test_fn() {
    let s = TestStruct { one: 0, two: Empty::Foo };
}
"#,
        );

        // make sure the assist doesn't fill non Unit variants
        check_fix(
            r#"
struct Empty {};

struct TestStruct { one: i32, two: Empty }

fn test_fn() {
    let s = TestStruct {$0};
}
"#,
            r#"
struct Empty {};

struct TestStruct { one: i32, two: Empty }

fn test_fn() {
    let s = TestStruct { one: 0, two: todo!() };
}
"#,
        );
        check_fix(
            r#"
enum Empty { Foo {} };

struct TestStruct { one: i32, two: Empty }

fn test_fn() {
    let s = TestStruct {$0};
}
"#,
            r#"
enum Empty { Foo {} };

struct TestStruct { one: i32, two: Empty }

fn test_fn() {
    let s = TestStruct { one: 0, two: todo!() };
}
"#,
        );
    }

    #[test]
    fn test_fill_struct_fields_self() {
        check_fix(
            r#"
struct TestStruct { one: i32 }

impl TestStruct {
    fn test_fn() { let s = Self {$0}; }
}
"#,
            r#"
struct TestStruct { one: i32 }

impl TestStruct {
    fn test_fn() { let s = Self { one: 0 }; }
}
"#,
        );
    }

    #[test]
    fn test_fill_struct_fields_enum() {
        check_fix(
            r#"
enum Expr {
    Bin { lhs: Box<Expr>, rhs: Box<Expr> }
}

impl Expr {
    fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
        Expr::Bin {$0 }
    }
}
"#,
            r#"
enum Expr {
    Bin { lhs: Box<Expr>, rhs: Box<Expr> }
}

impl Expr {
    fn new_bin(lhs: Box<Expr>, rhs: Box<Expr>) -> Expr {
        Expr::Bin { lhs, rhs }
    }
}
"#,
        );
    }

    #[test]
    fn test_fill_struct_fields_partial() {
        check_fix(
            r#"
struct TestStruct { one: i32, two: i64 }

fn test_fn() {
    let s = TestStruct{ two: 2$0 };
}
"#,
            r"
struct TestStruct { one: i32, two: i64 }

fn test_fn() {
    let s = TestStruct{ two: 2, one: 0 };
}
",
        );
    }

    #[test]
    fn test_fill_struct_fields_new() {
        check_fix(
            r#"
struct TestWithNew(usize);
impl TestWithNew {
    pub fn new() -> Self {
        Self(0)
    }
}
struct TestStruct { one: i32, two: TestWithNew }

fn test_fn() {
    let s = TestStruct{ $0 };
}
"#,
            r"
struct TestWithNew(usize);
impl TestWithNew {
    pub fn new() -> Self {
        Self(0)
    }
}
struct TestStruct { one: i32, two: TestWithNew }

fn test_fn() {
    let s = TestStruct{ one: 0, two: TestWithNew::new()  };
}
",
        );
    }

    #[test]
    fn test_fill_struct_fields_default() {
        check_fix(
            r#"
//- minicore: default, option
struct TestWithDefault(usize);
impl Default for TestWithDefault {
    pub fn default() -> Self {
        Self(0)
    }
}
struct TestStruct { one: i32, two: TestWithDefault }

fn test_fn() {
    let s = TestStruct{ $0 };
}
"#,
            r"
struct TestWithDefault(usize);
impl Default for TestWithDefault {
    pub fn default() -> Self {
        Self(0)
    }
}
struct TestStruct { one: i32, two: TestWithDefault }

fn test_fn() {
    let s = TestStruct{ one: 0, two: TestWithDefault::default()  };
}
",
        );
    }

    #[test]
    fn test_fill_struct_fields_raw_ident() {
        check_fix(
            r#"
struct TestStruct { r#type: u8 }

fn test_fn() {
    TestStruct { $0 };
}
"#,
            r"
struct TestStruct { r#type: u8 }

fn test_fn() {
    TestStruct { r#type: 0  };
}
",
        );
    }

    #[test]
    fn test_fill_struct_fields_no_diagnostic() {
        check_diagnostics(
            r#"
struct TestStruct { one: i32, two: i64 }

fn test_fn() {
    let one = 1;
    let _s = TestStruct{ one, two: 2 };
}
        "#,
        );
    }

    #[test]
    fn test_fill_struct_fields_no_diagnostic_on_spread() {
        check_diagnostics(
            r#"
struct TestStruct { one: i32, two: i64 }

fn test_fn() {
    let one = 1;
    let s = TestStruct{ ..a };
}
"#,
        );
    }

    #[test]
    fn test_fill_struct_fields_blank_line() {
        check_fix(
            r#"
struct S { a: (), b: () }

fn f() {
    S {
        $0
    };
}
"#,
            r#"
struct S { a: (), b: () }

fn f() {
    S {
        a: todo!(),
        b: todo!(),
    };
}
"#,
        );
    }

    #[test]
    fn test_fill_struct_fields_shorthand() {
        cov_mark::check!(field_shorthand);
        check_fix(
            r#"
struct S { a: &'static str, b: i32 }

fn f() {
    let a = "hello";
    let b = 1i32;
    S {
        $0
    };
}
"#,
            r#"
struct S { a: &'static str, b: i32 }

fn f() {
    let a = "hello";
    let b = 1i32;
    S {
        a,
        b,
    };
}
"#,
        );
    }

    #[test]
    fn test_fill_struct_fields_shorthand_ty_mismatch() {
        check_fix(
            r#"
struct S { a: &'static str, b: i32 }

fn f() {
    let a = "hello";
    let b = 1usize;
    S {
        $0
    };
}
"#,
            r#"
struct S { a: &'static str, b: i32 }

fn f() {
    let a = "hello";
    let b = 1usize;
    S {
        a,
        b: 0,
    };
}
"#,
        );
    }

    #[test]
    fn test_fill_struct_fields_shorthand_unifies() {
        check_fix(
            r#"
struct S<T> { a: &'static str, b: T }

fn f() {
    let a = "hello";
    let b = 1i32;
    S {
        $0
    };
}
"#,
            r#"
struct S<T> { a: &'static str, b: T }

fn f() {
    let a = "hello";
    let b = 1i32;
    S {
        a,
        b,
    };
}
"#,
        );
    }

    #[test]
    fn test_fill_struct_pat_fields() {
        check_fix(
            r#"
struct S { a: &'static str, b: i32 }

fn f() {
    let S {
        $0
    };
}
"#,
            r#"
struct S { a: &'static str, b: i32 }

fn f() {
    let S {
        a,
        b,
    };
}
"#,
        );
    }

    #[test]
    fn test_fill_struct_pat_fields_partial() {
        check_fix(
            r#"
struct S { a: &'static str, b: i32 }

fn f() {
    let S {
        a,$0
    };
}
"#,
            r#"
struct S { a: &'static str, b: i32 }

fn f() {
    let S {
        a,
        b,
    };
}
"#,
        );
    }

    #[test]
    fn import_extern_crate_clash_with_inner_item() {
        // This is more of a resolver test, but doesn't really work with the hir_def testsuite.

        check_diagnostics(
            r#"
//- /lib.rs crate:lib deps:jwt
mod permissions;

use permissions::jwt;

fn f() {
    fn inner() {}
    jwt::Claims {}; // should resolve to the local one with 0 fields, and not get a diagnostic
}

//- /permissions.rs
pub mod jwt  {
    pub struct Claims {}
}

//- /jwt/lib.rs crate:jwt
pub struct Claims {
    field: u8,
}
        "#,
        );
    }
}