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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//! Functionality for generating trivial constructors

use hir::StructKind;
use span::Edition;
use syntax::{
    ToSmolStr,
    ast::{Expr, Path, make, syntax_factory::SyntaxFactory},
};

/// given a type return the trivial constructor (if one exists)
pub fn use_trivial_constructor(
    db: &crate::RootDatabase,
    path: Path,
    ty: &hir::Type<'_>,
    edition: Edition,
) -> Option<Expr> {
    match ty.as_adt() {
        Some(hir::Adt::Enum(x)) => {
            if let &[variant] = &*x.variants(db)
                && variant.kind(db) == hir::StructKind::Unit
            {
                let path = make::path_qualified(
                    path,
                    make::path_segment(make::name_ref(
                        &variant.name(db).display_no_db(edition).to_smolstr(),
                    )),
                );

                return Some(make::expr_path(path));
            }
        }
        Some(hir::Adt::Struct(x)) if x.kind(db) == StructKind::Unit => {
            return Some(make::expr_path(path));
        }
        _ => {}
    }

    None
}

pub fn use_trivial_constructor_with_factory(
    make: &SyntaxFactory,
    db: &crate::RootDatabase,
    path: Path,
    ty: &hir::Type<'_>,
    edition: Edition,
) -> Option<Expr> {
    match ty.as_adt() {
        Some(hir::Adt::Enum(x)) => {
            if let &[variant] = &*x.variants(db)
                && variant.kind(db) == hir::StructKind::Unit
            {
                let path = make.path_qualified(
                    path,
                    make.path_segment(
                        make.name_ref(&variant.name(db).display_no_db(edition).to_smolstr()),
                    ),
                );

                return Some(make.expr_path(path));
            }
        }
        Some(hir::Adt::Struct(x)) if x.kind(db) == StructKind::Unit => {
            return Some(make.expr_path(path));
        }
        _ => {}
    }

    None
}