Skip to content

Commit

Permalink
Don't check variant exhaustiveness if a fallback variant is provided.
Browse files Browse the repository at this point in the history
  • Loading branch information
jakubadamw committed Nov 27, 2023
1 parent 6ec3fa1 commit a064b9e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
6 changes: 4 additions & 2 deletions cynic-codegen/src/enum_derive/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,11 @@ fn join_variants<'a>(
rename_all: RenameAll,
enum_span: &Span,
) -> Result<Vec<(&'a EnumDeriveVariant, &'a EnumValue<'a>)>, TokenStream> {
let mut has_fallback = false;
let mut map = BTreeMap::new();
for variant in variants {
if *variant.fallback {
has_fallback = true;
// We can't join up a fallback as it has no corresponding GQL value.
// We handle them separately.
continue;
Expand Down Expand Up @@ -237,7 +239,7 @@ fn join_variants<'a>(
_ => (),
}
}
if !missing_variants.is_empty() {
if !has_fallback && !missing_variants.is_empty() {
let missing_variants_string = missing_variants.join(", ");
errors.extend(
syn::Error::new(
Expand All @@ -253,7 +255,7 @@ fn join_variants<'a>(

Ok(map
.into_iter()
.map(|(_, (a, b))| (a.unwrap(), b.unwrap()))
.filter_map(|(_, (a, b))| Some((a?, b.unwrap())))
.collect())
}

Expand Down
21 changes: 21 additions & 0 deletions cynic/tests/enum-fallbacks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ enum PostStateStringFallback {
Unknown(String),
}

#[derive(Enum, Debug, PartialEq)]
#[cynic(graphql_type = "PostState", schema_path = "tests/test-schema.graphql")]
enum PostStateNonexhaustiveFallback {
Posted,
#[cynic(fallback)]
Unknown(String),
}

#[allow(non_snake_case, non_camel_case_types)]
mod schema {
cynic::use_schema!("tests/test-schema.graphql");
Expand All @@ -46,3 +54,16 @@ fn test_string_fallback() {

assert_eq!(val, serde_json::Value::String("BLAH".into()));
}

#[test]
fn test_nonexhaustive_fallback() {
assert_eq!(
PostStateNonexhaustiveFallback::deserialize(json!("DRAFT")).unwrap(),
PostStateNonexhaustiveFallback::Unknown("DRAFT".to_string())
);

let val =
serde_json::to_value(PostStateNonexhaustiveFallback::Unknown("DRAFT".to_string())).unwrap();

assert_eq!(val, serde_json::Value::String("DRAFT".into()));
}

0 comments on commit a064b9e

Please sign in to comment.