summaryrefslogtreecommitdiffstats
path: root/src/tools/rust-analyzer/crates/ide-db/src/use_trivial_constructor.rs
blob: f96ea29ae2f9d1df722985d87b00dd9e4c5a1fb1 (plain)
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
//! Functionality for generating trivial constructors

use hir::StructKind;
use syntax::ast;

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

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

    None
}