use heck::ToLowerCamelCase as _;
use quote::ToTokens as _;
use super::{BitWidth, FlagBit, FlagsModel};
fn disposition() -> FlagsModel {
FlagsModel {
krate: syn::parse_quote!(::ingraph),
vis: syn::parse_quote!(pub),
name: ident("Disposition"),
width: BitWidth::U32,
bits: vec![
FlagBit {
attrs: vec![syn::parse_quote!(#[doc = "The default track for its kind."])],
..bit("Default", 0x1)
},
bit("Forced", 0x2),
bit("HearingImpaired", 0x4),
],
attrs: vec![
syn::parse_quote!(#[doc = "Which roles a track takes."]),
syn::parse_quote!(#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]),
],
remote: None,
wire_name: None,
}
}
fn narrow() -> FlagsModel {
FlagsModel {
width: BitWidth::U8,
..disposition()
}
}
fn vendored() -> FlagsModel {
FlagsModel {
krate: syn::parse_quote!(vendored::ingraph),
..disposition()
}
}
fn bit(name: &str, value: u128) -> FlagBit {
FlagBit {
ident: ident(name),
rename: None,
upstream: None,
value,
attrs: Vec::new(),
}
}
fn ident(name: &str) -> syn::Ident {
syn::Ident::new(name, proc_macro2::Span::call_site())
}
fn emission(model: &FlagsModel) -> syn::File {
syn::parse2(model.emit()).expect("the expansion parses")
}
fn rendered(model: &FlagsModel) -> String {
prettyplease::unparse(&emission(model))
}
fn minted(file: &syn::File) -> &syn::ItemMacro {
let mut invocations = file.items.iter().filter_map(|item| match item {
syn::Item::Macro(item) => Some(item),
_ => None,
});
let minted = invocations.next().expect("the expansion mints a type");
assert!(invocations.next().is_none(), "one invocation and no other");
minted
}
fn declaration(model: &FlagsModel) -> String {
let file = emission(model);
minted(&file).mac.tokens.to_string().replace(' ', "")
}
fn is_gate(path: &syn::Path) -> bool {
path
.segments
.iter()
.skip_while(|segment| segment.ident != "__private")
.nth(1)
.is_some_and(|segment| segment.ident == "gate")
}
fn blocks(file: &syn::File) -> Vec<Vec<syn::Stmt>> {
file
.items
.iter()
.filter_map(|item| match item {
syn::Item::Const(anonymous) if anonymous.ident == "_" => Some(&anonymous.expr),
_ => None,
})
.map(|block| {
let syn::Expr::Block(block) = block.as_ref() else {
panic!("the const's value is a block");
};
block.block.stmts.clone()
})
.collect()
}
fn body(file: &syn::File) -> Vec<syn::Stmt> {
blocks(file).swap_remove(0)
}
fn wire(file: &syn::File) -> Vec<syn::Stmt> {
let mut blocks = blocks(file);
assert_eq!(blocks.len(), 2, "the expansion is two anonymous consts");
blocks.swap_remove(1)
}
fn ungated(model: &FlagsModel) -> String {
let held = body(&emission(model));
quote::quote!(#(#held)*).to_string().replace(' ', "")
}
fn ungated_traits(model: &FlagsModel) -> Vec<String> {
body(&emission(model))
.iter()
.filter_map(|stmt| match stmt {
syn::Stmt::Item(syn::Item::Impl(item)) => item.trait_.as_ref(),
_ => None,
})
.map(|(path, _)| tight(path))
.collect()
}
fn gated(model: &FlagsModel) -> Vec<(String, Vec<String>)> {
body(&emission(model))
.iter()
.filter_map(|stmt| match stmt {
syn::Stmt::Macro(gate) if is_gate(&gate.mac.path) => Some(&gate.mac),
_ => None,
})
.map(|gate| {
let held: syn::File = syn::parse2(gate.tokens.clone()).expect("a gate holds parsable items");
let traits = held
.items
.iter()
.filter_map(|item| match item {
syn::Item::Impl(item) => item.trait_.as_ref().map(|(path, _)| tight(path)),
_ => None,
})
.collect();
(tight(&gate.path), traits)
})
.collect()
}
fn inside(model: &FlagsModel, gate: &str) -> String {
body(&emission(model))
.iter()
.find_map(|stmt| match stmt {
syn::Stmt::Macro(item) if is_gate(&item.mac.path) && tight(&item.mac.path) == gate => {
Some(item.mac.tokens.to_string().replace(' ', ""))
}
_ => None,
})
.unwrap_or_else(|| panic!("no `{gate}` group"))
}
fn declared_structs(file: &syn::File) -> Vec<String> {
file
.items
.iter()
.filter_map(|item| match item {
syn::Item::Struct(item) => Some(item.ident.to_string()),
_ => None,
})
.collect()
}
fn constants(model: &FlagsModel) -> Vec<String> {
let file = emission(model);
flat_tokens(minted(&file).mac.tokens.clone())
.windows(2)
.filter_map(|pair| match pair {
[
proc_macro2::TokenTree::Ident(keyword),
proc_macro2::TokenTree::Ident(name),
] if keyword == "const" => Some(name.to_string()),
_ => None,
})
.collect()
}
fn fields(model: &FlagsModel) -> Vec<String> {
let list = body(&emission(model))
.iter()
.filter_map(|stmt| match stmt {
syn::Stmt::Item(syn::Item::Impl(item)) => Some(item.items.clone()),
_ => None,
})
.flatten()
.find_map(|item| match item {
syn::ImplItem::Const(item) if item.ident == "FIELDS" => Some(item.expr),
_ => None,
})
.expect("the wire face declares its field list");
let syn::Expr::Reference(list) = list else {
panic!("the field list is a slice");
};
let syn::Expr::Array(list) = *list.expr else {
panic!("the field list is an array behind that slice");
};
list
.elems
.iter()
.map(|field| match field {
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(word),
..
}) => word.value(),
other => panic!("a field is a string literal: {}", other.to_token_stream()),
})
.collect()
}
fn tight(path: &syn::Path) -> String {
path
.segments
.last()
.expect("a path has a last segment")
.ident
.to_string()
}
#[test]
fn the_expansion_mints_one_bitflags_type_and_declares_nothing_itself() {
let file = emission(&disposition());
assert_eq!(
minted(&file)
.mac
.path
.to_token_stream()
.to_string()
.replace(' ', ""),
"::ingraph::__private::bitflags::bitflags"
);
assert!(
declared_structs(&file).is_empty(),
"{:?}",
declared_structs(&file)
);
assert_eq!(
file.items.len(),
3,
"the invocation, the storage block and the gated wire block"
);
}
#[test]
fn the_declarations_own_attributes_ride_in_front_of_the_minted_type() {
let written = declaration(&disposition());
let doc = written.find("#[doc=").expect("the declaration's own doc");
let derive = written
.find("#[derive(")
.expect("the declaration's own derive");
let minted_type = written
.find("pubstructDisposition")
.expect("the minted type");
assert!(doc < derive, "as written: {written}");
assert!(derive < minted_type, "in front of the type: {written}");
let mut reversed = disposition();
reversed.attrs.reverse();
let reversed = declaration(&reversed);
assert!(
reversed.find("#[derive(") < reversed.find("#[doc="),
"the order is the declaration's and not a sort: {reversed}"
);
}
#[test]
fn the_door_forwards_attributes_and_invents_none() {
let mut model = disposition();
model.attrs.clear();
model.bits[0].attrs.clear();
let written = declaration(&model);
assert!(written.starts_with("pubstructDisposition"), "{written}");
assert!(!written.contains("#["), "nothing was added: {written}");
}
#[test]
fn a_bit_is_a_suffixed_hex_literal_at_the_declared_width() {
let written = declaration(&disposition());
assert!(
written.contains("Disposition:::core::primitive::u32{"),
"{written}"
);
assert!(written.contains("constDEFAULT=0x1u32;"), "{written}");
assert!(written.contains("constFORCED=0x2u32;"), "{written}");
assert!(
written.contains("constHEARING_IMPAIRED=0x4u32;"),
"{written}"
);
let narrowed = declaration(&narrow());
assert!(
narrowed.contains("Disposition:::core::primitive::u8{"),
"{narrowed}"
);
assert!(
narrowed.contains("constHEARING_IMPAIRED=0x4u8;"),
"{narrowed}"
);
}
#[test]
fn a_bits_own_attributes_reach_its_const() {
let written = declaration(&disposition());
let body = written
.split_once('{')
.expect("the minted type has a body")
.1;
assert!(
body.starts_with("#[doc="),
"the bit's own doc leads it: {written}"
);
assert!(body.contains("]constDEFAULT=0x1u32;"), "{written}");
assert!(
body.ends_with("constFORCED=0x2u32;constHEARING_IMPAIRED=0x4u32;}"),
"a bit that wrote nothing carries nothing: {written}"
);
}
#[test]
fn the_const_names_are_the_identifiers_shouted() {
assert_eq!(
constants(&disposition()),
["DEFAULT", "FORCED", "HEARING_IMPAIRED"]
);
}
#[test]
fn a_rename_moves_the_const_the_word_and_the_field_together() {
let mut model = disposition();
model.bits[2].rename = Some("HARD_OF_HEARING".to_owned());
assert_eq!(model.bits[2].word(), "HARD_OF_HEARING");
assert_eq!(model.bits[2].field(), "hardOfHearing");
assert_eq!(constants(&model), ["DEFAULT", "FORCED", "HARD_OF_HEARING"]);
assert_eq!(fields(&model), ["default", "forced", "hardOfHearing"]);
let rendered = rendered(&model);
assert!(!rendered.contains("HEARING_IMPAIRED"), "{rendered}");
assert!(!rendered.contains("hearingImpaired"), "{rendered}");
}
#[test]
fn the_minted_type_takes_the_declarations_visibility() {
let mut model = disposition();
model.vis = syn::parse_quote!(pub(crate));
let written = declaration(&model);
assert!(written.contains("pub(crate)structDisposition"), "{written}");
}
#[test]
fn the_wire_face_carries_the_types_own_name_and_a_field_per_bit() {
let rendered = rendered(&disposition());
assert!(
rendered.contains(r#"const GRAPHQL_NAME: &'static ::core::primitive::str = "Disposition";"#),
"{rendered}"
);
assert_eq!(
fields(&disposition()),
["default", "forced", "hearingImpaired"]
);
}
#[test]
fn a_raw_name_is_published_without_its_escape() {
let mut model = disposition();
model.name = syn::Ident::new_raw("type", proc_macro2::Span::call_site());
assert_eq!(model.sdl_name(), "type");
let rendered = rendered(&model);
assert!(
rendered.contains(r#"const GRAPHQL_NAME: &'static ::core::primitive::str = "type";"#),
"{rendered}"
);
assert!(declaration(&model).contains("structr#type"), "{rendered}");
}
#[test]
fn the_field_list_is_parallel_to_the_bit_list() {
let mut model = disposition();
model.bits[1].rename = Some("FORCED_SUBTITLES".to_owned());
let constants = constants(&model);
let fields = fields(&model);
assert_eq!(constants.len(), model.bits.len(), "{constants:?}");
assert_eq!(fields.len(), constants.len(), "{fields:?}");
for (constant, field) in constants.iter().zip(&fields) {
assert_eq!(&constant.to_lower_camel_case(), field);
}
}
#[test]
fn the_reading_rows_are_the_ungated_ones() {
assert_eq!(
ungated_traits(&disposition()),
[
"FlagsValue",
"FlagsFilterMarker",
"DefaultMarker",
"DefaultVecMarker",
"CursorValue",
"ColumnKind",
"ColumnEq"
]
);
for stmt in body(&emission(&disposition())) {
let syn::Stmt::Item(syn::Item::Impl(item)) = stmt else {
continue;
};
let attrs: Vec<String> = item
.attrs
.iter()
.map(|attr| attr.to_token_stream().to_string().replace(' ', ""))
.collect();
assert_eq!(attrs, ["#[automatically_derived]"]);
}
}
#[test]
fn each_sql_dialect_gets_one_storage_group_and_mongodb_gets_none() {
let rows = || {
vec![
"StoredAs".to_owned(),
"Type".to_owned(),
"Encode".to_owned(),
"Decode".to_owned(),
"Carrier".to_owned(),
]
};
assert_eq!(
gated(&disposition()),
vec![
("if_sqlx".to_owned(), vec!["Assemble".to_owned()]),
("if_sqlite".to_owned(), rows()),
("if_postgres".to_owned(), rows()),
("if_mysql".to_owned(), rows()),
]
);
}
#[test]
fn a_u32_set_binds_as_i64_on_postgres_and_as_itself_elsewhere() {
let postgres = inside(&disposition(), "if_postgres");
assert!(
postgres.contains("letstored=<::core::primitive::i64as"),
"the column is READ at the dialect's own width: {postgres}"
);
assert!(
postgres.contains("qb.push_bind(Disposition::bits(self)as::core::primitive::i64);"),
"{postgres}"
);
assert!(
postgres.contains("<::core::primitive::u32as::core::convert::TryFrom<::core::primitive::i64>>"),
"the way back narrows to the declared width: {postgres}"
);
assert!(
!postgres.contains("as::core::primitive::u32"),
"nothing binds unsigned on Postgres: {postgres}"
);
for gate in ["if_sqlite", "if_mysql"] {
let held = inside(&disposition(), gate);
assert!(
held.contains("qb.push_bind(Disposition::bits(self)as::core::primitive::u32);"),
"{gate}: {held}"
);
assert!(!held.contains("i64"), "{gate}: {held}");
}
let widened = inside(&narrow(), "if_postgres");
assert!(
widened.contains("qb.push_bind(Disposition::bits(self)as::core::primitive::i16);"),
"the table's own widening and not a constant: {widened}"
);
assert!(!inside(&narrow(), "if_sqlite").contains("i16"));
}
#[test]
fn the_cursor_writes_the_bit_pattern_big_endian_at_the_declared_width() {
let wide = ungated(&disposition());
assert!(
wide.contains("::core::primitive::u32::to_be_bytes(Disposition::bits(self),)"),
"{wide}"
);
assert!(wide.contains("[::core::primitive::u8;4usize]"), "{wide}");
assert!(
wide.contains("Disposition::from_bits(::core::primitive::u32::from_be_bytes(fixed))"),
"{wide}"
);
let narrowed = ungated(&narrow());
assert!(
narrowed.contains("::core::primitive::u8::to_be_bytes(Disposition::bits(self),)"),
"{narrowed}"
);
assert!(
narrowed.contains("[::core::primitive::u8;1usize]"),
"{narrowed}"
);
}
#[test]
fn the_two_crossing_rows_are_one_gated_block() {
let emitted = emission(&disposition());
let wire = wire(&emitted);
assert_eq!(wire.len(), 1, "the wire block is one statement: the gate");
let syn::Stmt::Macro(gate) = &wire[0] else {
panic!("the wire block's statement is a gate invocation");
};
assert!(is_gate(&gate.mac.path), "{}", tight(&gate.mac.path));
assert_eq!(tight(&gate.mac.path), "if_async_graphql");
let held: syn::File = syn::parse2(gate.mac.tokens.clone()).expect("a gate holds parsable items");
assert_eq!(
held
.items
.iter()
.filter_map(|item| match item {
syn::Item::Impl(item) => item.trait_.as_ref().map(|(path, _)| tight(path)),
_ => None,
})
.collect::<Vec<_>>(),
["ToGraphqlOutput", "ToGraphqlInput"]
);
let seats = gate.mac.tokens.to_string().replace(' ', "");
assert!(
seats.contains("typeOutput<'__ingraph>=::ingraph::__private::graphql::FlagsView<Self>;"),
"{seats}"
);
assert!(
seats.contains("typeInput=::ingraph::__private::graphql::FlagsInput<Self>;"),
"{seats}"
);
let storage = ungated(&disposition());
for name in [
"ToGraphqlOutput",
"ToGraphqlInput",
"FlagsView",
"FlagsInput",
] {
assert!(
!storage.contains(name),
"{name} escaped the gate: {storage}"
);
}
}
#[test]
fn every_framework_path_goes_through_a_private_module() {
for model in [disposition(), vendored()] {
assert!(
ill_formed_shelf_paths(&model).is_empty(),
"{:?}",
ill_formed_shelf_paths(&model)
);
}
let mut elsewhere = disposition();
elsewhere.krate = syn::parse_quote!(core);
assert!(!ill_formed_shelf_paths(&elsewhere).is_empty());
}
fn ill_formed_shelf_paths(model: &FlagsModel) -> Vec<String> {
let root = model
.krate
.segments
.last()
.expect("a crate path has a last segment")
.ident
.to_string();
let tokens = flat_tokens(model.emit());
let colon = |at: usize| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == ':');
let ident = |at: usize| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Ident(_)));
let named = |at: usize, name: &str| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Ident(id)) if id == name);
let well_formed = |at: usize| {
if !(colon(at + 1) && colon(at + 2) && named(at + 3, "__private")) {
return false;
}
let mut segments = 0;
let mut cursor = at + 3;
while colon(cursor + 1) && colon(cursor + 2) && ident(cursor + 3) {
segments += 1;
cursor += 3;
}
segments >= 2
};
(0..tokens.len())
.filter(|at| named(*at, &root))
.filter(|at| !well_formed(*at))
.map(|at| {
tokens[at..(at + 10).min(tokens.len())]
.iter()
.map(ToString::to_string)
.collect()
})
.collect()
}
fn flat_tokens(stream: proc_macro2::TokenStream) -> Vec<proc_macro2::TokenTree> {
stream
.into_iter()
.flat_map(|token| match token {
proc_macro2::TokenTree::Group(group) => flat_tokens(group.stream()),
other => vec![other],
})
.collect()
}
#[test]
fn the_shelf_follows_a_declared_crate_path() {
let rendered = rendered(&vendored());
assert!(
rendered.contains("vendored::ingraph::__private::bitflags::bitflags!"),
"{rendered}"
);
assert!(
rendered.contains("impl vendored::ingraph::__private::flags::FlagsValue for Disposition"),
"{rendered}"
);
assert_eq!(
rendered.matches("vendored::ingraph::__private").count(),
rendered.matches("::ingraph::__private").count(),
"no shelf path is rooted anywhere else: {rendered}"
);
}