1 use ide_db::{helpers::FamousDefs, RootDatabase};
2 use syntax::ast::{self, AstNode, NameOwner};
4 use crate::{AssistContext, AssistId, AssistKind, Assists};
6 // Assist: generate_default_from_enum_variant
8 // Adds a Default impl for an enum using a variant.
25 // impl Default for Version {
26 // fn default() -> Self {
31 pub(crate) fn generate_default_from_enum_variant(
35 let variant = ctx.find_node_at_offset::<ast::Variant>()?;
36 let variant_name = variant.name()?;
37 let enum_name = variant.parent_enum().name()?;
38 if !matches!(variant.kind(), ast::StructKind::Unit) {
39 cov_mark::hit!(test_gen_default_on_non_unit_variant_not_implemented);
43 if existing_default_impl(&ctx.sema, &variant).is_some() {
44 cov_mark::hit!(test_gen_default_impl_already_exists);
48 let target = variant.syntax().text_range();
50 AssistId("generate_default_from_enum_variant", AssistKind::Generate),
51 "Generate `Default` impl from this enum variant",
54 let start_offset = variant.parent_enum().syntax().text_range().end();
58 impl Default for {0} {{
59 fn default() -> Self {{
63 enum_name, variant_name
65 edit.insert(start_offset, buf);
70 fn existing_default_impl(
71 sema: &'_ hir::Semantics<'_, RootDatabase>,
72 variant: &ast::Variant,
74 let variant = sema.to_def(variant)?;
75 let enum_ = variant.parent_enum(sema.db);
76 let krate = enum_.module(sema.db).krate();
78 let default_trait = FamousDefs(sema, Some(krate)).core_default_Default()?;
79 let enum_type = enum_.ty(sema.db);
81 if enum_type.impls_trait(sema.db, default_trait, &[]) {
90 use crate::tests::{check_assist, check_assist_not_applicable};
95 fn test_generate_default_from_variant() {
97 generate_default_from_enum_variant,
113 impl Default for Variant {
114 fn default() -> Self {
123 fn test_generate_default_already_implemented() {
124 cov_mark::check!(test_gen_default_impl_already_exists);
125 check_assist_not_applicable(
126 generate_default_from_enum_variant,
128 //- minicore: default
135 impl Default for Variant {
136 fn default() -> Self {
145 fn test_add_from_impl_no_element() {
146 cov_mark::check!(test_gen_default_on_non_unit_variant_not_implemented);
147 check_assist_not_applicable(
148 generate_default_from_enum_variant,
150 //- minicore: default
161 fn test_generate_default_from_variant_with_one_variant() {
163 generate_default_from_enum_variant,
165 //- minicore: default
166 enum Variant { Undefi$0ned }
169 enum Variant { Undefined }
171 impl Default for Variant {
172 fn default() -> Self {