rust/crates/ide-db/src/use_trivial_constructor.rs

33 lines
934 B
Rust
Raw Normal View History

//! Functionality for generating trivial constructors
2022-06-22 09:34:01 -05:00
use hir::StructKind;
2023-08-08 12:51:59 -05:00
use syntax::ast::{make, Expr, Path};
2022-06-22 09:34:01 -05:00
/// given a type return the trivial constructor (if one exists)
2022-06-22 09:34:01 -05:00
pub fn use_trivial_constructor(
db: &crate::RootDatabase,
2023-08-08 12:51:59 -05:00
path: Path,
2022-06-22 09:34:01 -05:00
ty: &hir::Type,
2023-08-08 12:51:59 -05:00
) -> Option<Expr> {
2022-06-22 09:34:01 -05:00
match ty.as_adt() {
Some(hir::Adt::Enum(x)) => {
if let &[variant] = &*x.variants(db) {
if variant.kind(db) == hir::StructKind::Unit {
2023-08-08 12:51:59 -05:00
let path = make::path_qualified(
2022-06-22 09:34:01 -05:00
path,
2023-08-08 12:51:59 -05:00
make::path_segment(make::name_ref(&variant.name(db).to_smol_str())),
2022-06-22 09:34:01 -05:00
);
2023-08-08 12:51:59 -05:00
return Some(make::expr_path(path));
2022-06-22 09:34:01 -05:00
}
}
}
Some(hir::Adt::Struct(x)) if x.kind(db) == StructKind::Unit => {
2023-08-08 12:51:59 -05:00
return Some(make::expr_path(path));
2022-06-22 09:34:01 -05:00
}
_ => {}
}
None
}