use ingraph_codegen::{
interface::{InterfaceModel, Tier},
model::DatabaseKind,
};
use quote::ToTokens;
pub(super) fn parse(
input: &syn::DeriveInput,
) -> syn::Result<ingraph_codegen::interface::InterfaceModel> {
let (host, arguments) = crate::host::split(input);
super::parse(&host, &arguments)
}
fn fields(model: &InterfaceModel) -> Vec<(String, String, Tier)> {
model
.fields
.iter()
.map(|field| (field.name.to_string(), tight(&field.ty), field.tier))
.collect()
}
fn ident(name: &str) -> syn::Ident {
syn::Ident::new(name, proc_macro2::Span::call_site())
}
fn tight(tokens: impl ToTokens) -> String {
tokens.to_token_stream().to_string().replace(' ', "")
}
pub(super) fn refusal(input: &syn::DeriveInput) -> String {
parse(input)
.expect_err("the declaration is refused")
.into_iter()
.map(|error| error.to_string())
.collect::<Vec<_>>()
.join(" | ")
}
#[test]
fn the_short_form_takes_every_default() {
let model = parse(&syn::parse_quote! {
#[ingraph(fields(title: String, duration: Duration))]
pub enum Media {
Video(Video),
Audio(Audio),
}
})
.expect("a name and a type is a whole field");
assert_eq!(
fields(&model),
[
("title".to_owned(), "String".to_owned(), Tier::Stored),
("duration".to_owned(), "Duration".to_owned(), Tier::Stored),
]
);
assert!(model.fields.iter().all(|field| !field.copy));
assert!(model.fields.iter().all(|field| field.pins.is_empty()));
assert_eq!(model.databases(), []);
assert_eq!(model.krate, syn::parse_quote!(::ingraph));
}
#[test]
fn the_long_form_carries_the_pins_the_projection_and_the_tier() {
let model = parse(&syn::parse_quote! {
#[ingraph(fields(
title: String,
mask(type = "Mask", copy, persist(sqlite(type = "u32"), postgres)),
display_label(type = "String", graphql(computed)),
checksum(type = "u64", graphql(try_computed)),
))]
pub enum Media {
Video(Video),
}
})
.expect("the long form is the same field with more said about it");
assert_eq!(
fields(&model),
[
("title".to_owned(), "String".to_owned(), Tier::Stored),
("mask".to_owned(), "Mask".to_owned(), Tier::Stored),
(
"display_label".to_owned(),
"String".to_owned(),
Tier::Computed
),
("checksum".to_owned(), "u64".to_owned(), Tier::TryComputed),
]
);
let mask = &model.fields[1];
assert!(mask.copy);
assert_eq!(tight(mask.pinned(DatabaseKind::Sqlite)), "u32");
assert_eq!(
tight(mask.pinned(DatabaseKind::Postgres)),
"Mask",
"a database named with no `type` keeps the domain type — and is still named"
);
assert_eq!(
model.databases(),
[DatabaseKind::Sqlite, DatabaseKind::Postgres]
);
}
#[test]
fn the_block_selects_the_databases_a_short_form_field_is_checked_at() {
let model = parse(&syn::parse_quote! {
#[ingraph(persist(sqlite, mongo), fields(title: String))]
pub enum Media {
Video(Video),
}
})
.expect("a selection is not a storage declaration");
assert_eq!(
model
.persist
.iter()
.map(|database| database.kind)
.collect::<Vec<_>>(),
[DatabaseKind::Sqlite, DatabaseKind::Mongo]
);
assert_eq!(
model.databases(),
[DatabaseKind::Sqlite, DatabaseKind::Mongo]
);
}
#[test]
fn a_database_block_names_the_namespace_its_words_are_minted_in() {
let model = parse(&syn::parse_quote! {
#[ingraph(persist(sqlite(alias(prefix = "__mine")), postgres), fields(title: String))]
pub enum Media {
Video(Video),
}
})
.expect("the same entry the record's database block takes");
assert_eq!(model.kind_word(DatabaseKind::Sqlite), "__mine_kind__");
assert_eq!(model.source_word(DatabaseKind::Sqlite), "__mine_union__");
assert!(!model.mints_the_default_words(DatabaseKind::Sqlite));
assert_eq!(model.kind_word(DatabaseKind::Postgres), "__ig_kind__");
assert_eq!(model.source_word(DatabaseKind::Postgres), "__ig_union__");
assert!(
model.mints_the_default_words(DatabaseKind::Postgres),
"the database beside it named nothing, and states nothing",
);
}
#[test]
fn the_engines_own_words_are_the_ones_the_default_mints() {
let model = parse(&syn::parse_quote! {
#[ingraph(persist(sqlite, postgres), fields(title: String))]
pub enum Media {
Video(Video),
}
})
.expect("a declaration that moves nothing");
for kind in [DatabaseKind::Sqlite, DatabaseKind::Postgres] {
assert!(
model.mints_the_default_words(kind),
"{kind:?} named no prefix, so the emission is silent and the engine answers",
);
assert_eq!(
model.kind_word(kind),
ingraph::interface::KIND.as_str(),
"the arm writes the engine's word and the decode reads the mint's; they must be one string",
);
assert_eq!(
model.source_word(kind),
ingraph::interface::SOURCE.as_str(),
"the derived table is named by the engine and qualified by the mint",
);
}
}
#[test]
fn an_interface_has_no_alias_table_for_a_depth_to_size() {
let refused = refusal(&syn::parse_quote! {
#[ingraph(persist(sqlite(alias(depth = 16))), fields(title: String))]
pub enum Media {
Video(Video),
}
});
assert!(
refused.contains("owns no table to mint one for"),
"{refused}"
);
}
#[test]
fn an_interfaces_alias_block_is_held_to_the_same_rules() {
for (declaration, expected) in [
(
syn::parse_quote! {
#[ingraph(persist(sqlite(alias(prefix = "mine"))), fields(title: String))]
pub enum Media {
Video(Video),
}
},
"does not begin `__`",
),
(
syn::parse_quote! {
#[ingraph(persist(sqlite(alias())), fields(title: String))]
pub enum Media {
Video(Video),
}
},
"names neither knob",
),
] {
let refused = refusal(&declaration);
assert!(refused.contains(expected), "{refused}");
}
}
#[test]
fn the_empty_block_names_only_the_knob_an_interface_has() {
let refused = refusal(&syn::parse_quote! {
#[ingraph(persist(sqlite(alias())), fields(title: String))]
pub enum Media {
Video(Video),
}
});
assert!(refused.contains("it takes `prefix = \"…\"`,"), "{refused}");
assert!(!refused.contains("`depth = N`"), "{refused}");
}
#[test]
fn the_computed_cell_names_no_database() {
let model = parse(&syn::parse_quote! {
#[ingraph(
graphql(computed(error = "media::ComputeError")),
fields(label(type = "String", graphql(try_computed))),
)]
pub enum Media {
Video(Video),
}
})
.expect("a computed value is derived from the member, so the crossing has no database");
assert_eq!(tight(model.computed_error()), "media::ComputeError");
}
#[test]
fn the_enum_level_block_carries_the_root_and_the_refusals_name() {
let model = parse(&syn::parse_quote! {
#[ingraph(crate = "shim::ingraph", unwrap_error(rename = "NoSuchMedia"), fields(title: String))]
pub enum Media {
Video(Video),
}
})
.expect("a re-export shim is where the framework may live");
assert_eq!(tight(&model.krate), "shim::ingraph");
assert_eq!(model.error(), "NoSuchMedia");
assert_eq!(
model
.emitted_types()
.iter()
.map(|declared| declared.name.to_string())
.collect::<Vec<_>>(),
[
"NoSuchMedia",
"MediaFields",
"MediaDerivations",
"MediaGraphqlOutput"
]
);
}
#[test]
fn a_field_may_be_spelled_with_a_keyword() {
let model = parse(&syn::parse_quote! {
#[ingraph(fields(r#type: Kind, r#match(type = "bool")))]
pub enum Media {
Video(Video),
}
})
.expect("`parse_any` is what reads a keyword as a name");
assert_eq!(
fields(&model)
.into_iter()
.map(|(name, _, _)| name)
.collect::<Vec<_>>(),
["r#type", "r#match"]
);
}
#[test]
fn refuses_an_interface_that_promises_nothing() {
for declaration in [
syn::parse_quote! {
pub enum Media { Video(Video) }
},
syn::parse_quote! {
#[ingraph(fields())]
pub enum Media { Video(Video) }
},
] {
let refused: syn::DeriveInput = declaration;
let message = refusal(&refused);
assert!(message.contains("is a UNION"), "{message}");
assert!(message.contains("`#[derive(ingraph::Union)]`"), "{message}");
}
}
#[test]
fn refuses_a_field_that_names_no_type() {
let message = refusal(&syn::parse_quote! {
#[ingraph(fields(title(copy)))]
pub enum Media { Video(Video) }
});
assert!(message.contains("a field names its type"), "{message}");
}
#[test]
fn refuses_a_bare_type_by_naming_the_spelling() {
let message = refusal(&syn::parse_quote! {
#[ingraph(fields(title(type = String)))]
pub enum Media { Video(Video) }
});
assert!(
message.contains("`type = \"<Type>\"` in the long one, in a string literal"),
"{message}"
);
assert!(
!message.contains(" | "),
"one mistake, one refusal: {message}"
);
}
#[test]
fn the_string_form_carries_a_generic_type() {
let model = parse(&syn::parse_quote! {
#[ingraph(fields(marks(type = "Vec<i64>", list(scalar))))]
pub enum Media { Video(Video) }
})
.expect("a type in a string literal is the type it spells");
assert_eq!(tight(&model.fields[0].ty), "Vec<i64>");
}
#[test]
fn refuses_an_entry_a_field_does_not_take() {
let message = refusal(&syn::parse_quote! {
#[ingraph(fields(title(type = "String", indexed)))]
pub enum Media { Video(Video) }
});
assert!(message.contains("unknown entry on a field"), "{message}");
}
#[test]
fn refuses_a_field_declared_twice() {
let message = refusal(&syn::parse_quote! {
#[ingraph(fields(title: String, title(type = "u64")))]
pub enum Media { Video(Video) }
});
assert!(message.contains("is declared more than once"), "{message}");
assert!(message.contains("one field, one promise"), "{message}");
}
#[test]
fn refuses_a_database_written_where_a_domain_belongs() {
for declaration in [
syn::parse_quote! {
#[ingraph(sqlite(type = "u32"), fields(title: String))]
pub enum Media { Video(Video) }
},
syn::parse_quote! {
#[ingraph(fields(title(type = "String", sqlite(type = "u32"))))]
pub enum Media { Video(Video) }
},
syn::parse_quote! {
#[ingraph(fields(title(type = "String", graphql(sqlite(type = "u32")))))]
pub enum Media { Video(Video) }
},
] {
let refused: syn::DeriveInput = declaration;
let message = refusal(&refused);
assert!(
message.contains("`sqlite` is a DATABASE and this is not a database's scope"),
"{message}"
);
}
}
#[test]
fn refuses_a_field_that_is_computed_and_pinned() {
let computed_first = refusal(&syn::parse_quote! {
#[ingraph(fields(label(type = "String", graphql(computed), persist(sqlite(type = "text")))))]
pub enum Media { Video(Video) }
});
assert!(
computed_first.contains("is COMPUTED and pinned"),
"{computed_first}"
);
let pinned_first = refusal(&syn::parse_quote! {
#[ingraph(fields(label(type = "String", persist(sqlite(type = "text")), graphql(computed))))]
pub enum Media { Video(Video) }
});
assert!(
pinned_first.contains("is PINNED and computed"),
"{pinned_first}"
);
}
#[test]
fn refuses_a_field_that_claims_both_computed_words() {
let message = refusal(&syn::parse_quote! {
#[ingraph(fields(label(type = "String", graphql(computed, try_computed))))]
pub enum Media { Video(Video) }
});
assert!(message.contains("a field is COMPUTED once"), "{message}");
}
#[test]
fn refuses_the_cell_whose_consumer_has_not_landed_by_naming_it() {
let field = refusal(&syn::parse_quote! {
#[ingraph(fields(mask(type = "Mask",
graphql(output(sqlite(from = "hex_of_mask"))))))]
pub enum Media { Video(Video) }
});
assert!(
field.contains("`output(<db>(from = \"…\"))` is a field's own row-to-wire crossing"),
"{field}"
);
assert!(
field.contains("arrives with the interface's own output face"),
"{field}"
);
let declaration = refusal(&syn::parse_quote! {
#[ingraph(graphql(output(sqlite(try_from(error = "media::Error")))), fields(title: String))]
pub enum Media { Video(Video) }
});
assert!(
declaration.contains("arrives with the interface's own output face"),
"{declaration}"
);
}
#[test]
fn the_operand_cells_are_read_at_the_level_each_belongs_to() {
let model = parse(&syn::parse_quote! {
#[ingraph(
persist(sqlite, postgres),
graphql(input(comparison(sqlite(try_into(error = "media::TooWide"))))),
fields(mask(type = "Mask",
persist(sqlite(type = "u32")),
graphql(input(comparison(sqlite(try_into = "narrow")))))),
)]
pub enum Media { Video(Video) }
})
.expect("both operand cells have consumers");
let mask = &model.fields[0];
assert_eq!(
mask.operand(DatabaseKind::Sqlite).map(tight).as_deref(),
Some("narrow")
);
assert_eq!(
mask.operand(DatabaseKind::Postgres).map(tight),
None,
"a database with no converter crosses through the stored type's own `TryFrom`"
);
assert_eq!(
tight(model.operand_error(DatabaseKind::Sqlite)),
"media::TooWide"
);
assert!(
tight(model.operand_error(DatabaseKind::Postgres)).contains("dyn"),
"and a database with no cell takes the boxed refusal"
);
}
#[test]
fn the_operand_position_takes_one_leg_and_one_position() {
for leg in ["from", "try_from", "into"] {
let word = ident(leg);
let message = refusal(&syn::parse_quote! {
#[ingraph(
graphql(input(comparison(sqlite(#word(error = "media::Error"))))),
fields(title: String)
)]
pub enum Media { Video(Video) }
});
assert!(
message.contains("is not the leg an operand takes"),
"{message}"
);
}
for (position, why) in [
("orderby", "carries a DIRECTION and a subject"),
("pagination", "opaque engine round trip"),
] {
let word = ident(position);
let message = refusal(&syn::parse_quote! {
#[ingraph(graphql(input(#word(sqlite(try_into(error = "E"))))), fields(title: String))]
pub enum Media { Video(Video) }
});
assert!(message.contains(why), "{message}");
}
}
#[test]
fn refuses_an_operand_crossing_on_a_computed_field() {
let message = refusal(&syn::parse_quote! {
#[ingraph(fields(label(type = "String",
graphql(computed, input(comparison(sqlite(try_into = "narrow")))))))]
pub enum Media { Video(Video) }
});
assert!(
message.contains("is COMPUTED and names an operand crossing"),
"{message}"
);
}
#[test]
fn refuses_a_second_operand_converter_for_one_database() {
let message = refusal(&syn::parse_quote! {
#[ingraph(fields(mask(type = "Mask", graphql(input(comparison(
sqlite(try_into = "a"), sqlite(try_into = "b")
))))))]
pub enum Media { Video(Video) }
});
assert!(
message.contains("is declared more than once for this field's operand"),
"{message}"
);
}
#[test]
fn the_hydration_cell_is_read_and_the_other_three_legs_are_not() {
let model = parse(&syn::parse_quote! {
#[ingraph(persist(sqlite(try_into(error = "media::Error"))), fields(title: String))]
pub enum Media { Video(Video) }
})
.expect("`try_into` types the crossing the hydration performs");
assert_eq!(model.errors.len(), 1);
assert_eq!(model.errors[0].kind, DatabaseKind::Sqlite);
assert_eq!(
tight(model.hydration_error(DatabaseKind::Sqlite)),
"media::Error"
);
assert!(
tight(model.hydration_error(DatabaseKind::Postgres)).contains("dyn"),
"a database with no cell takes the boxed refusal"
);
for leg in ["from", "try_from", "into"] {
let word = syn::Ident::new(leg, proc_macro2::Span::call_site());
let message = refusal(&syn::parse_quote! {
#[ingraph(persist(sqlite(#word(error = "media::Error"))), fields(title: String))]
pub enum Media { Video(Video) }
});
assert!(
message.contains(&format!(
"`{leg}(error = \"…\")` is an interface's per-leg refusal cell"
)),
"{message}"
);
assert!(message.contains("arrives with the find half"), "{message}");
}
}
#[test]
fn refuses_a_second_hydration_cell_for_one_database() {
let message = refusal(&syn::parse_quote! {
#[ingraph(
persist(sqlite(try_into(error = "a::Error"), try_into(error = "b::Error"))),
fields(title: String)
)]
pub enum Media { Video(Video) }
});
assert!(
message.contains("`try_into(…)` is declared more than once"),
"{message}"
);
}
#[test]
fn refuses_a_refusal_named_after_something_the_expansion_declares() {
for name in ["Media", "MediaFields", "MediaDerivations"] {
let rename = syn::LitStr::new(name, proc_macro2::Span::call_site());
let message = refusal(&syn::parse_quote! {
#[ingraph(unwrap_error(rename = #rename), fields(title: String))]
pub enum Media { Video(Video) }
});
assert!(message.contains("and it is already"), "{name}: {message}");
}
}
#[test]
fn the_shape_refusals_state_the_interfaces_own_law() {
let empty = refusal(&syn::parse_quote! {
#[ingraph(fields(title: String))]
pub enum Media {}
});
assert!(
empty.contains("an enum with no variants declares no interface"),
"{empty}"
);
assert!(empty.contains("a promise ABOUT its members"), "{empty}");
let duplicated = refusal(&syn::parse_quote! {
#[ingraph(fields(title: String))]
pub enum Media { Video(Video), Second(Video) }
});
assert!(duplicated.contains("carry ONE member type"), "{duplicated}");
assert!(
duplicated.contains("no fan-out could say which variant it answered from"),
"{duplicated}"
);
let generic = refusal(&syn::parse_quote! {
#[ingraph(fields(title: String))]
pub enum Media<T> { Video(T) }
});
assert!(
generic.contains("generic interfaces are not supported"),
"{generic}"
);
}
#[test]
fn one_pass_reports_the_grammar_and_the_shape_together() {
let message = refusal(&syn::parse_quote! {
#[ingraph(nonsense, fields(title(copy)))]
pub enum Media { Video { id: u64 } }
});
assert!(
message.contains("unknown entry in `#[ingraph(…)]`"),
"{message}"
);
assert!(message.contains("a field names its type"), "{message}");
assert!(
message.contains("takes the member POSITIONALLY"),
"{message}"
);
}
#[test]
fn a_member_block_names_what_one_member_calls_the_field() {
let model = parse(&syn::parse_quote! {
#[ingraph(fields(
created_at(type = "Timestamp", members(Audio(field = "imported_at"))),
title: String,
))]
pub enum Media {
Video(Video),
Audio(Audio),
}
})
.expect("a member set and its contract arrive in one derive input");
let created_at = &model.fields[0];
assert_eq!(*created_at.column(&ident("Audio")), "imported_at");
assert_eq!(
*created_at.column(&ident("Video")),
"created_at",
"a member with no block carries the interface's own name"
);
assert_eq!(*model.fields[1].column(&ident("Audio")), "title");
}
#[test]
fn a_raw_variant_is_a_member_block_key_too() {
let model = parse(&syn::parse_quote! {
#[ingraph(fields(kind(type = "u8", members(r#Type(field = "code")))))]
pub enum Media {
r#Type(Marker),
}
})
.expect("the escape is not part of the name");
assert_eq!(*model.fields[0].column(&ident("Type")), "code");
}
#[test]
fn refuses_a_member_block_that_names_no_variant() {
let message = refusal(&syn::parse_quote! {
#[ingraph(fields(title(type = "String", members(Sound(field = "name")))))]
pub enum Media { Video(Video), Audio(Audio) }
});
assert!(
message.contains("`Sound` is not a member variant of this interface"),
"{message}"
);
assert!(message.contains("`Video` and `Audio`"), "{message}");
}
#[test]
fn refuses_a_member_declared_twice_on_one_field() {
let message = refusal(&syn::parse_quote! {
#[ingraph(fields(title(type = "String", members(Video(field = "a"), Video(field = "b")))))]
pub enum Media { Video(Video) }
});
assert!(
message.contains("is declared more than once on `title`"),
"{message}"
);
}
#[test]
fn refuses_a_member_block_on_a_computed_field() {
let message = refusal(&syn::parse_quote! {
#[ingraph(fields(label(type = "String", graphql(computed), members(Video(field = "name")))))]
pub enum Media { Video(Video) }
});
assert!(
message.contains("is COMPUTED and names a member's column"),
"{message}"
);
}
#[test]
fn refuses_a_member_block_that_names_no_column_or_names_it_wrongly() {
let empty = refusal(&syn::parse_quote! {
#[ingraph(fields(title(type = "String", members(Video))))]
pub enum Media { Video(Video) }
});
assert!(
empty.contains("a member block is `<Variant>(field = \"…\")`"),
"{empty}"
);
let unknown = refusal(&syn::parse_quote! {
#[ingraph(fields(title(type = "String", members(Video(field = "name", type = "u8")))))]
pub enum Media { Video(Video) }
});
assert!(
unknown.contains("unknown entry in a member block"),
"{unknown}"
);
let mangled = refusal(&syn::parse_quote! {
#[ingraph(fields(title(type = "String", members(Video(field = "not an ident")))))]
pub enum Media { Video(Video) }
});
assert!(
mangled.contains("as an identifier in a string literal"),
"{mangled}"
);
}
#[test]
fn refuses_the_old_spelling_of_the_refusals_knob() {
let moved = refusal(&syn::parse_quote! {
#[ingraph(error(rename = "NoSuchMedia"), fields(title: String))]
pub enum Media { Video(Video) }
});
assert!(
moved.contains("`error` names CONVERSION CELLS now"),
"{moved}"
);
assert!(moved.contains("`unwrap_error(rename = \"…\")`"), "{moved}");
}
#[test]
fn position_decides_what_a_key_is_and_case_decides_nothing() {
let model = parse(&syn::parse_quote! {
#[ingraph(fields(
title(type = "String", members(quiet(field = "name"))),
kind(type = "u8", members(r#type(field = "tag"))),
))]
pub enum Media {
quiet(Audio),
r#type(Marker),
}
})
.expect("a variant is whatever the enum spells, and the container is where it is a key");
assert_eq!(*model.fields[0].column(&ident("quiet")), "name");
assert_eq!(*model.fields[1].column(&ident("type")), "tag");
assert_eq!(
tight(&model.fields[1].ty),
"u8",
"and `type = …` outside the container is still the field's own type"
);
}
#[test]
fn refuses_a_member_block_outside_the_container_by_naming_where_it_goes() {
let message = refusal(&syn::parse_quote! {
#[ingraph(fields(title(type = "String", Audio(field = "name"))))]
pub enum Media { Video(Video), Audio(Audio) }
});
assert!(
message.contains("`Audio` is a MEMBER and this is the field's own scope"),
"{message}"
);
assert!(
message.contains("write `members(Audio(field = \"…\"))`"),
"{message}"
);
}
#[test]
fn refuses_a_second_members_block_and_one_naming_nobody() {
let twice = refusal(&syn::parse_quote! {
#[ingraph(fields(title(type = "String", members(Video(field = "a")), members(Audio(field = "b")))))]
pub enum Media { Video(Video), Audio(Audio) }
});
assert!(
twice.contains("`members(…)` is declared more than once on a field"),
"{twice}"
);
for empty in [
syn::parse_quote! {
#[ingraph(fields(title(type = "String", members())))]
pub enum Media { Video(Video) }
},
syn::parse_quote! {
#[ingraph(fields(title(type = "String", members)))]
pub enum Media { Video(Video) }
},
] {
let refused: syn::DeriveInput = empty;
let message = refusal(&refused);
assert!(
message.contains("`members(…)` names no member"),
"{message}"
);
}
}