use ingraph_codegen::prefix::EmissionPrefix;
use ingraph_codegen::{
interface::{InterfaceDatabase, InterfaceField, InterfaceModel, Pin, Tier},
model::{AliasOptions, DatabaseKind, FrameworkMarker, Label, Marker},
union::UnionMember,
unit,
};
use quote::quote;
const THE_UNITS_COMPARISON: &str = include_str!("the_third_fold/the_units_comparison.rs");
const THE_INTERFACES_COMPARISON: &str = include_str!("the_third_fold/the_interfaces_comparison.rs");
#[test]
fn the_units_comparison_is_the_byte_it_was() {
assert_eq!(render(the_units_face()), THE_UNITS_COMPARISON);
}
#[test]
fn the_interfaces_comparison_is_the_byte_it_was() {
assert_eq!(render(the_interfaces_face()), THE_INTERFACES_COMPARISON);
}
#[test]
fn the_interfaces_comparison_speaks_the_units_sentences() {
for sentence in SHAPE_SENTENCES {
assert!(
THE_UNITS_COMPARISON.contains(sentence),
"the shared emitter says it: {sentence}"
);
assert!(
THE_INTERFACES_COMPARISON.contains(sentence),
"and so does the interface, which is now the same emitter: {sentence}"
);
}
assert!(THE_UNITS_COMPARISON.contains(
"A predicate over a [`Cue`]'s columns, in the types this database stores — each field"
));
assert!(THE_INTERFACES_COMPARISON.contains(
"A predicate over a [`Screened`]'s columns, in the types this database stores — each field"
));
assert!(
THE_UNITS_COMPARISON.contains("The predicate on the `slate` column, in the type this database")
);
assert!(
THE_INTERFACES_COMPARISON
.contains("The predicate on the shared `slate` column, in the type this database")
);
}
#[test]
fn the_interfaces_own_paragraph_survives_and_the_shape_never_learned_it() {
assert!(
THE_INTERFACES_COMPARISON
.contains("Written in the INTERFACE's vocabulary and lowered ONCE, above the union"),
"the contract's own paragraph is still on its face"
);
assert!(
!THE_UNITS_COMPARISON.contains("above the union"),
"and the shape knows nothing about a union — the paragraph is the caller's"
);
}
const SHAPE_SENTENCES: [&str; 3] = [
"Construct a predicate from one comparison per column, in the order this database stores them.",
"How many conjuncts this predicate renders — the sum over its columns, since each is a comparison \
of its own.",
"Render every column's conjuncts into `builder`, each at the same row and one segment below the \
address this predicate was applied at.",
];
#[test]
fn the_struct_walks_stored_and_the_lowering_walks_projected() {
let held = struct_members(&the_interfaces_face());
let lowered = lowered_members(&the_interfaces_face());
let model = reeled();
let collected: Vec<String> = model
.collected()
.map(|field| field.name.to_string())
.collect();
assert_eq!(
held,
["slate", "marks"],
"the struct holds one field per STORED column, collections included"
);
assert_eq!(
lowered,
["slate"],
"and the lowering renders the PROJECTED ones alone"
);
assert!(
lowered.iter().all(|member| held.contains(member)),
"the lowering's list is a subset of the struct's, never a list of its own"
);
let difference: Vec<String> = held
.iter()
.filter(|member| !lowered.contains(member))
.cloned()
.collect();
assert_eq!(
difference, collected,
"and the difference is exactly what the model calls collected"
);
}
fn reeled() -> InterfaceModel {
InterfaceModel {
prefix: EmissionPrefix::default(),
vis: syn::parse_quote!(pub),
name: ident("Screened"),
krate: syn::parse_quote!(::ingraph),
members: vec![
UnionMember {
ident: ident("Reel"),
ty: syn::parse_quote!(Reel),
},
UnionMember {
ident: ident("Tape"),
ty: syn::parse_quote!(Tape),
},
],
fields: vec![
InterfaceField {
name: ident("slate"),
ty: syn::parse_quote!(String),
tier: Tier::Stored,
marker: None,
copy: false,
pins: Vec::new(),
wire: None,
operands: Vec::new(),
members: Vec::new(),
},
InterfaceField {
name: ident("marks"),
ty: syn::parse_quote!(Vec<u64>),
tier: Tier::Stored,
marker: Some(Marker::Framework(FrameworkMarker {
label: Label::List,
element: Some(Label::Scalar),
})),
copy: false,
pins: vec![Pin {
kind: DatabaseKind::Sqlite,
stored: Some(syn::parse_quote!(i64)),
}],
wire: None,
operands: Vec::new(),
members: Vec::new(),
},
],
error: None,
computed_error: None,
persist: vec![InterfaceDatabase {
kind: DatabaseKind::Sqlite,
aliases: AliasOptions::default(),
}],
errors: Vec::new(),
operand_errors: Vec::new(),
plural: None,
connection: None,
edge: None,
}
}
fn the_units_face() -> Vec<syn::Item> {
let vis: syn::Visibility = syn::parse_quote!(pub);
let db = ident("__INGRAPH_DB__");
let name = ident("CueSqliteComparison");
let crossings = quote! {
__INGRAPH_DB__: ::ingraph::__private::comparison::Backend,
::ingraph::__private::graphql::TextFilter<String>:
::ingraph::__private::comparison::ToDatabaseComparison<String, __INGRAPH_DB__>,
::ingraph::__private::graphql::ScalarFilter<i64>:
::ingraph::__private::comparison::ToDatabaseComparison<i64, __INGRAPH_DB__>,
};
let rows = vec![
unit::ComparisonColumn {
member: ident("slate"),
name: "`slate` column".to_owned(),
gate: proc_macro2::TokenStream::new(),
held: quote!(
<::ingraph::__private::graphql::TextFilter<String>
as ::ingraph::__private::comparison::ToDatabaseComparison<
String,
__INGRAPH_DB__,
>>::Comparison
),
},
unit::ComparisonColumn {
member: ident("marks"),
name: "`marks` column".to_owned(),
gate: proc_macro2::TokenStream::new(),
held: quote!(
<::ingraph::__private::graphql::ScalarFilter<i64>
as ::ingraph::__private::comparison::ToDatabaseComparison<
i64,
__INGRAPH_DB__,
>>::Comparison
),
},
];
let header = unit::UnitHeader {
vis: &vis,
name: name.clone(),
subject: "[`Cue`]".to_owned(),
note: None,
};
let (declaration, methods) = unit::comparison(&header, &db, &crossings, &rows);
let seats = unit::LoweringSeats {
backend: quote!(::ingraph::__private::comparison::Backend),
complex: quote!(::ingraph::__private::comparison::ComplexComparison),
frame: quote!(::ingraph::__private::comparison::Frame),
at: quote!(::ingraph::__private::comparison::At),
field_name: quote!(::ingraph::__private::field::FieldName),
};
let lowered = vec![unit::LoweringColumn {
member: ident("slate"),
rendered: "slate".to_owned(),
flatten: false,
through: None,
gate: proc_macro2::TokenStream::new(),
}];
let lowering = unit::comparison_lowering(&name, &db, &crossings, &seats, &lowered);
let file: syn::File =
syn::parse2(quote! { #declaration #methods #lowering }).expect("an emission is a file");
file.items
}
fn the_interfaces_face() -> Vec<syn::Item> {
let file: syn::File = syn::parse2(reeled().emit()).expect("the expansion is a file");
let mut found = Vec::new();
face(&file.items, "ScreenedSqliteComparison", &mut found);
assert_eq!(
found.len(),
3,
"a comparison face is its struct, its methods and its lowering"
);
found
}
fn struct_members(items: &[syn::Item]) -> Vec<String> {
items
.iter()
.find_map(|item| match item {
syn::Item::Struct(declared) => Some(declared),
_ => None,
})
.expect("the face declares its struct")
.fields
.iter()
.filter_map(|field| field.ident.as_ref().map(ToString::to_string))
.collect()
}
fn lowered_members(items: &[syn::Item]) -> Vec<String> {
let block = items
.iter()
.find_map(|item| match item {
syn::Item::Impl(block) if trait_of(block) == "ComplexComparison" => Some(block),
_ => None,
})
.expect("the face declares its lowering");
let conjuncts = block
.items
.iter()
.find_map(|member| match member {
syn::ImplItem::Fn(function) if function.sig.ident == "conjuncts" => Some(function),
_ => None,
})
.expect("a lowering counts its conjuncts");
tight(conjuncts)
.match_indices("(&self.")
.filter_map(|(at, _)| {
let rest = &tight(conjuncts)[at + "(&self.".len()..];
rest.split(')').next().map(ToOwned::to_owned)
})
.collect()
}
fn ident(name: &str) -> syn::Ident {
syn::Ident::new(name, proc_macro2::Span::call_site())
}
fn tight(tokens: impl quote::ToTokens) -> String {
quote::ToTokens::to_token_stream(&tokens)
.to_string()
.replace(' ', "")
}
fn render(items: Vec<syn::Item>) -> String {
prettyplease::unparse(&syn::File {
shebang: None,
frontmatter: None,
attrs: Vec::new(),
items,
})
}
fn trait_of(block: &syn::ItemImpl) -> String {
block.trait_.as_ref().map_or_else(String::new, |(path, _)| {
path
.segments
.last()
.map_or_else(String::new, |segment| segment.ident.to_string())
})
}
fn face(items: &[syn::Item], name: &str, found: &mut Vec<syn::Item>) {
for item in items {
match item {
syn::Item::Struct(declared) if declared.ident == name => found.push(item.clone()),
syn::Item::Impl(block)
if base_of(&block.self_ty) == name
&& (block.trait_.is_none() || trait_of(block) == "ComplexComparison") =>
{
found.push(item.clone());
}
syn::Item::Const(constant) => {
if let syn::Expr::Block(block) = &*constant.expr {
let nested: Vec<syn::Item> = block
.block
.stmts
.iter()
.filter_map(|statement| match statement {
syn::Stmt::Item(item) => Some(item.clone()),
_ => None,
})
.collect();
face(&nested, name, found);
}
}
_ => {}
}
}
}
fn base_of(ty: &syn::Type) -> String {
match ty {
syn::Type::Path(path) => path
.path
.segments
.last()
.map_or_else(String::new, |segment| segment.ident.to_string()),
_ => String::new(),
}
}