diff --git a/CHANGELOG.md b/CHANGELOG.md index 85cf789..1276cb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +# unreleased () + +### Added + - Documentation comments for enum variants + - Marking an enum `non_exhaustive` + # 0.1.3 (May 9, 2020) ### Added diff --git a/src/enum.rs b/src/enum.rs index 6e08906..cd7dae0 100644 --- a/src/enum.rs +++ b/src/enum.rs @@ -86,6 +86,12 @@ impl Enum { self } + /// Mark this enum with `#[non_exhaustive]`. + pub fn non_exhaustive(&mut self) -> &mut Self { + self.type_def.r#macro("#[non_exhaustive]"); + self + } + /// Formats the enum using the given formatter. pub fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { self.type_def.fmt_head("enum", &[], fmt)?; diff --git a/src/variant.rs b/src/variant.rs index b522a55..8f4c133 100644 --- a/src/variant.rs +++ b/src/variant.rs @@ -4,6 +4,7 @@ use fields::Fields; use formatter::Formatter; use r#type::Type; +use docs::Docs; /// Defines an enum variant. @@ -11,6 +12,9 @@ use r#type::Type; pub struct Variant { name: String, fields: Fields, + + /// Variant documentation + docs: Option, } @@ -20,6 +24,7 @@ impl Variant { Variant { name: name.to_string(), fields: Fields::Empty, + docs: None, } } @@ -38,8 +43,17 @@ impl Variant { self } + /// Set the variant documentation. + pub fn doc(&mut self, docs: &str) -> &mut Self { + self.docs = Some(Docs::new(docs)); + self + } + /// Formats the variant using the given formatter. pub fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { + if let Some(ref docs) = self.docs { + docs.fmt(fmt)?; + } write!(fmt, "{}", self.name)?; self.fields.fmt(fmt)?; write!(fmt, ",\n")?; diff --git a/tests/codegen.rs b/tests/codegen.rs index c8c0306..843722e 100644 --- a/tests/codegen.rs +++ b/tests/codegen.rs @@ -405,6 +405,47 @@ enum IpAddrKind { assert_eq!(scope.to_string(), &expect[1..]); } +#[test] +fn enum_with_non_exhaustive() { + let mut scope = Scope::new(); + + scope.new_enum("IpAddrKind") + .non_exhaustive() + .push_variant(Variant::new("V4")) + .push_variant(Variant::new("V6")) + ; + + let expect = r#" +#[non_exhaustive] +enum IpAddrKind { + V4, + V6, +}"#; + + assert_eq!(scope.to_string(), &expect[1..]); +} + +#[test] +fn enum_with_variant_doc() { + let mut scope = Scope::new(); + + let mut v = Variant::new("V4"); + v.doc("best"); + scope.new_enum("IpAddrKind") + .push_variant(v) + .push_variant(Variant::new("V6")) + ; + + let expect = r#" +enum IpAddrKind { + /// best + V4, + V6, +}"#; + + assert_eq!(scope.to_string(), &expect[1..]); +} + #[test] fn scoped_imports() { let mut scope = Scope::new();